From b7f68633f75d14de4ad4b06eec29680d56fed145 Mon Sep 17 00:00:00 2001 From: pieroviano Date: Thu, 15 Oct 2026 05:43:52 +0300 Subject: [PATCH 001/498] Upgraded to .Net 10 --- .editorconfig | 36 ++- .vscode/launch.json | 2 +- CONTRIBUTING.md | 15 + Dockerfile | 4 +- build.ps1 | 286 +++++++++++++++++ nuget.config | 8 +- readme.md | 88 ++++-- .../BaGet.Protocol.Samples.Tests.csproj | 11 +- .../BaGetWebApplication.csproj | 3 +- service/.gitignore | 289 ++++++++++++++++++ service/BaGetService.sln | 43 +++ service/BaGetService/BaGetService.csproj | 42 +++ service/BaGetService/NuGet/NuGetHelper.cs | 55 ++++ service/BaGetService/Program.cs | 33 ++ service/BaGetService/Runtime/BaGetRunner.cs | 36 +++ service/BaGetService/Runtime/Configuration.cs | 25 ++ service/BaGetService/Service/BaGetService.cs | 39 +++ service/BaGetService/Service/ServiceHelper.cs | 66 ++++ .../BaGetService/appsettings.Development.json | 15 + service/BaGetService/appsettings.json | 63 ++++ service/BaGetService/favicon.ico | Bin 0 -> 15086 bytes service/nuget.config | 8 + src/BaGet.Aliyun/BaGet.Aliyun.csproj | 8 +- src/BaGet.Aws/BaGet.Aws.csproj | 14 +- src/BaGet.Azure/AzureApplicationExtensions.cs | 6 +- src/BaGet.Azure/BaGet.Azure.csproj | 21 +- .../Extensions/StorageExceptionExtensions.cs | 2 +- src/BaGet.Azure/Storage/BlobStorageService.cs | 4 +- src/BaGet.Core/BaGet.Core.csproj | 8 +- .../Metadata/RegistrationBuilder.cs | 2 +- src/BaGet.Core/PackageDatabase.cs | 3 + .../BaGet.Database.MySql.csproj | 8 +- .../MySqlApplicationExtensions.cs | 5 +- src/BaGet.Database.MySql/MySqlContext.cs | 2 +- .../BaGet.Database.PostgreSql.csproj | 8 +- .../BaGet.Database.SqlServer.csproj | 8 +- .../BaGet.Database.Sqlite.csproj | 8 +- src/BaGet.Gcp/BaGet.Gcp.csproj | 8 +- src/BaGet.Protocol/BaGet.Protocol.csproj | 7 +- src/BaGet.Web/BaGet.Web.csproj | 12 +- src/BaGet.Web/BaGetEndpointBuilder.cs | 1 + .../IServiceCollectionExtensions.cs | 11 +- src/BaGet.Web/NavLinkTagHelper.cs | 17 +- src/BaGet.Web/Pages/Index.cshtml | 5 +- src/BaGet.Web/Pages/Package.cshtml | 2 +- src/BaGet.Web/Pages/Shared/_Layout.cshtml | 2 +- src/BaGet/BaGet.csproj | 13 +- src/BaGet/Startup.cs | 4 +- src/BaGet/appsettings.json | 9 + src/BaGet/libman.json | 10 + src/Directory.Build.props | 32 +- .../BaGet.Core.Tests/BaGet.Core.Tests.csproj | 15 +- .../BaGet.Protocol.Tests.csproj | 15 +- .../BaGet.Protocol.Tests/TestData.Designer.cs | 2 +- tests/BaGet.Protocol.Tests/TestData.resx | 50 +-- tests/BaGet.Tests/BaGet.Tests.csproj | 31 +- .../BaGet.Tests/TestData/TestData.Designer.cs | 2 +- tests/BaGet.Web.Tests/BaGet.Web.Tests.csproj | 18 +- .../Pages/PackageModelFacts.cs | 4 +- tests/Directory.Build.props | 18 +- 60 files changed, 1421 insertions(+), 141 deletions(-) create mode 100644 CONTRIBUTING.md create mode 100644 build.ps1 mode change 100644 => 120000 nuget.config create mode 100644 service/.gitignore create mode 100644 service/BaGetService.sln create mode 100644 service/BaGetService/BaGetService.csproj create mode 100644 service/BaGetService/NuGet/NuGetHelper.cs create mode 100644 service/BaGetService/Program.cs create mode 100644 service/BaGetService/Runtime/BaGetRunner.cs create mode 100644 service/BaGetService/Runtime/Configuration.cs create mode 100644 service/BaGetService/Service/BaGetService.cs create mode 100644 service/BaGetService/Service/ServiceHelper.cs create mode 100644 service/BaGetService/appsettings.Development.json create mode 100644 service/BaGetService/appsettings.json create mode 100644 service/BaGetService/favicon.ico create mode 100644 service/nuget.config create mode 100644 src/BaGet/libman.json diff --git a/.editorconfig b/.editorconfig index df9dfe6ff..3879e6f27 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,6 +6,25 @@ indent_style = space charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion [*.{htm,html,js,ts,tsx,css,sass,scss,less,svg,vue}] indent_size = 2 @@ -53,7 +72,7 @@ dotnet_naming_style.pascal_case_style.capitalization = pascal_case # Use PascalCase for constant fields dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields -dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style +dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style dotnet_naming_symbols.constant_fields.applicable_kinds = field dotnet_naming_symbols.constant_fields.applicable_accessibilities = * dotnet_naming_symbols.constant_fields.required_modifiers = const @@ -94,3 +113,18 @@ csharp_space_between_method_call_empty_parameter_list_parentheses = false # Wrapping preferences csharp_preserve_single_line_statements = true csharp_preserve_single_line_blocks = true +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_prefer_braces = true:silent +csharp_style_namespace_declarations = block_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = true:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent diff --git a/.vscode/launch.json b/.vscode/launch.json index ccbe25d9e..63972bf4d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,7 +10,7 @@ "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/src/BaGet/bin/Debug/netcoreapp3.1/BaGet.dll", + "program": "${workspaceFolder}/src/BaGet/bin/Debug/net10.0/BaGet.dll", "args": [], "cwd": "${workspaceFolder}/src/BaGet", "stopAtEntry": false, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..f12e5d009 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,15 @@ +## Contribute + +Please read the [code of conduct] before contributing. + +If you want to run from BaGet's source code: + +1. Install the [.NET SDK] and [Node.js] +2. Run `git clone https://github.com/loic-sharma/BaGet.git` +3. Navigate to `./BaGet/src/BaGet` +4. Start the service with `dotnet run` +5. Open the URL `http://localhost:5000/v3/index.json` in your browser + +[Code of conduct]: CODE_OF_CONDUCT.md +[.NET SDK]: https://www.microsoft.com/net/download +[Node.js]: https://nodejs.org/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index ee8ba3c5e..881ccea92 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base WORKDIR /app EXPOSE 80 -FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY /src . RUN dotnet restore BaGet diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 000000000..8bb804154 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,286 @@ +param( + [switch]$Run, # Run the solution after building (starts BaGet service) + [switch]$Publish # Clean, restore, build (Release), and publish the solution +) + +# Script configuration - script is in root, solution is in root +# Usage: +# .\build.ps1 - Clean, restore, and build (Debug) +# .\build.ps1 -Run - Clean, restore, build (Debug), and run BaGet service +# .\build.ps1 -Publish - Clean, restore, build (Release), and publish to Publish folder +$SolutionPath = Join-Path $PSScriptRoot "BaGet.sln" +$ProjectPath = Join-Path $PSScriptRoot "src\BaGet\BaGet.csproj" +$PublishPath = Join-Path $PSScriptRoot "Publish" + +# Determine build configuration +$Configuration = if ($Publish) { "Release" } else { "Debug" } + +Write-Host "========================================" -ForegroundColor Cyan +Write-Host "BaGet Build Script" -ForegroundColor Cyan +Write-Host "========================================" -ForegroundColor Cyan +Write-Host "" + +# Function to check if a process is running +function Test-ProcessRunning { + param([string]$ProcessName) + $processes = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue + return $null -ne $processes -and $processes.Count -gt 0 +} + +# Function to close processes +function Stop-ProjectProcesses { + Write-Host "Checking for running processes..." -ForegroundColor Yellow + + $processesToCheck = @( + "dotnet" + ) + + $foundProcesses = $false + + foreach ($processName in $processesToCheck) { + if (Test-ProcessRunning $processName) { + $foundProcesses = $true + try { + Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue + Start-Sleep -Seconds 2 + } + catch { + Write-Host " Warning: Could not close all $processName processes: $_" -ForegroundColor Red + } + } + } + + # Check for processes using files in the solution directory + Write-Host "Checking for processes locking solution files..." -ForegroundColor Yellow + try { + $solutionDir = Split-Path $SolutionPath -Parent + $lockedFiles = Get-ChildItem -Path $solutionDir -Recurse -File -ErrorAction SilentlyContinue | + Where-Object { + try { + [System.IO.File]::OpenWrite($_.FullName).Close() + $false + } + catch { + $true + } + } + + if ($lockedFiles) { + Write-Host " Warning: Some files may be locked by other processes." -ForegroundColor Yellow + } + } + catch { + # Ignore errors in file locking check + } + + if (-not $foundProcesses) { + Write-Host "No running processes found." -ForegroundColor Green + } + + Write-Host "" +} + +# Step 1: Close running processes +Stop-ProjectProcesses + +# Step 2: Clean the solution +Write-Host "Cleaning solution..." -ForegroundColor Cyan +try { + # Suppress verbose output from dotnet clean + $originalTerminalLogger = $env:MSBUILDTERMINALLOGGER + $env:MSBUILDTERMINALLOGGER = "off" + + $processInfo = New-Object System.Diagnostics.ProcessStartInfo + $processInfo.FileName = "dotnet" + $processInfo.Arguments = "clean `"$SolutionPath`" --verbosity quiet /nologo /noconsolelogger" + $processInfo.UseShellExecute = $false + $processInfo.RedirectStandardOutput = $true + $processInfo.RedirectStandardError = $true + $processInfo.CreateNoWindow = $true + $processInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden + + $process = New-Object System.Diagnostics.Process + $process.StartInfo = $processInfo + $null = $process.Start() + + # Read and discard all output + $null = $process.StandardOutput.ReadToEnd() + $null = $process.StandardError.ReadToEnd() + $null = $process.WaitForExit() + + # Restore environment + if ($originalTerminalLogger) { + $env:MSBUILDTERMINALLOGGER = $originalTerminalLogger + } else { + Remove-Item Env:\MSBUILDTERMINALLOGGER -ErrorAction SilentlyContinue + } + + if ($process.ExitCode -eq 0) { + Write-Host " Solution cleaned successfully." -ForegroundColor Green + } + else { + Write-Host " Warning: Clean completed with exit code $($process.ExitCode)" -ForegroundColor Yellow + } +} +catch { + Write-Host " Error cleaning solution: $_" -ForegroundColor Red +} +Write-Host "" + +# Step 3: Remove bin and obj directories +Write-Host "Removing bin and obj directories..." -ForegroundColor Cyan +$solutionDir = Split-Path $SolutionPath -Parent +$removedCount = 0 + +try { + # Remove bin directories + $binDirs = Get-ChildItem -Path $solutionDir -Directory -Recurse -Filter "bin" -ErrorAction SilentlyContinue + foreach ($dir in $binDirs) { + try { + Remove-Item -Path $dir.FullName -Recurse -Force -ErrorAction Stop + $removedCount++ + } + catch { + Write-Host " Warning: Could not remove $($dir.FullName): $_" -ForegroundColor Yellow + } + } + + # Remove obj directories + $objDirs = Get-ChildItem -Path $solutionDir -Directory -Recurse -Filter "obj" -ErrorAction SilentlyContinue + foreach ($dir in $objDirs) { + try { + Remove-Item -Path $dir.FullName -Recurse -Force -ErrorAction Stop + $removedCount++ + } + catch { + Write-Host " Warning: Could not remove $($dir.FullName): $_" -ForegroundColor Yellow + } + } + + if (Test-Path "$($solutionDir)\packages") { + Remove-Item -Path "$($solutionDir)\packages" -Recurse -Force -ErrorAction Stop + $removedCount++ + } + + if (Test-Path $PublishPath) { + Remove-Item -Path $PublishPath -Recurse -Force -ErrorAction Stop + $removedCount++ + } + + if ($removedCount -gt 0) { + Write-Host " Removed $removedCount directories." -ForegroundColor Green + } + else { + Write-Host " No bin/obj directories found to remove." -ForegroundColor Green + } +} +catch { + Write-Host " Error removing directories: $_" -ForegroundColor Red +} +Write-Host "" + +# Step 4: Restore NuGet packages +Write-Host "Restoring NuGet packages..." -ForegroundColor Cyan +try { + $restoreResult = & dotnet restore $SolutionPath --verbosity quiet + if ($LASTEXITCODE -eq 0) { + Write-Host " NuGet packages restored successfully." -ForegroundColor Green + } + else { + Write-Host " Error: NuGet restore failed with exit code $LASTEXITCODE" -ForegroundColor Red + exit $LASTEXITCODE + } +} +catch { + Write-Host " Error restoring packages: $_" -ForegroundColor Red + exit 1 +} +Write-Host "" + +# Step 5: Build the solution +Write-Host "Building solution..." -ForegroundColor Cyan +try { + $buildResult = & dotnet build $SolutionPath --configuration $Configuration --no-restore --verbosity quiet + if ($LASTEXITCODE -eq 0) { + Write-Host " Solution built successfully!" -ForegroundColor Green + } + else { + Write-Host " Error: Build failed with exit code $LASTEXITCODE" -ForegroundColor Red + exit $LASTEXITCODE + } +} +catch { + Write-Host " Error building solution: $_" -ForegroundColor Red + exit 1 +} +Write-Host "" + +# Step 6: Publish the solution (if requested) +if ($Publish) { + Write-Host "Publishing solution..." -ForegroundColor Cyan + + # Remove existing publish directory if it exists + if (Test-Path $PublishPath) { + Write-Host " Removing existing publish directory..." -ForegroundColor Yellow + try { + Remove-Item -Path $PublishPath -Recurse -Force -ErrorAction Stop + Write-Host " Existing publish directory removed." -ForegroundColor Green + } + catch { + Write-Host " Warning: Could not remove existing publish directory: $_" -ForegroundColor Yellow + } + } + + try { + Write-Host " Publishing to: $PublishPath" -ForegroundColor Yellow + + # Ensure the publish directory exists + $null = New-Item -ItemType Directory -Path $PublishPath -Force -ErrorAction SilentlyContinue + + # Publish using dotnet publish + Write-Host " Publishing BaGet project..." -ForegroundColor Yellow + $publishResult = & dotnet publish $ProjectPath --configuration $Configuration --output $PublishPath --no-build + if ($LASTEXITCODE -eq 0) { + Write-Host " Solution published successfully!" -ForegroundColor Green + Write-Host " Published files are located at: $PublishPath" -ForegroundColor Green + } + else { + Write-Host " Error: Publish failed with exit code $LASTEXITCODE" -ForegroundColor Red + exit $LASTEXITCODE + } + } + catch { + Write-Host " Error publishing solution: $_" -ForegroundColor Red + Write-Host " Stack trace: $($_.ScriptStackTrace)" -ForegroundColor Red + exit 1 + } + Write-Host "" +} + +# Run the solution (if requested) +if ($Run) { + Write-Host "Running solution..." -ForegroundColor Cyan + + Write-Host " Starting BaGet service..." -ForegroundColor Yellow + Write-Host " Navigate to http://localhost:50561/v3/index.json in your browser" -ForegroundColor Cyan + Write-Host " Press Ctrl+C to stop the service" -ForegroundColor Gray + Write-Host "" + + try { + $projectDir = Split-Path $ProjectPath -Parent + Set-Location -Path $projectDir + & dotnet run --urls "http://localhost:50561" --verbosity quiet + } + catch { + Write-Host " Error running solution: $_" -ForegroundColor Red + exit 1 + } + finally { + Set-Location -Path $PSScriptRoot + } +} + +Write-Host "" +Write-Host "========================================" -ForegroundColor Cyan +Write-Host "Build script completed!" -ForegroundColor Cyan +Write-Host "========================================" -ForegroundColor Cyan diff --git a/nuget.config b/nuget.config deleted file mode 100644 index fbcef1011..000000000 --- a/nuget.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/nuget.config b/nuget.config new file mode 120000 index 000000000..687c701b7 --- /dev/null +++ b/nuget.config @@ -0,0 +1 @@ +d:/CommonLibrary/NuGet.Config \ No newline at end of file diff --git a/readme.md b/readme.md index a3d5c0016..caf62f392 100644 --- a/readme.md +++ b/readme.md @@ -1,8 +1,8 @@ # BaGet :baguette_bread: -![Build status](https://img.shields.io/github/workflow/status/loic-sharma/BaGet/Build/main) [![Discord](https://img.shields.io/discord/889377258068930591)](https://discord.gg/MWbhpf66mk) [![Twitter](https://img.shields.io/twitter/follow/bagetapp?label=Follow)](https://twitter.com/bagetapp) +![Build status] [![Discord][Discord image]][Discord link] [![Twitter][Twitter image]][Twitter link] -A lightweight [NuGet](https://docs.microsoft.com/en-us/nuget/what-is-nuget) and [Symbol](https://docs.microsoft.com/en-us/windows/desktop/debug/symbol-servers-and-symbol-stores) server. +A lightweight [NuGet] and [symbol] server.

@@ -10,30 +10,84 @@ A lightweight [NuGet](https://docs.microsoft.com/en-us/nuget/what-is-nuget) and ## Getting Started -1. Install [.NET Core SDK](https://www.microsoft.com/net/download) -2. Download and extract [BaGet's latest release](https://github.com/loic-sharma/BaGet/releases) +1. Install the [.NET SDK] +2. Download and extract [BaGet's latest release] 3. Start the service with `dotnet BaGet.dll` 4. Browse `http://localhost:5000/` in your browser -For more information, please refer to [our documentation](https://loic-sharma.github.io/BaGet/). +For more information, please refer to the [documentation]. ## Features -* Cross-platform -* [Dockerized](https://loic-sharma.github.io/BaGet/#running-baget-on-docker) -* [Cloud ready](https://loic-sharma.github.io/BaGet/cloud/azure/) -* [Supports read-through caching](https://loic-sharma.github.io/BaGet/configuration/#enabling-read-through-caching) -* Can index the entirety of nuget.org. See [this documentation](https://loic-sharma.github.io/BaGet/import/nugetorg/#mirroring) -* Coming soon: Supports [private feeds](https://loic-sharma.github.io/BaGet/private-feeds/) -* And more! +* **Cross-platform**: runs on Windows, macOS, and Linux! +* **Cloud native**: supports [Docker], [Azure], [AWS], [Google Cloud], [Alibaba Cloud] +* **Offline support**: [mirror a NuGet server] to speed up builds and enable offline downloads Stay tuned, more features are planned! -## Develop +[Build status]: https://img.shields.io/github/actions/workflow/status/loic-sharma/BaGet/.github/workflows/main.yml +[Discord image]: https://img.shields.io/discord/889377258068930591 +[Discord link]: https://discord.gg/MWbhpf66mk +[Twitter image]: https://img.shields.io/twitter/follow/bagetapp?label=Follow +[Twitter link]: https://twitter.com/bagetapp + +[NuGet]: https://learn.microsoft.com/nuget/what-is-nuget +[symbol]: https://docs.microsoft.com/en-us/windows/desktop/debug/symbol-servers-and-symbol-stores +[.NET SDK]: https://www.microsoft.com/net/download +[Node.js]: https://nodejs.org/ + +[BaGet's latest release]: https://github.com/loic-sharma/BaGet/releases + +[Documentation]: https://loic-sharma.github.io/BaGet/ +[Docker]: https://loic-sharma.github.io/BaGet/installation/docker/ +[Azure]: https://loic-sharma.github.io/BaGet/installation/azure/ +[AWS]: https://loic-sharma.github.io/BaGet/installation/aws/ +[Google Cloud]: https://loic-sharma.github.io/BaGet/installation/gcp/ +[Alibaba Cloud]: https://loic-sharma.github.io/BaGet/installation/aliyun/ + +1. Install the [.NET 10 SDK](https://www.microsoft.com/net/download) -1. Install [.NET Core SDK](https://www.microsoft.com/net/download) and [Node.js](https://nodejs.org/) 2. Run `git clone https://github.com/loic-sharma/BaGet.git` -3. Navigate to `.\BaGet\src\BaGet` -4. Navigate to `..\BaGet` -5. Start the service with `dotnet run` + +3. Navigate to the BaGet directory + +4. Run the build script: + ```powershell + .\build.ps1 + ``` + + Or manually clean, restore, and build: + ```bash + dotnet clean BaGet.sln + dotnet restore BaGet.sln + dotnet build BaGet.sln + ``` + +5. Navigate to `.\src\BaGet` and start the service: + ```bash + dotnet run + ``` + 6. Open the URL `http://localhost:5000/v3/index.json` in your browser + +[Build status]: https://img.shields.io/github/actions/workflow/status/loic-sharma/BaGet/.github/workflows/main.yml +[Discord image]: https://img.shields.io/discord/889377258068930591 +[Discord link]: https://discord.gg/MWbhpf66mk +[Twitter image]: https://img.shields.io/twitter/follow/bagetapp?label=Follow +[Twitter link]: https://twitter.com/bagetapp + +[NuGet]: https://learn.microsoft.com/nuget/what-is-nuget +[symbol]: https://docs.microsoft.com/en-us/windows/desktop/debug/symbol-servers-and-symbol-stores +[.NET SDK]: https://www.microsoft.com/net/download +[Node.js]: https://nodejs.org/ + +[BaGet's latest release]: https://github.com/loic-sharma/BaGet/releases + +[Documentation]: https://loic-sharma.github.io/BaGet/ +[Docker]: https://loic-sharma.github.io/BaGet/installation/docker/ +[Azure]: https://loic-sharma.github.io/BaGet/installation/azure/ +[AWS]: https://loic-sharma.github.io/BaGet/installation/aws/ +[Google Cloud]: https://loic-sharma.github.io/BaGet/installation/gcp/ +[Alibaba Cloud]: https://loic-sharma.github.io/BaGet/installation/aliyun/ + +[Mirror a NuGet server]: https://loic-sharma.github.io/BaGet/configuration/#enable-read-through-caching \ No newline at end of file diff --git a/samples/BaGet.Protocol.Samples.Tests/BaGet.Protocol.Samples.Tests.csproj b/samples/BaGet.Protocol.Samples.Tests/BaGet.Protocol.Samples.Tests.csproj index 51c3b7967..ec9d2abbd 100644 --- a/samples/BaGet.Protocol.Samples.Tests/BaGet.Protocol.Samples.Tests.csproj +++ b/samples/BaGet.Protocol.Samples.Tests/BaGet.Protocol.Samples.Tests.csproj @@ -1,21 +1,20 @@ - netcoreapp3.1 + net10.0 false IDE0007 - - - - + + + + all runtime; build; native; contentfiles; analyzers - diff --git a/samples/BaGetWebApplication/BaGetWebApplication.csproj b/samples/BaGetWebApplication/BaGetWebApplication.csproj index 3123a668b..a93905b10 100644 --- a/samples/BaGetWebApplication/BaGetWebApplication.csproj +++ b/samples/BaGetWebApplication/BaGetWebApplication.csproj @@ -1,10 +1,11 @@ - netcoreapp3.1 + net10.0 + diff --git a/service/.gitignore b/service/.gitignore new file mode 100644 index 000000000..cf93673c3 --- /dev/null +++ b/service/.gitignore @@ -0,0 +1,289 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Typescript v1 declaration files +typings/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs +obfuscar.xml \ No newline at end of file diff --git a/service/BaGetService.sln b/service/BaGetService.sln new file mode 100644 index 000000000..d0a62bfc7 --- /dev/null +++ b/service/BaGetService.sln @@ -0,0 +1,43 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33110.190 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaGetService", "BaGetService\BaGetService.csproj", "{66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}" +EndProject +Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "BaGetService_Setup", "BaGetService_Setup\BaGetService_Setup.wixproj", "{B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}" + ProjectSection(ProjectDependencies) = postProject + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A} = {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}.Debug|x64.ActiveCfg = Debug|Any CPU + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}.Debug|x64.Build.0 = Debug|Any CPU + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}.Release|Any CPU.Build.0 = Release|Any CPU + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}.Release|x64.ActiveCfg = Release|Any CPU + {66A9B7B0-4AF8-452E-BF50-B4100EBCBB6A}.Release|x64.Build.0 = Release|Any CPU + {B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}.Debug|Any CPU.ActiveCfg = Debug|x64 + {B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}.Debug|Any CPU.Build.0 = Debug|x64 + {B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}.Debug|x64.ActiveCfg = Debug|x64 + {B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}.Debug|x64.Build.0 = Debug|x64 + {B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}.Release|Any CPU.ActiveCfg = Release|x64 + {B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}.Release|Any CPU.Build.0 = Release|x64 + {B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}.Release|x64.ActiveCfg = Release|x64 + {B16C7D39-7168-7AFD-0DCB-D14601BBC0B5}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2493BF23-F33C-44FF-B5E7-C9419966F674} + EndGlobalSection +EndGlobal diff --git a/service/BaGetService/BaGetService.csproj b/service/BaGetService/BaGetService.csproj new file mode 100644 index 000000000..9a364c02d --- /dev/null +++ b/service/BaGetService/BaGetService.csproj @@ -0,0 +1,42 @@ + + + + net7.0-windows + enable + true + BaGet.Service + exe + true + win-x64 + x64 + 0.1.0-prerelease + Loic Sharma + bin\ + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + diff --git a/service/BaGetService/NuGet/NuGetHelper.cs b/service/BaGetService/NuGet/NuGetHelper.cs new file mode 100644 index 000000000..84d63b344 --- /dev/null +++ b/service/BaGetService/NuGet/NuGetHelper.cs @@ -0,0 +1,55 @@ +using System.Diagnostics; + +namespace BaGet.Service.NuGet +{ + public static class NuGetHelper + { + + public static async Task Push(string directoryName) + { + try + { + if (!Directory.Exists(directoryName)) + { + Console.WriteLine($"The directory '{directoryName}' does not exists."); + Environment.Exit(-1); + } + + var builder = new ConfigurationBuilder(); + builder + .SetBasePath(Path.GetDirectoryName(typeof(Program).Assembly.Location)!) + .AddJsonFile("appsettings.json", false); + + var configuration = builder.Build(); + var section = configuration.GetSection("ApiKey"); + + var apikey = section.Value; + + foreach (var file in Directory.GetFiles(directoryName, "*.*pkg")) + { + try + { + var dotnetExe = "dotnet.exe"; + var arguments = $"nuget push -s http://localhost:6060/v3/index.json --api-key {apikey} {file}"; + Console.WriteLine($"Running:\n]n{dotnetExe} {arguments}\n\n"); + var process = Process.Start(dotnetExe, + arguments); + await process.WaitForExitAsync(); + } + catch (Exception e) + { + Console.WriteLine(e); + Console.Read(); + } + } + } + catch (Exception e) + { + Console.WriteLine(e); + Console.Read(); + } + + Environment.Exit(0); + } + } +} diff --git a/service/BaGetService/Program.cs b/service/BaGetService/Program.cs new file mode 100644 index 000000000..4d22e1268 --- /dev/null +++ b/service/BaGetService/Program.cs @@ -0,0 +1,33 @@ +using BaGet.Service.NuGet; +using BaGet.Service.Runtime; +using BaGet.Service.Service; + +namespace BaGet.Service; + +public static class Program +{ + public static string[] Arguments = Array.Empty(); + + public static async Task Main(string[] args) + { + Arguments = args; + if (Arguments.Any(a => a.ToLower() == "register")) + { + await ServiceHelper.Register(); + } + + if (args.Any(a => a.ToLower() == "package")) + { + var directoryName = Configuration.GetDirectoryName(args); + + await NuGetHelper.Push(directoryName); + } + + if (args.Any(a => a.ToLower() == "delete")) + { + await ServiceHelper.UnRegister(); + } + + await BaGetRunner.RunBaGet(args); + } +} diff --git a/service/BaGetService/Runtime/BaGetRunner.cs b/service/BaGetService/Runtime/BaGetRunner.cs new file mode 100644 index 000000000..1956aafc2 --- /dev/null +++ b/service/BaGetService/Runtime/BaGetRunner.cs @@ -0,0 +1,36 @@ +using BaGet.Service.Service; +using Microsoft.Extensions.Logging.Configuration; +using Microsoft.Extensions.Logging.EventLog; +using Serilog; + +namespace BaGet.Service.Runtime +{ + public static class BaGetRunner + { + public static async Task RunBaGet(string[] args) + { + Environment.CurrentDirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location)!; + using var host = Host.CreateDefaultBuilder(args) + .UseWindowsService(options => { options.ServiceName = "BaGetService"; }) + .ConfigureServices(services => + { + LoggerProviderOptions.RegisterProviderOptions< + EventLogSettings, EventLogLoggerProvider>(services); + + services.AddHostedService(); + }) + .ConfigureLogging( + loggingBuilder => + { + var configuration = new ConfigurationBuilder() + .AddJsonFile("appsettings.json") + .Build(); + var logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .CreateLogger(); + loggingBuilder.AddSerilog(logger, true); + }).Build(); + await host.RunAsync(); + } + } +} diff --git a/service/BaGetService/Runtime/Configuration.cs b/service/BaGetService/Runtime/Configuration.cs new file mode 100644 index 000000000..ecf15eb79 --- /dev/null +++ b/service/BaGetService/Runtime/Configuration.cs @@ -0,0 +1,25 @@ +namespace BaGet.Service.Runtime +{ + public static class Configuration + { + public static string GetDirectoryName(string[] args) + { + var directoryName = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location)!, "PackagesToPublish"); + + var lastOrDefault = (args.LastOrDefault() ?? "").Trim('"'); + if (!string.IsNullOrEmpty(lastOrDefault) && Directory.Exists(lastOrDefault)) + { + directoryName = lastOrDefault; + } + + Console.WriteLine($"Please insert the directory containing packages ('{directoryName}' if empty)"); + var readLine = Console.ReadLine(); + if (!string.IsNullOrEmpty(readLine) && Directory.Exists(readLine)) + { + directoryName = readLine; + } + + return directoryName; + } + } +} diff --git a/service/BaGetService/Service/BaGetService.cs b/service/BaGetService/Service/BaGetService.cs new file mode 100644 index 000000000..e34c805c6 --- /dev/null +++ b/service/BaGetService/Service/BaGetService.cs @@ -0,0 +1,39 @@ +using System.Diagnostics; + +namespace BaGet.Service.Service; + +public sealed class BaGetService : BackgroundService +{ + private readonly ILogger _logger; + + public BaGetService(ILogger logger) => + _logger = logger; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + while (!stoppingToken.IsCancellationRequested) + { + await BaGet.Program.Main(Program.Arguments); + } + Dispose(); + } + catch (Exception ex) + { + _logger.LogError(ex, "{Message}", ex.Message); + + // Terminates this process and returns an exit code to the operating system. + // This is required to avoid the 'BackgroundServiceExceptionBehavior', which + // performs one of two scenarios: + // 1. When set to "Ignore": will do nothing at all, errors cause zombie services. + // 2. When set to "StopHost": will cleanly stop the host, and log errors. + // + // In order for the Windows Service Management system to leverage configured + // recovery options, we need to terminate the process with a non-zero exit code. + Dispose(); + Environment.Exit(1); + } + } + +} diff --git a/service/BaGetService/Service/ServiceHelper.cs b/service/BaGetService/Service/ServiceHelper.cs new file mode 100644 index 000000000..ce80874a1 --- /dev/null +++ b/service/BaGetService/Service/ServiceHelper.cs @@ -0,0 +1,66 @@ +using System.Diagnostics; + +namespace BaGet.Service.Service; + +public static class ServiceHelper +{ + public static async Task UnRegister() + { + Process process; + try + { + process = Process.Start("net.exe", + $"stop BaGetService"); + await process.WaitForExitAsync(); + } + catch (Exception e) + { + Console.WriteLine(e); + Console.Read(); + } + + try + { + process = Process.Start("sc.exe", + $"delete BaGetService"); + await process.WaitForExitAsync(); + } + catch (Exception e) + { + Console.WriteLine(e); + Console.Read(); + } + + Environment.Exit(0); + } + + public static async Task Register() + { + try + { + var arguments = + $"create \"BaGetService\" binpath=\"dotnet.exe \\\"{typeof(Program).Assembly.Location}\\\"\" start=auto"; + var process = Process.Start("sc.exe", arguments); + await process.WaitForExitAsync(); + } + catch (Exception e) + { + Console.WriteLine(e); + Console.Read(); + } + + try + { + var process = Process.Start("net.exe", + $"start BaGetService"); + await process.WaitForExitAsync(); + } + catch (Exception e) + { + Console.WriteLine(e); + Console.Read(); + } + + Environment.Exit(0); + } +} diff --git a/service/BaGetService/appsettings.Development.json b/service/BaGetService/appsettings.Development.json new file mode 100644 index 000000000..9cb25d1eb --- /dev/null +++ b/service/BaGetService/appsettings.Development.json @@ -0,0 +1,15 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + }, + "EventLog": { + "SourceName": "The Joke Service", + "LogName": "Application", + "LogLevel": { + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } + } +} diff --git a/service/BaGetService/appsettings.json b/service/BaGetService/appsettings.json new file mode 100644 index 000000000..a1bf3112b --- /dev/null +++ b/service/BaGetService/appsettings.json @@ -0,0 +1,63 @@ +{ + "Serilog": { + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.txt", + "rollingInterval": "Day" + } + } + ] + }, + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + + "ApiKey": "BaGet", + "AllowPackageOverwrites": true, + "PackageDeletionBehavior": "HardDelete", + + "Database": { + "Type": "Sqlite", + "ConnectionString": "Data Source=baget.db" + }, + + "Storage": { + "Type": "FileSystem", + "Path": "" + }, + + "Search": { + "Type": "Database" + }, + + "Mirror": { + "Enabled": false, + + // Uncomment this to use the NuGet v2 protocol + //"Legacy": true, + "PackageSource": "https://api.nuget.org/v3/index.json" + }, + + // Uncomment this to configure BaGet to listen to port 8080. + // See: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-3.1#listenoptionsusehttps + //"Kestrel": { + // "Endpoints": { + // "Http": { + // "Url": "http://localhost:8080" + // } + // } + //}, + + "Kestrel": { + "Endpoints": { + "Http": { + "Url": "http://localhost:6060" + } + } + } + +} diff --git a/service/BaGetService/favicon.ico b/service/BaGetService/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..b3065baffc747dbd38169d8f88289268de20f89b GIT binary patch literal 15086 zcmd6t35;D+7{||;wo_ZCAr)FNqp3#hJJHsNXbGbBJydM9uZdl!8WkkgYDAGBN{B7Q zQY39kW3O0Bl$zQaRE@0$^`77V&O7g&d+ze?ySXQk-->;Bp8T;J10Q+*T;Eyiz4*8s z+SBr&zXR?E|5_-AF=@7bANsm)ZiTElCh2KBo(rvhjJP&>?QkFX{%%2*`94B-Yxp|G zkMFl$`yPC>#pRkLLw{3v!;AeT?H!YBd^x%odiM45jO+gnA3OWLv$U~05j1A3UyX}t z8Ey5v)U(0b<}IJaM?>e{=7-$~SnTESn(a?3vDp9?dA50u;fAz0X??`jv*|G}hZSiy zwhtTKe@i{vJo#U0edZ~NKg-KubrwI^bb#I|d2)7buFVoJNr(86=TMTaD=#qrIrz%- z+;rosj-BR-^T9nIWnV9@jZIPK|5N#ji&0O8-EOb~{?GjXA^!RGa`pSM(b%2o=dQM| z8`nm!sPnILw*)f3ca#tMhr&+~I`?YF8rO@G5NU$MM_fXpJ!uw3dnFE}3r= z*G8}C{FTeca4HOk(7Hrz*aR+tZy`2!$>Z|%W#}~{f90h4fZmI@gXYU8fadqQ*FS*O zkeIvr{9NPO=rt>UKR3;3d|7HcE?-}kA%DfyoL<-Z7ic&SY*O<~>i2VvYh&91N$+1h z(=P=*pSOUqa3g50nJcG8?BeqEW%x_Ve<6L_#pr9TqdlBu(9~n_W5>10AufNN-*IvJ zR!09Rp!Ipvj={!CD~Z1ueBtHsFzwX64Ei^OH$1x{kEN8Bx9ubTM&Pg8ueAMXC3g2V zG5=rEV%t9AYfs|^FORJG&-Uz!Jpb?89P5?jFx|@|%l*@ijphnP=Ir{qvtHh|pB%=4 zJBM0Mdso{ZSJHn3{0?r+qUzemnh+N^PKK`TA%Fcj7ul!;eZ3Dpgrf5G{XB~Ab>dx#f;IY{fxVt9H^U!LbdE{>6ifTBd?{P= zAAU5Rwf@ljEh%PEa;-T}gSFQ@^RNeej)Chy@8>=!Drfmx3^O3pUO9RipP{u}INSJE z#ZK!z%{eu;G(I$MxGx8?l@IwE0d@01NAoPr6>U7#H;m7AU`feS&+I3`eV(ZP6pR>H z*+#P=$Gf2farf=@QHy~kA@9hZoO3LTs1NA-i2VL`^7XI5XY`F6SZ6$(4f$yw$3>1o`=oZmcJo8VPIt&&4wJ?;B3%4PVWq%`Z+KpYBBI6NRZd`<^^_bK??Km-yO7Dl!|0~R7#4V-Ctg&f_DEFM0vinY1?u^rENC0%fw8t$sUC5QxRF!=kxG~Es=WSZ0q=TOlh%c?)f=Yi- zps)Ya>V&*CnJ2+8wbwi_@&9D# zYX!~0tbV;x`z8m}qDE`R(z#Giwbmwj&|*n>ga6+cCY836usloYh;{f`u>a0 z@lYL41;&2@zeAJ!SvfjWp?dwS+%M5-^!Rm65A*%FZTfeF&!HLdy+UnH$rsI(c$P{7!_=E#aGrZ^ei_Taf7*=-lLq zEt`emBdWFN)3IqUUwS`6adV!~2l>JflA;w(gT>VNVFfRvUD`rLJx19|^*z4J%cZEG~Z&Lry_O^)Sk6+#6lalU*qUFTWdc_{Q%2hD2 z=r~FKh;;?@f@14BJOYX9k|aNQ<;2q1(i~+bTm&2E^_9ntZHKAl9`;t|vHj59I=yV# zmz7M%&(K#gT@Gq@^p;FJI~=XudU2K*O{Kk{D@03qGtpIu=y4(9t z^Nq!z=Yak%Uhh4<14Hi#+Fg}CYiG-skO%to}PSY zk7cEmQ`fWSL9lkV)Hvo!gn!6xldhFgm%Zl4*3K=bso&8ZN&7A7IG#3c2 z52cGqb>~4ew pkZIoI`(4c*Y9HD3jx(l*t + + + + + + + diff --git a/src/BaGet.Aliyun/BaGet.Aliyun.csproj b/src/BaGet.Aliyun/BaGet.Aliyun.csproj index ad7896fcc..26a555bc2 100644 --- a/src/BaGet.Aliyun/BaGet.Aliyun.csproj +++ b/src/BaGet.Aliyun/BaGet.Aliyun.csproj @@ -2,15 +2,19 @@ NuGet;Alibaba;Cloud The libraries to host BaGet on Alibaba Cloud (Aliyun). - netstandard2.0 + net10.0 - + + + + + diff --git a/src/BaGet.Aws/BaGet.Aws.csproj b/src/BaGet.Aws/BaGet.Aws.csproj index 5094cd3d6..fbfe62b28 100644 --- a/src/BaGet.Aws/BaGet.Aws.csproj +++ b/src/BaGet.Aws/BaGet.Aws.csproj @@ -1,20 +1,24 @@ - + - netstandard2.0 + net10.0 NuGet;Amazon;Cloud The libraries to host BaGet on AWS. - - - + + + + + + + diff --git a/src/BaGet.Azure/AzureApplicationExtensions.cs b/src/BaGet.Azure/AzureApplicationExtensions.cs index f8916840f..150d4f1df 100644 --- a/src/BaGet.Azure/AzureApplicationExtensions.cs +++ b/src/BaGet.Azure/AzureApplicationExtensions.cs @@ -6,12 +6,12 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -using Microsoft.WindowsAzure.Storage.Blob; +using Microsoft.Azure.Storage.Blob; namespace BaGet { - using CloudStorageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount; - using StorageCredentials = Microsoft.WindowsAzure.Storage.Auth.StorageCredentials; + using CloudStorageAccount = Microsoft.Azure.Storage.CloudStorageAccount; + using StorageCredentials = Microsoft.Azure.Storage.Auth.StorageCredentials; using TableStorageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount; diff --git a/src/BaGet.Azure/BaGet.Azure.csproj b/src/BaGet.Azure/BaGet.Azure.csproj index 7b567f6aa..6cc2bb33a 100644 --- a/src/BaGet.Azure/BaGet.Azure.csproj +++ b/src/BaGet.Azure/BaGet.Azure.csproj @@ -1,21 +1,30 @@ - netstandard2.0 + net10.0 NuGet;Azure;Cloud The libraries to host BaGet on Azure. + + + + + true - + - - - - + + + + + + + + diff --git a/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs b/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs index a7f50c131..8f6a87bf5 100644 --- a/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs +++ b/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs @@ -2,7 +2,7 @@ namespace BaGet.Azure { - using StorageException = Microsoft.WindowsAzure.Storage.StorageException; + using StorageException = Microsoft.Azure.Storage.StorageException; using TableStorageException = Microsoft.Azure.Cosmos.Table.StorageException; internal static class StorageExceptionExtensions diff --git a/src/BaGet.Azure/Storage/BlobStorageService.cs b/src/BaGet.Azure/Storage/BlobStorageService.cs index fe07efb38..63e08a2b1 100644 --- a/src/BaGet.Azure/Storage/BlobStorageService.cs +++ b/src/BaGet.Azure/Storage/BlobStorageService.cs @@ -3,8 +3,8 @@ using System.Threading; using System.Threading.Tasks; using BaGet.Core; -using Microsoft.WindowsAzure.Storage; -using Microsoft.WindowsAzure.Storage.Blob; +using Microsoft.Azure.Storage; +using Microsoft.Azure.Storage.Blob; namespace BaGet.Azure { diff --git a/src/BaGet.Core/BaGet.Core.csproj b/src/BaGet.Core/BaGet.Core.csproj index e88788429..685416fc5 100644 --- a/src/BaGet.Core/BaGet.Core.csproj +++ b/src/BaGet.Core/BaGet.Core.csproj @@ -1,7 +1,7 @@ - netstandard2.0 + net10.0 NuGet The core libraries that power BaGet. @@ -13,11 +13,15 @@ - + + + + + diff --git a/src/BaGet.Core/Metadata/RegistrationBuilder.cs b/src/BaGet.Core/Metadata/RegistrationBuilder.cs index 4090e9323..945e3bb1e 100644 --- a/src/BaGet.Core/Metadata/RegistrationBuilder.cs +++ b/src/BaGet.Core/Metadata/RegistrationBuilder.cs @@ -83,7 +83,7 @@ private BaGetRegistrationIndexPageItem ToRegistrationIndexPageItem(Package packa ProjectUrl = package.ProjectUrlString, RepositoryUrl = package.RepositoryUrlString, RepositoryType = package.RepositoryType, - Published = package.Published, + Published = package.Published==DateTime.MinValue?DateTimeOffset.Now : package.Published, RequireLicenseAcceptance = package.RequireLicenseAcceptance, Summary = package.Summary, Tags = package.Tags, diff --git a/src/BaGet.Core/PackageDatabase.cs b/src/BaGet.Core/PackageDatabase.cs index 98f5168cc..2bdf7accf 100644 --- a/src/BaGet.Core/PackageDatabase.cs +++ b/src/BaGet.Core/PackageDatabase.cs @@ -57,6 +57,7 @@ public async Task> FindAsync(string id, bool includeUnlis .Include(p => p.Dependencies) .Include(p => p.PackageTypes) .Include(p => p.TargetFrameworks) + .AsSplitQuery() .Where(p => p.Id == id); if (!includeUnlisted) @@ -76,6 +77,7 @@ public Task FindOrNullAsync( var query = _context.Packages .Include(p => p.Dependencies) .Include(p => p.TargetFrameworks) + .AsSplitQuery() .Where(p => p.Id == id) .Where(p => p.NormalizedVersionString == version.ToNormalizedString()); @@ -109,6 +111,7 @@ public async Task HardDeletePackageAsync(string id, NuGetVersion version, .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) .Include(p => p.Dependencies) .Include(p => p.TargetFrameworks) + .AsSplitQuery() .FirstOrDefaultAsync(cancellationToken); if (package == null) diff --git a/src/BaGet.Database.MySql/BaGet.Database.MySql.csproj b/src/BaGet.Database.MySql/BaGet.Database.MySql.csproj index adb58c0cf..fbc939886 100644 --- a/src/BaGet.Database.MySql/BaGet.Database.MySql.csproj +++ b/src/BaGet.Database.MySql/BaGet.Database.MySql.csproj @@ -1,19 +1,23 @@ - netstandard2.0 + net10.0 NuGet The libraries to host BaGet on MySQL. - + + + + + diff --git a/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs b/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs index 2156d90c3..07d5ef331 100644 --- a/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs +++ b/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; +using Pomelo.EntityFrameworkCore.MySql.Infrastructure; namespace BaGet { @@ -15,7 +16,9 @@ public static BaGetApplication AddMySqlDatabase(this BaGetApplication app) { var databaseOptions = provider.GetRequiredService>(); - options.UseMySql(databaseOptions.Value.ConnectionString); + options.UseMySql( + databaseOptions.Value.ConnectionString, + ServerVersion.AutoDetect(databaseOptions.Value.ConnectionString)); }); return app; diff --git a/src/BaGet.Database.MySql/MySqlContext.cs b/src/BaGet.Database.MySql/MySqlContext.cs index 49bbb65fb..f1118dc3f 100644 --- a/src/BaGet.Database.MySql/MySqlContext.cs +++ b/src/BaGet.Database.MySql/MySqlContext.cs @@ -1,6 +1,6 @@ using BaGet.Core; using Microsoft.EntityFrameworkCore; -using MySql.Data.MySqlClient; +using MySqlConnector; namespace BaGet.Database.MySql { diff --git a/src/BaGet.Database.PostgreSql/BaGet.Database.PostgreSql.csproj b/src/BaGet.Database.PostgreSql/BaGet.Database.PostgreSql.csproj index afc7a1214..8d8fce4e1 100644 --- a/src/BaGet.Database.PostgreSql/BaGet.Database.PostgreSql.csproj +++ b/src/BaGet.Database.PostgreSql/BaGet.Database.PostgreSql.csproj @@ -1,18 +1,22 @@ - netstandard2.0 + net10.0 NuGet The libraries to host BaGet on PostgreSQL. - + + + + + diff --git a/src/BaGet.Database.SqlServer/BaGet.Database.SqlServer.csproj b/src/BaGet.Database.SqlServer/BaGet.Database.SqlServer.csproj index c6720e41b..28e69a89a 100644 --- a/src/BaGet.Database.SqlServer/BaGet.Database.SqlServer.csproj +++ b/src/BaGet.Database.SqlServer/BaGet.Database.SqlServer.csproj @@ -1,18 +1,22 @@ - netstandard2.0 + net10.0 NuGet The libraries to host BaGet on SQL Server. - + + + + + diff --git a/src/BaGet.Database.Sqlite/BaGet.Database.Sqlite.csproj b/src/BaGet.Database.Sqlite/BaGet.Database.Sqlite.csproj index c7515daac..069f2f6cb 100644 --- a/src/BaGet.Database.Sqlite/BaGet.Database.Sqlite.csproj +++ b/src/BaGet.Database.Sqlite/BaGet.Database.Sqlite.csproj @@ -1,18 +1,22 @@ - netstandard2.0 + net10.0 NuGet The libraries to host BaGet on SQLite. - + + + + + diff --git a/src/BaGet.Gcp/BaGet.Gcp.csproj b/src/BaGet.Gcp/BaGet.Gcp.csproj index 3dc33ae66..2415184b9 100644 --- a/src/BaGet.Gcp/BaGet.Gcp.csproj +++ b/src/BaGet.Gcp/BaGet.Gcp.csproj @@ -1,18 +1,22 @@ - netstandard2.0 + net10.0 NuGet;Google;Cloud The libraries to host BaGet on the Google Cloud Platform. - + + + + + diff --git a/src/BaGet.Protocol/BaGet.Protocol.csproj b/src/BaGet.Protocol/BaGet.Protocol.csproj index 5711a54bb..01037b0f9 100644 --- a/src/BaGet.Protocol/BaGet.Protocol.csproj +++ b/src/BaGet.Protocol/BaGet.Protocol.csproj @@ -1,7 +1,7 @@ - netstandard2.0 + net10.0 NuGet;Protocol Libraries to interact with NuGet server APIs. @@ -11,7 +11,10 @@ - + + + + diff --git a/src/BaGet.Web/BaGet.Web.csproj b/src/BaGet.Web/BaGet.Web.csproj index 276e6569d..237761d57 100644 --- a/src/BaGet.Web/BaGet.Web.csproj +++ b/src/BaGet.Web/BaGet.Web.csproj @@ -1,7 +1,7 @@ - + - netcoreapp3.1 + net10.0 NuGet BaGet's NuGet server implementation @@ -15,12 +15,16 @@ - - + + + + + + diff --git a/src/BaGet.Web/BaGetEndpointBuilder.cs b/src/BaGet.Web/BaGetEndpointBuilder.cs index d485eb40e..89f1da661 100644 --- a/src/BaGet.Web/BaGetEndpointBuilder.cs +++ b/src/BaGet.Web/BaGetEndpointBuilder.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using BaGet.Web; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; diff --git a/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs b/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs index 39964850d..d29da73f8 100644 --- a/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs +++ b/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs @@ -1,7 +1,9 @@ using System; +using System.Text.Json.Serialization; using BaGet.Core; using BaGet.Web; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.DependencyInjection; namespace BaGet @@ -16,13 +18,16 @@ public static IServiceCollection AddBaGetWebApplication( .AddRouting(options => options.LowercaseUrls = true) .AddControllers() .AddApplicationPart(typeof(PackageContentController).Assembly) - .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddJsonOptions(options => { - options.JsonSerializerOptions.IgnoreNullValues = true; + options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; }); - services.AddRazorPages(); + services.AddRazorPages(options => + { + // Add /packages route to the Index page + options.Conventions.AddPageRoute("/Index", "/packages"); + }); services.AddHttpContextAccessor(); services.AddTransient(); diff --git a/src/BaGet.Web/NavLinkTagHelper.cs b/src/BaGet.Web/NavLinkTagHelper.cs index 2f41b5f3e..b35873969 100644 --- a/src/BaGet.Web/NavLinkTagHelper.cs +++ b/src/BaGet.Web/NavLinkTagHelper.cs @@ -33,9 +33,22 @@ private bool IsActiveLink() if (pageDescriptor == null) return false; if (pageDescriptor.AreaName != null) return false; - if (pageDescriptor.ViewEnginePath != Page) return false; + + // If asp-page is specified, check if the page path matches + if (!string.IsNullOrEmpty(Page)) + { + if (pageDescriptor.ViewEnginePath == Page) return true; + } + + // Special case: /packages and / should both be active for the Packages link + // (both routes point to the Index page) + var path = _accessor.HttpContext?.Request.Path.Value; + if (pageDescriptor.ViewEnginePath == "/Index" && (path == "/packages" || path == "/")) + { + return true; + } - return true; + return false; } } } diff --git a/src/BaGet.Web/Pages/Index.cshtml b/src/BaGet.Web/Pages/Index.cshtml index 303e1c0c5..a056ab988 100644 --- a/src/BaGet.Web/Pages/Index.cshtml +++ b/src/BaGet.Web/Pages/Index.cshtml @@ -115,7 +115,6 @@ else

@package.PackageId @@ -190,7 +189,9 @@ else { "header1", ".NET" }, { "net5.0", ".NET 5.0" }, - + { "net6.0", ".NET 6.0" }, + { "net7.0", ".NET 7.0" }, + { "net8.0", ".NET 8.0" }, { "divider2", "-" }, { "header2", ".NET Standard" }, diff --git a/src/BaGet.Web/Pages/Package.cshtml b/src/BaGet.Web/Pages/Package.cshtml index 8e42cd6d3..9f489642d 100644 --- a/src/BaGet.Web/Pages/Package.cshtml +++ b/src/BaGet.Web/Pages/Package.cshtml @@ -181,7 +181,7 @@ else var alwaysShow = Json.Serialize(i < DefaultVisibleVersions); - @version.Version.ToNormalizedString() + @version.Version.ToNormalizedString() @version.Downloads.ToString("N0") @version.LastUpdated.ToShortDateString() diff --git a/src/BaGet.Web/Pages/Shared/_Layout.cshtml b/src/BaGet.Web/Pages/Shared/_Layout.cshtml index 91bae357e..ba96a9b1a 100644 --- a/src/BaGet.Web/Pages/Shared/_Layout.cshtml +++ b/src/BaGet.Web/Pages/Shared/_Layout.cshtml @@ -22,7 +22,7 @@
diff --git a/src/BaGet/Startup.cs b/src/BaGet/Startup.cs index 1c9a1dfda..960d26cee 100644 --- a/src/BaGet/Startup.cs +++ b/src/BaGet/Startup.cs @@ -1,6 +1,7 @@ using System; using System.IO; using BaGet.Core; +using BaGet.Identity; using BaGet.Web; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors.Infrastructure; @@ -41,6 +42,7 @@ public void ConfigureServices(IServiceCollection services) services.AddBaGetOptions(nameof(IISServerOptions)); services.AddBaGetWebApplication(ConfigureBaGetApplication); + services.AddBaGetAccounts(Configuration); // You can swap between implementations of subsystems like storage and search using BaGet's configuration. // Each subsystem's implementation has a provider that reads the configuration to determine if it should be @@ -116,6 +118,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) app.UseRouting(); app.UseCors(ConfigureBaGetOptions.CorsPolicy); + app.UseAuthentication(); + app.UseAuthorization(); app.UseOperationCancelledMiddleware(); app.UseEndpoints(endpoints => diff --git a/tests/BaGet.Tests/AccountsDisabledTests.cs b/tests/BaGet.Tests/AccountsDisabledTests.cs new file mode 100644 index 000000000..11d34cd7f --- /dev/null +++ b/tests/BaGet.Tests/AccountsDisabledTests.cs @@ -0,0 +1,50 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Xunit; +using Xunit.Abstractions; + +namespace BaGet.Tests +{ + /// + /// Accounts are off by default, and an upgraded server must not grow account pages. + /// + public class AccountsDisabledTests : IDisposable + { + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public AccountsDisabledTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output); + _client = _app.CreateClient(); + } + + [Theory] + [InlineData("account/login")] + [InlineData("account/register")] + [InlineData("account/logout")] + [InlineData("account/apikeys")] + public async Task AccountPagesAreNotFound(string url) + { + using var response = await _client.GetAsync(url); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task TheLayoutHasNoSignInLink() + { + var html = await _client.GetStringAsync("upload"); + + Assert.DoesNotContain("account/login", html); + } + + public void Dispose() + { + _app.Dispose(); + _client.Dispose(); + } + } +} diff --git a/tests/BaGet.Tests/AccountsIntegrationTests.cs b/tests/BaGet.Tests/AccountsIntegrationTests.cs new file mode 100644 index 000000000..3ceca3d4c --- /dev/null +++ b/tests/BaGet.Tests/AccountsIntegrationTests.cs @@ -0,0 +1,311 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Xunit; +using Xunit.Abstractions; + +namespace BaGet.Tests +{ + /// + /// Accounts enabled on a closed server: the global key is the superuser, and users' + /// keys act within their scopes, their globs and the packages they own. + /// + public class AccountsIntegrationTests : IDisposable + { + private const string GlobalKey = "global-key"; + + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + // Keeps cookies and does not follow redirects, like a browser seen one hop at a time. + private readonly HttpClient _browser; + + public AccountsIntegrationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary + { + { "ApiKey", GlobalKey }, + { "Accounts:Enabled", "true" }, + }); + _client = _app.CreateClient(); + _browser = _app.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + } + + [Fact] + public async Task TheGlobalKeyStillPushes() + { + Assert.Equal(HttpStatusCode.Created, await PushAsync("Legacy.Package", "1.0.0", GlobalKey)); + } + + [Fact] + public async Task AWrongKeyIsUnauthorized() + { + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Any.Package", "1.0.0", "bgt_wrong")); + } + + [Fact] + public async Task PushingANewIdMakesThePusherItsOwner() + { + var alice = await CreateUserAsync("alice"); + var key = await CreateKeyAsync(alice, ApiKeyScopes.Push); + + Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "1.0.0", key)); + Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "2.0.0", key)); + + var owners = await WithServiceAsync>( + s => s.GetOwnersAsync("alice.package", CancellationToken.None)); + Assert.Equal("alice", Assert.Single(owners).OwnerName); + } + + [Fact] + public async Task AnotherUserCannotPushToAnOwnedId() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + + Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Alice.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Push))); + } + + [Fact] + public async Task AnIdWithoutOwnersIsForTheGlobalKeyOnly() + { + // Pushed before accounts existed, so it has no owner and nobody may claim it. + await PushAsync("Legacy.Package", "1.0.0", GlobalKey); + var alice = await CreateUserAsync("alice"); + + Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Legacy.Package", "2.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); + Assert.Equal(HttpStatusCode.Created, await PushAsync("Legacy.Package", "2.0.0", GlobalKey)); + } + + [Fact] + public async Task PushVersionCannotClaimANewId() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + var versionOnly = await CreateKeyAsync(alice, ApiKeyScopes.PushVersion); + + Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "2.0.0", versionOnly)); + Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Alice.Other", "1.0.0", versionOnly)); + } + + [Fact] + public async Task AKeyOnlyActsWithinItsGlob() + { + var alice = await CreateUserAsync("alice"); + var key = await CreateKeyAsync(alice, ApiKeyScopes.Push, glob: "Alice.*"); + + Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "1.0.0", key)); + Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Elsewhere.Package", "1.0.0", key)); + } + + [Fact] + public async Task AnExpiredKeyIsUnauthorized() + { + var alice = await CreateUserAsync("alice"); + // The test host's clock is frozen at 2020-01-01. + var key = await CreateKeyAsync(alice, ApiKeyScopes.Push, expires: new DateTime(2019, 12, 31, 0, 0, 0, DateTimeKind.Utc)); + + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "1.0.0", key)); + } + + [Fact] + public async Task ARevokedKeyIsUnauthorized() + { + var alice = await CreateUserAsync("alice"); + var key = await CreateKeyAsync(alice, ApiKeyScopes.Push); + + await WithServiceAsync(async s => + { + var stored = Assert.Single(await s.ListAsync(alice.Id, CancellationToken.None)); + return await s.RevokeAsync(alice.Id, stored.Key, CancellationToken.None); + }); + + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "1.0.0", key)); + } + + [Fact] + public async Task UnlistingNeedsTheUnlistScopeAndOwnership() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + + Assert.Equal(HttpStatusCode.Forbidden, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); + Assert.Equal(HttpStatusCode.Forbidden, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Unlist))); + Assert.Equal(HttpStatusCode.NoContent, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Unlist))); + } + + [Fact] + public async Task AnOrganizationMemberActsForTheOrganizationsPackages() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); + await PushAsync("Contoso.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + + await WithServiceAsync(async s => + { + Assert.True(await s.CreateOrganizationAsync("contoso", alice.Id, CancellationToken.None)); + Assert.True(await s.AddMemberAsync("contoso", bob.Id, isAdmin: false, CancellationToken.None)); + Assert.Equal(OwnerChangeResult.Success, await s.AddOwnerAsync("Contoso.Package", "contoso", CancellationToken.None)); + return true; + }); + + Assert.Equal(HttpStatusCode.Created, await PushAsync("Contoso.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.PushVersion))); + } + + [Fact] + public async Task AnOrganizationCannotTakeAUsersName() + { + var alice = await CreateUserAsync("alice"); + + Assert.False(await WithServiceAsync( + s => s.CreateOrganizationAsync("Alice", alice.Id, CancellationToken.None))); + } + + [Fact] + public async Task ThePackagesLastOwnerCannotBeRemoved() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + + Assert.Equal(OwnerChangeResult.LastOwner, await WithServiceAsync( + s => s.RemoveOwnerAsync("Alice.Package", "alice", CancellationToken.None))); + } + + [Fact] + public async Task SearchReportsOwnersAndVerification() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + await PushAsync("Legacy.Package", "1.0.0", GlobalKey); + await WithServiceAsync( + s => s.SetVerifiedAsync("Alice.Package", verified: true, CancellationToken.None)); + + using var search = System.Text.Json.JsonDocument.Parse(await _client.GetStringAsync("v3/search")); + var results = search.RootElement.GetProperty("data").EnumerateArray() + .ToDictionary(r => r.GetProperty("id").GetString()); + + Assert.Equal("alice", results["Alice.Package"].GetProperty("owners")[0].GetString()); + Assert.True(results["Alice.Package"].GetProperty("verified").GetBoolean()); + Assert.False(results["Legacy.Package"].TryGetProperty("owners", out _)); + Assert.False(results["Legacy.Package"].TryGetProperty("verified", out _)); + } + + [Fact] + public async Task ARegisteredUserCanCreateAKeyThatPushes() + { + // The whole browser flow: register, then create a key on the API keys page. + var register = await GetFormAsync("account/register"); + using (var response = await PostFormAsync("account/register", register, new Dictionary + { + { "UserName", "carol" }, + { "Password", "Passw0rd!" }, + { "ConfirmPassword", "Passw0rd!" }, + })) + { + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + } + + var keys = await GetFormAsync("account/apikeys"); + string key; + using (var response = await PostFormAsync("account/apikeys?handler=Create", keys, new Dictionary + { + { "Description", "ci" }, + { "Scopes", ApiKeyScopes.Push }, + { "PackageGlobPattern", "*" }, + { "ExpiresInDays", "30" }, + })) + { + var html = await response.Content.ReadAsStringAsync(); + key = Regex.Match(html, "
([^<]+)
").Groups[1].Value; + } + + Assert.StartsWith("bgt_", key); + Assert.Equal(HttpStatusCode.Created, await PushAsync("Carol.Package", "1.0.0", key)); + } + + [Fact] + public async Task TheApiKeysPageNeedsASignedInUser() + { + using var response = await _browser.GetAsync("account/apikeys"); + + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/account/login", response.Headers.Location.ToString()); + } + + private async Task PushAsync(string id, string version, string apiKey) + { + using var package = TestPackages.Build(id, version); + using var request = TestPackages.PushRequest(package, apiKey); + using var response = await _client.SendAsync(request); + + return response.StatusCode; + } + + private async Task DeleteAsync(string id, string version, string apiKey) + { + using var request = new HttpRequestMessage(HttpMethod.Delete, $"api/v2/package/{id}/{version}"); + request.Headers.Add("X-NuGet-ApiKey", apiKey); + using var response = await _client.SendAsync(request); + + return response.StatusCode; + } + + private async Task CreateUserAsync(string name) + { + using var scope = _app.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + var user = new BaGetUser { UserName = name }; + + var result = await users.CreateAsync(user, "Passw0rd!"); + Assert.True(result.Succeeded, string.Join(" ", result.Errors.Select(e => e.Description))); + + return user; + } + + private Task CreateKeyAsync(BaGetUser user, string scope, string glob = "*", DateTime? expires = null) + => WithServiceAsync( + s => s.CreateAsync(user.Id, "test", new[] { scope }, glob, expires, CancellationToken.None)); + + private async Task WithServiceAsync(Func> action) + { + using var scope = _app.Services.CreateScope(); + + return await action(scope.ServiceProvider.GetRequiredService()); + } + + private async Task GetFormAsync(string url) + { + using var response = await _browser.GetAsync(url); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var html = await response.Content.ReadAsStringAsync(); + + return Regex.Match(html, "name=\"__RequestVerificationToken\" type=\"hidden\" value=\"([^\"]+)\"").Groups[1].Value; + } + + private async Task PostFormAsync(string url, string token, Dictionary fields) + { + fields["__RequestVerificationToken"] = token; + + return await _browser.PostAsync(url, new FormUrlEncodedContent(fields)); + } + + public void Dispose() + { + _app.Dispose(); + _client.Dispose(); + _browser.Dispose(); + } + } +} diff --git a/tests/BaGet.Tests/Support/TestPackages.cs b/tests/BaGet.Tests/Support/TestPackages.cs new file mode 100644 index 000000000..668567698 --- /dev/null +++ b/tests/BaGet.Tests/Support/TestPackages.cs @@ -0,0 +1,71 @@ +using System.IO; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using NuGet.Packaging; +using NuGet.Versioning; + +namespace BaGet.Tests +{ + /// + /// Builds minimal packages in memory, for tests that need more than the one checked in. + /// + internal static class TestPackages + { + public static MemoryStream Build(string id, string version) + { + var builder = new PackageBuilder + { + Id = id, + Version = NuGetVersion.Parse(version), + Description = "Test package", + }; + builder.Authors.Add("Test author"); + builder.Files.Add(new InMemoryFile("content/readme.txt", "test")); + + var stream = new MemoryStream(); + builder.Save(stream); + stream.Position = 0; + + return stream; + } + + /// + /// A push request as "dotnet nuget push" sends it. + /// + public static HttpRequestMessage PushRequest(Stream package, string apiKey) + { + var content = new MultipartFormDataContent(); + var file = new StreamContent(package); + file.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + content.Add(file, "package", "package.nupkg"); + + var request = new HttpRequestMessage(HttpMethod.Put, "api/v2/package") { Content = content }; + if (apiKey != null) + { + request.Headers.Add("X-NuGet-ApiKey", apiKey); + } + + return request; + } + + private class InMemoryFile : IPackageFile + { + private readonly byte[] _content; + + public InMemoryFile(string path, string content) + { + Path = path; + _content = Encoding.UTF8.GetBytes(content); + } + + public string Path { get; } + public string EffectivePath => Path; + public NuGet.Frameworks.NuGetFramework NuGetFramework => null; + public System.Runtime.Versioning.FrameworkName TargetFramework => null; + public System.DateTimeOffset LastWriteTime => System.DateTimeOffset.UnixEpoch; + + public Stream GetStream() => new MemoryStream(_content); + } + } +} From 4e99d71abe1bef59ac9b73689d2edd1940891f14 Mon Sep 17 00:00:00 2001 From: pieroviano Date: Sat, 17 Oct 2026 05:00:02 +0300 Subject: [PATCH 047/498] Phase 6: validation pipeline and repository signing New BaGet.Validation project, off unless Validation:Enabled. A push is staged in storage, recorded as PackageValidations rows (additive migrations for all four providers) and answered 202; a background worker runs every IPackageValidator (entry paths, signature integrity, optional required signatures, plus any registered hook), then repository-signs and indexes the package. Until then it does not exist, so no read path changes and it cannot be downloaded; a failure stays quarantined with its reasons, readable at v3/package/{id}/{version}/validation. Pending submissions are re-queued on start. RepositorySignatures/5.0.0 is advertised while a signing certificate is configured. Also merges the symbol package validation branch. --- BaGet.sln | 17 +- src/BaGet.Core/Configuration/BaGetOptions.cs | 2 + .../Configuration/ValidationOptions.cs | 37 + src/BaGet.Core/Entities/AbstractContext.cs | 23 + src/BaGet.Core/Entities/IContext.cs | 2 + src/BaGet.Core/Entities/NullContext.cs | 2 + src/BaGet.Core/Entities/PackageValidation.cs | 63 ++ .../DependencyInjectionExtensions.cs | 2 + src/BaGet.Core/IUrlGenerator.cs | 12 + .../Indexing/IPackageIndexingService.cs | 5 + .../Indexing/IPackageSubmissionService.cs | 35 + ...17014351_AddPackageValidations.Designer.cs | 845 +++++++++++++++++ .../20261017014351_AddPackageValidations.cs | 70 ++ .../Migrations/MySqlContextModelSnapshot.cs | 64 ++ ...17014349_AddPackageValidations.Designer.cs | 846 +++++++++++++++++ .../20261017014349_AddPackageValidations.cs | 64 ++ .../PostgreSqlContextModelSnapshot.cs | 64 ++ ...17014346_AddPackageValidations.Designer.cs | 848 ++++++++++++++++++ .../20261017014346_AddPackageValidations.cs | 63 ++ .../SqlServerContextModelSnapshot.cs | 64 ++ ...17014343_AddPackageValidations.Designer.cs | 812 +++++++++++++++++ .../20261017014343_AddPackageValidations.cs | 63 ++ .../Migrations/SqliteContextModelSnapshot.cs | 62 ++ src/BaGet.Validation/BaGet.Validation.csproj | 27 + src/BaGet.Validation/IPackageValidator.cs | 69 ++ .../PackageValidationRunner.cs | 189 ++++ .../RepositorySignaturesController.cs | 225 +++++ src/BaGet.Validation/RepositorySigner.cs | 112 +++ .../ValidatingPackageSubmissionService.cs | 131 +++ src/BaGet.Validation/ValidationQueue.cs | 31 + .../ValidationServiceCollectionExtensions.cs | 30 + src/BaGet.Validation/ValidationWorker.cs | 78 ++ src/BaGet.Validation/Validators.cs | 96 ++ src/BaGet.Web/BaGet.Web.csproj | 1 + src/BaGet.Web/BaGetEndpointBuilder.cs | 22 + src/BaGet.Web/BaGetUrlGenerator.cs | 10 + .../Controllers/PackagePublishController.cs | 17 +- .../IServiceCollectionExtensions.cs | 2 + src/BaGet.Web/Routes.cs | 3 + tests/BaGet.Tests/Support/BaGetApplication.cs | 6 +- .../BaGet.Tests/ValidationIntegrationTests.cs | 296 ++++++ 41 files changed, 5403 insertions(+), 7 deletions(-) create mode 100644 src/BaGet.Core/Configuration/ValidationOptions.cs create mode 100644 src/BaGet.Core/Entities/PackageValidation.cs create mode 100644 src/BaGet.Core/Indexing/IPackageSubmissionService.cs create mode 100644 src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.Designer.cs create mode 100644 src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.cs create mode 100644 src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.Designer.cs create mode 100644 src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.cs create mode 100644 src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.Designer.cs create mode 100644 src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.cs create mode 100644 src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.Designer.cs create mode 100644 src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.cs create mode 100644 src/BaGet.Validation/BaGet.Validation.csproj create mode 100644 src/BaGet.Validation/IPackageValidator.cs create mode 100644 src/BaGet.Validation/PackageValidationRunner.cs create mode 100644 src/BaGet.Validation/RepositorySignaturesController.cs create mode 100644 src/BaGet.Validation/RepositorySigner.cs create mode 100644 src/BaGet.Validation/ValidatingPackageSubmissionService.cs create mode 100644 src/BaGet.Validation/ValidationQueue.cs create mode 100644 src/BaGet.Validation/ValidationServiceCollectionExtensions.cs create mode 100644 src/BaGet.Validation/ValidationWorker.cs create mode 100644 src/BaGet.Validation/Validators.cs create mode 100644 tests/BaGet.Tests/ValidationIntegrationTests.cs diff --git a/BaGet.sln b/BaGet.sln index 1cfffe9ab..44d632a18 100644 --- a/BaGet.sln +++ b/BaGet.sln @@ -60,6 +60,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Web.V2", "src\BaGet.W EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Identity", "src\BaGet.Identity\BaGet.Identity.csproj", "{C8689F3D-B2C3-4B67-B2D6-6727AD11103D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaGet.Validation", "src\BaGet.Validation\BaGet.Validation.csproj", "{E2D03D72-23F2-409E-B895-45BAEEC75768}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -334,12 +336,24 @@ Global {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|x64.Build.0 = Release|Any CPU {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|x86.ActiveCfg = Release|Any CPU {C8689F3D-B2C3-4B67-B2D6-6727AD11103D}.Release|x86.Build.0 = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|x64.ActiveCfg = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|x64.Build.0 = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|x86.ActiveCfg = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Debug|x86.Build.0 = Debug|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|Any CPU.Build.0 = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|x64.ActiveCfg = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|x64.Build.0 = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|x86.ActiveCfg = Release|Any CPU + {E2D03D72-23F2-409E-B895-45BAEEC75768}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {C8689F3D-B2C3-4B67-B2D6-6727AD11103D} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {E2D03D72-23F2-409E-B895-45BAEEC75768} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} {284366CB-C68F-473E-908A-50A382616AE0} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} {FFFACD28-C300-4046-BCFE-4A7899E88EA3} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} {716C970D-9614-4265-AC92-57E8B227B98E} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} @@ -361,6 +375,7 @@ Global {493DE3CC-BE24-4206-88C6-7BDE7721EF10} = {C237857D-AD8E-4C52-974F-6A8155BB0C18} {17C1E34E-AAAC-46C0-9A38-86DAC1D5D399} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} {6F4FBCFC-6887-4401-A0B7-A856C91011BA} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} + {C8689F3D-B2C3-4B67-B2D6-6727AD11103D} = {26A0B557-53FB-4B9A-94C4-BCCF1BDCB0CC} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1423C027-2C90-417F-8629-2A4CF107C055} diff --git a/src/BaGet.Core/Configuration/BaGetOptions.cs b/src/BaGet.Core/Configuration/BaGetOptions.cs index 6dc751949..347061539 100644 --- a/src/BaGet.Core/Configuration/BaGetOptions.cs +++ b/src/BaGet.Core/Configuration/BaGetOptions.cs @@ -54,5 +54,7 @@ public class BaGetOptions public FeedsOptions Feeds { get; set; } public AccountsOptions Accounts { get; set; } + + public ValidationOptions Validation { get; set; } } } diff --git a/src/BaGet.Core/Configuration/ValidationOptions.cs b/src/BaGet.Core/Configuration/ValidationOptions.cs new file mode 100644 index 000000000..5f837e1af --- /dev/null +++ b/src/BaGet.Core/Configuration/ValidationOptions.cs @@ -0,0 +1,37 @@ +namespace BaGet.Core +{ + /// + /// Asynchronous validation of pushed packages. + /// + public class ValidationOptions + { + /// + /// Off by default. With it off a push is indexed at once, exactly as before. + /// With it on, a push answers 202 Accepted and the package appears once every + /// validator has passed; a package that fails is quarantined, never served. + /// + public bool Enabled { get; set; } + + /// + /// Reject packages without a valid author or repository signature. + /// + public bool RequireSignedPackages { get; set; } + + /// + /// A PFX file whose certificate repository-signs every package that passes + /// validation. Unused unless set; the RepositorySignatures resource is only + /// advertised when it is. + /// + public string RepositorySigningCertificatePath { get; set; } + + public string RepositorySigningCertificatePassword { get; set; } + + /// + /// This server's public service index URL, recorded in every repository signature; + /// a client checks it against the source it restored from. Required for signing, + /// since signing runs in the background, outside any request to read it from, and + /// it must be https: NuGet rejects a repository signature for any other scheme. + /// + public string RepositorySigningServiceIndexUrl { get; set; } + } +} diff --git a/src/BaGet.Core/Entities/AbstractContext.cs b/src/BaGet.Core/Entities/AbstractContext.cs index caca912c5..9432aa0a7 100644 --- a/src/BaGet.Core/Entities/AbstractContext.cs +++ b/src/BaGet.Core/Entities/AbstractContext.cs @@ -34,6 +34,8 @@ public abstract class AbstractContext : IdentityDbContext, public const int MaxApiKeyDescriptionLength = 256; public const int MaxApiKeyHashLength = 64; + public const int MaxValidationTypeLength = 64; + public AbstractContext(DbContextOptions options) : base(options) { } @@ -49,6 +51,7 @@ public AbstractContext(DbContextOptions options) public DbSet OrganizationMembers { get; set; } public DbSet PackageOwners { get; set; } public DbSet ApiKeys { get; set; } + public DbSet PackageValidations { get; set; } public Task SaveChangesAsync() => SaveChangesAsync(default); @@ -74,6 +77,7 @@ protected override void OnModelCreating(ModelBuilder builder) builder.Entity(BuildOrganizationMemberEntity); builder.Entity(BuildPackageOwnerEntity); builder.Entity(BuildApiKeyEntity); + builder.Entity(BuildPackageValidationEntity); } private void BuildPackageEntity(EntityTypeBuilder package) @@ -257,6 +261,25 @@ private void BuildApiKeyEntity(EntityTypeBuilder apiKey) .Metadata.SetValueComparer(StringArrayComparer.Instance); } + private void BuildPackageValidationEntity(EntityTypeBuilder validation) + { + validation.HasKey(v => v.Key); + validation.HasIndex(v => v.SubmissionId); + validation.HasIndex(v => v.PackageId); + + validation.Property(v => v.SubmissionId).HasMaxLength(MaxCatalogCommitIdLength).IsRequired(); + validation.Property(v => v.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + validation.Property(v => v.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + validation.Property(v => v.Type).HasMaxLength(MaxValidationTypeLength).IsRequired(); + validation.Property(v => v.Message).HasMaxLength(DefaultMaxStringLength); + + validation + .HasOne(v => v.Package) + .WithMany() + .HasForeignKey(v => v.PackageKey) + .IsRequired(false); + } + private void BuildPackageDependencyEntity(EntityTypeBuilder dependency) { dependency.HasKey(d => d.Key); diff --git a/src/BaGet.Core/Entities/IContext.cs b/src/BaGet.Core/Entities/IContext.cs index e58445135..29528f0fc 100644 --- a/src/BaGet.Core/Entities/IContext.cs +++ b/src/BaGet.Core/Entities/IContext.cs @@ -38,6 +38,8 @@ public interface IContext DbSet ApiKeys { get; set; } + DbSet PackageValidations { get; set; } + /// /// Identity's users. Declared here so that account services can query them through /// the same context as everything else. diff --git a/src/BaGet.Core/Entities/NullContext.cs b/src/BaGet.Core/Entities/NullContext.cs index 80468dde9..2f8451bef 100644 --- a/src/BaGet.Core/Entities/NullContext.cs +++ b/src/BaGet.Core/Entities/NullContext.cs @@ -28,6 +28,8 @@ public class NullContext : IContext public DbSet ApiKeys { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet PackageValidations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet Users { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public bool SupportsLimitInSubqueries => throw new NotImplementedException(); diff --git a/src/BaGet.Core/Entities/PackageValidation.cs b/src/BaGet.Core/Entities/PackageValidation.cs new file mode 100644 index 000000000..f53832a58 --- /dev/null +++ b/src/BaGet.Core/Entities/PackageValidation.cs @@ -0,0 +1,63 @@ +using System; + +namespace BaGet.Core +{ + public enum PackageValidationState + { + Pending = 0, + Succeeded = 1, + Failed = 2, + } + + /// + /// One step of validating a pushed package: a validator's verdict, or the final + /// indexing step. A submission is every row sharing a . + /// + /// + /// The package does not exist while it is validated: it is staged in storage and only + /// indexed once every validator succeeds. So nothing that serves packages needs to + /// know about validation, and a package being validated cannot be downloaded. + /// + public class PackageValidation + { + /// + /// The of the step that indexes the package once it is valid. + /// + public const string IndexType = "Index"; + + public int Key { get; set; } + + public string SubmissionId { get; set; } + + public string PackageId { get; set; } + + /// + /// The normalized version. + /// + public string PackageVersion { get; set; } + + /// + /// The indexed package, once the submission succeeds. Nullable so that the + /// relationship is additive; see . + /// + public int? PackageKey { get; set; } + + public Package Package { get; set; } + + /// + /// The validator's name, or . + /// + public string Type { get; set; } + + public PackageValidationState State { get; set; } + + /// + /// Why the step failed, if it did. + /// + public string Message { get; set; } + + public DateTime Created { get; set; } + + public DateTime? Completed { get; set; } + } +} diff --git a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs index 2c452eb60..09c45e12c 100644 --- a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs +++ b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs @@ -67,6 +67,7 @@ private static void AddConfiguration(this IServiceCollection services) services.AddBaGetOptions(nameof(BaGetOptions.Mirror)); services.AddBaGetOptions(nameof(BaGetOptions.Feeds)); services.AddBaGetOptions(nameof(BaGetOptions.Accounts)); + services.AddBaGetOptions(nameof(BaGetOptions.Validation)); services.AddBaGetOptions(nameof(BaGetOptions.Search)); services.AddBaGetOptions(nameof(BaGetOptions.Storage)); } @@ -93,6 +94,7 @@ private static void AddBaGetServices(this IServiceCollection services) services.TryAddTransient(); services.TryAddTransient(); services.TryAddTransient(); + services.TryAddTransient(); services.TryAddTransient(); services.TryAddTransient(); services.TryAddTransient(); diff --git a/src/BaGet.Core/IUrlGenerator.cs b/src/BaGet.Core/IUrlGenerator.cs index 5d66b459f..1cc5a943e 100644 --- a/src/BaGet.Core/IUrlGenerator.cs +++ b/src/BaGet.Core/IUrlGenerator.cs @@ -93,6 +93,18 @@ public interface IUrlGenerator /// The ID of the commit that wrote the leaf. string GetCatalogLeafUrl(string commitId); + /// + /// Get the URL of the repository signatures resource. + /// See: https://learn.microsoft.com/en-us/nuget/api/repository-signatures-resource + /// + string GetRepositorySignaturesUrl(); + + /// + /// Get the URL to download a repository signing certificate. + /// + /// The certificate's SHA-256 fingerprint, as lowercase hex. + string GetRepositorySigningCertificateUrl(string fingerprint); + /// /// Get the URL for the entry point of a package's metadata. /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index diff --git a/src/BaGet.Core/Indexing/IPackageIndexingService.cs b/src/BaGet.Core/Indexing/IPackageIndexingService.cs index ddbf06d27..db7844559 100644 --- a/src/BaGet.Core/Indexing/IPackageIndexingService.cs +++ b/src/BaGet.Core/Indexing/IPackageIndexingService.cs @@ -24,6 +24,11 @@ public enum PackageIndexingResult /// The package has been indexed successfully. /// Success, + + /// + /// The package was queued for validation and is not available yet. + /// + Accepted, } /// diff --git a/src/BaGet.Core/Indexing/IPackageSubmissionService.cs b/src/BaGet.Core/Indexing/IPackageSubmissionService.cs new file mode 100644 index 000000000..c6e5466c4 --- /dev/null +++ b/src/BaGet.Core/Indexing/IPackageSubmissionService.cs @@ -0,0 +1,35 @@ +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace BaGet.Core +{ + /// + /// Accepts a package a user pushed. Unlike , which + /// always indexes at once and which mirroring uses, a submission may be validated first. + /// + public interface IPackageSubmissionService + { + /// + /// if the package is queued for + /// validation, otherwise the result of indexing it. + /// + Task SubmitAsync(Stream package, CancellationToken cancellationToken); + } + + /// + /// Indexes every submission at once: the behaviour without validation. + /// + public class DirectPackageSubmissionService : IPackageSubmissionService + { + private readonly IPackageIndexingService _indexer; + + public DirectPackageSubmissionService(IPackageIndexingService indexer) + { + _indexer = indexer ?? throw new System.ArgumentNullException(nameof(indexer)); + } + + public Task SubmitAsync(Stream package, CancellationToken cancellationToken) + => _indexer.IndexAsync(package, cancellationToken); + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.Designer.cs new file mode 100644 index 000000000..624f5097b --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.Designer.cs @@ -0,0 +1,845 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261017014351_AddPackageValidations")] + partial class AddPackageValidations + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.cs b/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.cs new file mode 100644 index 000000000..71f3717ef --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017014351_AddPackageValidations.cs @@ -0,0 +1,70 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddPackageValidations : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageValidations", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + SubmissionId = table.Column(type: "varchar(36)", maxLength: 36, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageId = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageVersion = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageKey = table.Column(type: "int", nullable: true), + Type = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + State = table.Column(type: "int", nullable: false), + Message = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Completed = table.Column(type: "datetime(6)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageValidations", x => x.Key); + table.ForeignKey( + name: "FK_PackageValidations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageKey", + table: "PackageValidations", + column: "PackageKey"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_SubmissionId", + table: "PackageValidations", + column: "SubmissionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageValidations"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs b/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs index 759b5b293..6335d7126 100644 --- a/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs +++ b/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs @@ -466,6 +466,61 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("PackageTypes"); }); + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => { b.Property("Key") @@ -689,6 +744,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Package"); }); + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => { b.HasOne("BaGet.Core.Package", "Package") diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.Designer.cs new file mode 100644 index 000000000..73d78e595 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.Designer.cs @@ -0,0 +1,846 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261017014349_AddPackageValidations")] + partial class AddPackageValidations + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.cs new file mode 100644 index 000000000..d8f0bdf3e --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017014349_AddPackageValidations.cs @@ -0,0 +1,64 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddPackageValidations : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageValidations", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + SubmissionId = table.Column(type: "character varying(36)", maxLength: 36, nullable: false), + PackageId = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + PackageKey = table.Column(type: "integer", nullable: true), + Type = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + State = table.Column(type: "integer", nullable: false), + Message = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Completed = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageValidations", x => x.Key); + table.ForeignKey( + name: "FK_PackageValidations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageKey", + table: "PackageValidations", + column: "PackageKey"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_SubmissionId", + table: "PackageValidations", + column: "SubmissionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageValidations"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs b/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs index 4dd656942..967881e4e 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs @@ -467,6 +467,61 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("PackageTypes"); }); + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => { b.Property("Key") @@ -690,6 +745,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Package"); }); + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => { b.HasOne("BaGet.Core.Package", "Package") diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.Designer.cs new file mode 100644 index 000000000..94ab371c3 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.Designer.cs @@ -0,0 +1,848 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261017014346_AddPackageValidations")] + partial class AddPackageValidations + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.cs b/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.cs new file mode 100644 index 000000000..0d7037462 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017014346_AddPackageValidations.cs @@ -0,0 +1,63 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddPackageValidations : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageValidations", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + SubmissionId = table.Column(type: "nvarchar(36)", maxLength: 36, nullable: false), + PackageId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + PackageKey = table.Column(type: "int", nullable: true), + Type = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + State = table.Column(type: "int", nullable: false), + Message = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + Completed = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageValidations", x => x.Key); + table.ForeignKey( + name: "FK_PackageValidations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageKey", + table: "PackageValidations", + column: "PackageKey"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_SubmissionId", + table: "PackageValidations", + column: "SubmissionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageValidations"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs b/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs index 837f8a9ba..bfd94884b 100644 --- a/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs +++ b/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs @@ -468,6 +468,61 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("PackageTypes"); }); + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => { b.Property("Key") @@ -692,6 +747,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Package"); }); + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => { b.HasOne("BaGet.Core.Package", "Package") diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.Designer.cs new file mode 100644 index 000000000..fdb18f5c0 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.Designer.cs @@ -0,0 +1,812 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261017014343_AddPackageValidations")] + partial class AddPackageValidations + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.cs b/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.cs new file mode 100644 index 000000000..55b5feb25 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017014343_AddPackageValidations.cs @@ -0,0 +1,63 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddPackageValidations : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PackageValidations", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + SubmissionId = table.Column(type: "TEXT", maxLength: 36, nullable: false), + PackageId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "TEXT", maxLength: 64, nullable: false), + PackageKey = table.Column(type: "INTEGER", nullable: true), + Type = table.Column(type: "TEXT", maxLength: 64, nullable: false), + State = table.Column(type: "INTEGER", nullable: false), + Message = table.Column(type: "TEXT", maxLength: 4000, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Completed = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PackageValidations", x => x.Key); + table.ForeignKey( + name: "FK_PackageValidations_Packages_PackageKey", + column: x => x.PackageKey, + principalTable: "Packages", + principalColumn: "Key"); + }); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageId", + table: "PackageValidations", + column: "PackageId"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_PackageKey", + table: "PackageValidations", + column: "PackageKey"); + + migrationBuilder.CreateIndex( + name: "IX_PackageValidations_SubmissionId", + table: "PackageValidations", + column: "SubmissionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PackageValidations"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs b/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs index 50c524174..45ba2aa9c 100644 --- a/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs +++ b/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs @@ -443,6 +443,59 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("PackageTypes"); }); + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => { b.Property("Key") @@ -658,6 +711,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Package"); }); + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => { b.HasOne("BaGet.Core.Package", "Package") diff --git a/src/BaGet.Validation/BaGet.Validation.csproj b/src/BaGet.Validation/BaGet.Validation.csproj new file mode 100644 index 000000000..2cf7b4b40 --- /dev/null +++ b/src/BaGet.Validation/BaGet.Validation.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + + NuGet + BaGet's validation pipeline: pushed packages are validated, and optionally repository signed, before they are served. + BaGet.Validation + + + + + + + + + + + + + + + + + + + diff --git a/src/BaGet.Validation/IPackageValidator.cs b/src/BaGet.Validation/IPackageValidator.cs new file mode 100644 index 000000000..6fddeb251 --- /dev/null +++ b/src/BaGet.Validation/IPackageValidator.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using NuGet.Packaging; +using NuGet.Versioning; + +namespace BaGet.Validation +{ + /// + /// Decides whether a pushed package may be served. Register any number, for example a + /// malware scanner; every one must pass. A validator that throws fails the package. + /// + public interface IPackageValidator + { + /// + /// Recorded as the validation step's type, so it must be stable and unique. + /// + string Name { get; } + + Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken); + } + + public sealed class PackageValidationContext + { + public PackageValidationContext(string packageId, NuGetVersion packageVersion, Stream package, PackageArchiveReader reader) + { + PackageId = packageId; + PackageVersion = packageVersion; + Package = package; + Reader = reader; + } + + public string PackageId { get; } + + public NuGetVersion PackageVersion { get; } + + /// + /// The raw package. Seekable; a validator must not dispose it. + /// + public Stream Package { get; } + + /// + /// A reader over . A validator must not dispose it. + /// + public PackageArchiveReader Reader { get; } + } + + public sealed class PackageValidatorResult + { + public static readonly PackageValidatorResult Valid = new PackageValidatorResult(true, null); + + private PackageValidatorResult(bool isValid, string message) + { + IsValid = isValid; + Message = message; + } + + public bool IsValid { get; } + + /// + /// Why the package is invalid. Shown to the package's owners. + /// + public string Message { get; } + + public static PackageValidatorResult Invalid(string message) + => new PackageValidatorResult(false, message ?? throw new ArgumentNullException(nameof(message))); + } +} diff --git a/src/BaGet.Validation/PackageValidationRunner.cs b/src/BaGet.Validation/PackageValidationRunner.cs new file mode 100644 index 000000000..ea9621386 --- /dev/null +++ b/src/BaGet.Validation/PackageValidationRunner.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Packaging; + +namespace BaGet.Validation +{ + /// + /// Runs one submission: every validator, then, if all passed, repository signing and + /// indexing. A package that fails stays staged, quarantined, for its owners to inspect. + /// + public class PackageValidationRunner + { + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IPackageIndexingService _indexer; + private readonly IPackageDatabase _packages; + private readonly IEnumerable _validators; + private readonly RepositorySigner _signer; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + private readonly ILogger _logger; + + public PackageValidationRunner( + IContext context, + IStorageService storage, + IPackageIndexingService indexer, + IPackageDatabase packages, + IEnumerable validators, + RepositorySigner signer, + SystemTime time, + IOptionsSnapshot options, + ILogger logger) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _validators = validators ?? throw new ArgumentNullException(nameof(validators)); + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task> GetPendingSubmissionIdsAsync(CancellationToken cancellationToken) + { + return await _context.PackageValidations + .Where(v => v.State == PackageValidationState.Pending) + .Select(v => v.SubmissionId) + .Distinct() + .ToListAsync(cancellationToken); + } + + public async Task RunAsync(string submissionId, CancellationToken cancellationToken) + { + var steps = await _context.PackageValidations + .Where(v => v.SubmissionId == submissionId) + .ToListAsync(cancellationToken); + + var index = steps.SingleOrDefault(s => s.Type == PackageValidation.IndexType); + if (index == null || index.State != PackageValidationState.Pending) + { + return; + } + + using var package = new MemoryStream(); + using (var staged = await _storage.GetAsync(ValidatingPackageSubmissionService.StagedPath(submissionId), cancellationToken)) + { + await staged.CopyToAsync(package, cancellationToken); + } + + package.Position = 0; + + using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) + { + var identity = await reader.GetIdentityAsync(cancellationToken); + var context = new PackageValidationContext(identity.Id, identity.Version, package, reader); + + foreach (var validator in _validators) + { + var step = steps.FirstOrDefault(s => s.Type == validator.Name); + if (step == null || step.State != PackageValidationState.Pending) continue; + + PackageValidatorResult result; + try + { + package.Position = 0; + result = await validator.ValidateAsync(context, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogError(e, "Validator {Validator} failed on submission {SubmissionId}", validator.Name, submissionId); + result = PackageValidatorResult.Invalid($"The {validator.Name} validator failed: {e.Message}"); + } + + Complete(step, result.IsValid, result.Message); + } + } + + // A step whose validator is no longer registered cannot pass. + foreach (var orphan in steps.Where(s => s.State == PackageValidationState.Pending && s != index)) + { + Complete(orphan, succeeded: false, $"The {orphan.Type} validator is no longer registered."); + } + + if (steps.Any(s => s.State == PackageValidationState.Failed)) + { + Complete(index, succeeded: false, "Quarantined: the package failed validation."); + await _context.SaveChangesAsync(cancellationToken); + + _logger.LogWarning("Submission {SubmissionId} failed validation and is quarantined", submissionId); + return; + } + + var indexError = await IndexAsync(package, _options.Value.RepositorySigningServiceIndexUrl, cancellationToken); + Complete(index, indexError == null, indexError); + + if (indexError == null) + { + var version = NuGet.Versioning.NuGetVersion.Parse(index.PackageVersion); + var indexed = await _packages.FindOrNullAsync(index.PackageId, version, includeUnlisted: true, cancellationToken); + foreach (var step in steps) + { + step.PackageKey = indexed?.Key; + } + } + + await _context.SaveChangesAsync(cancellationToken); + + if (indexError == null) + { + await _storage.DeleteAsync(ValidatingPackageSubmissionService.StagedPath(submissionId), cancellationToken); + } + } + + /// Null on success, otherwise why indexing failed. + private async Task IndexAsync(Stream package, string serviceIndexUrl, CancellationToken cancellationToken) + { + Stream toIndex = package; + try + { + if (_signer.IsConfigured) + { + // NuGet only accepts a repository signature that names an https source. + if (!Uri.TryCreate(serviceIndexUrl, UriKind.Absolute, out var url) || url.Scheme != Uri.UriSchemeHttps) + { + return "Repository signing needs Validation:RepositorySigningServiceIndexUrl to be an absolute https URL."; + } + + toIndex = await _signer.SignAsync(package, serviceIndexUrl, cancellationToken); + } + + toIndex.Position = 0; + var result = await _indexer.IndexAsync(toIndex, cancellationToken); + + return result == PackageIndexingResult.Success ? null : $"Indexing failed: {result}."; + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogError(e, "Failed to index a validated package"); + return $"Indexing failed: {e.Message}"; + } + finally + { + if (!ReferenceEquals(toIndex, package)) + { + toIndex.Dispose(); + } + } + } + + private void Complete(PackageValidation step, bool succeeded, string message) + { + step.State = succeeded ? PackageValidationState.Succeeded : PackageValidationState.Failed; + step.Message = message?.Length > AbstractContext.DefaultMaxStringLength + ? message.Substring(0, AbstractContext.DefaultMaxStringLength) + : message; + step.Completed = _time.UtcNow; + } + } +} diff --git a/src/BaGet.Validation/RepositorySignaturesController.cs b/src/BaGet.Validation/RepositorySignaturesController.cs new file mode 100644 index 000000000..eb46b64b9 --- /dev/null +++ b/src/BaGet.Validation/RepositorySignaturesController.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Protocol.Models; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; + +namespace BaGet.Validation +{ + /// + /// The RepositorySignatures/5.0.0 resource, and each submission's validation status. + /// + public class RepositorySignaturesController : Controller + { + // The OID the protocol keys a SHA-256 fingerprint by. + internal const string Sha256Oid = "2.16.840.1.101.3.4.2.1"; + + private readonly RepositorySigner _signer; + private readonly IUrlGenerator _url; + + public RepositorySignaturesController(RepositorySigner signer, IUrlGenerator url) + { + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } + + [HttpGet] + public IActionResult Index() + { + using var certificate = _signer.GetPublicCertificateOrNull(); + if (certificate == null) return NotFound(); + + var fingerprint = Fingerprint(certificate.RawData); + + return Json(new RepositorySignaturesResponse + { + // Packages pushed before signing was configured, and mirrored ones, are not + // repository signed, so a client must not insist that every package is. + AllRepositorySigned = false, + SigningCertificates = new[] + { + new RepositorySigningCertificate + { + Fingerprints = new Dictionary { [Sha256Oid] = fingerprint }, + Subject = certificate.Subject, + Issuer = certificate.Issuer, + NotBefore = certificate.NotBefore.ToUniversalTime(), + NotAfter = certificate.NotAfter.ToUniversalTime(), + ContentUrl = _url.GetRepositorySigningCertificateUrl(fingerprint), + }, + }, + }); + } + + [HttpGet] + public IActionResult Certificate(string fingerprint) + { + using var certificate = _signer.GetPublicCertificateOrNull(); + if (certificate == null || !string.Equals(Fingerprint(certificate.RawData), fingerprint, StringComparison.OrdinalIgnoreCase)) + { + return NotFound(); + } + + return File(certificate.RawData, "application/pkix-cert"); + } + + internal static string Fingerprint(byte[] certificate) + => Convert.ToHexString(SHA256.HashData(certificate)).ToLowerInvariant(); + } + + /// + /// A package version's validation, for its owners: whether it is pending, available + /// or quarantined, and why. + /// + public class ValidationStatusController : Controller + { + private readonly IContext _context; + private readonly Core.IAuthenticationService _authentication; + private readonly IPackageAuthorizationService _authorization; + + public ValidationStatusController( + IContext context, + Core.IAuthenticationService authentication, + IPackageAuthorizationService authorization) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + } + + [HttpGet] + public async Task Get(string id, string version, CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var nugetVersion)) return NotFound(); + + var principal = await _authentication.AuthenticatePrincipalAsync(Request.Headers["X-NuGet-ApiKey"], cancellationToken); + if (principal == null) return Unauthorized(); + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, id, cancellationToken) + && !await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken)) + { + return StatusCode(403); + } + + if (_context is NullContext) return NotFound(); + + var lowerId = id.ToLowerInvariant(); + var normalized = nugetVersion.ToNormalizedString(); + var steps = await _context.PackageValidations + .AsNoTracking() + .Where(v => v.PackageId.ToLower() == lowerId && v.PackageVersion == normalized) + .OrderByDescending(v => v.Key) + .ToListAsync(cancellationToken); + + if (steps.Count == 0) return NotFound(); + + // The newest submission is the one that matters. + var latest = steps[0].SubmissionId; + var submission = steps.Where(s => s.SubmissionId == latest).OrderBy(s => s.Key).ToList(); + var index = submission.Single(s => s.Type == PackageValidation.IndexType); + + return Json(new ValidationStatusResponse + { + SubmissionId = latest, + Status = index.State switch + { + PackageValidationState.Succeeded => "Available", + PackageValidationState.Failed => "Quarantined", + _ => "Validating", + }, + Steps = submission + .Select(s => new ValidationStep { Type = s.Type, State = s.State.ToString(), Message = s.Message }) + .ToList(), + }); + } + } + + public class RepositorySignaturesResponse + { + [JsonPropertyName("allRepositorySigned")] + public bool AllRepositorySigned { get; set; } + + [JsonPropertyName("signingCertificates")] + public IReadOnlyList SigningCertificates { get; set; } + } + + public class RepositorySigningCertificate + { + [JsonPropertyName("fingerprints")] + public IReadOnlyDictionary Fingerprints { get; set; } + + [JsonPropertyName("subject")] + public string Subject { get; set; } + + [JsonPropertyName("issuer")] + public string Issuer { get; set; } + + [JsonPropertyName("notBefore")] + public DateTime NotBefore { get; set; } + + [JsonPropertyName("notAfter")] + public DateTime NotAfter { get; set; } + + [JsonPropertyName("contentUrl")] + public string ContentUrl { get; set; } + } + + public class ValidationStatusResponse + { + [JsonPropertyName("submissionId")] + public string SubmissionId { get; set; } + + /// + /// "Validating", "Available" or "Quarantined". + /// + [JsonPropertyName("status")] + public string Status { get; set; } + + [JsonPropertyName("steps")] + public IReadOnlyList Steps { get; set; } + } + + public class ValidationStep + { + [JsonPropertyName("type")] + public string Type { get; set; } + + [JsonPropertyName("state")] + public string State { get; set; } + + [JsonPropertyName("message")] + public string Message { get; set; } + } + + /// + /// Advertises RepositorySignatures/5.0.0 while a signing certificate is configured. + /// + public class RepositorySignaturesServiceIndexProvider : IServiceIndexResourceProvider + { + private readonly RepositorySigner _signer; + private readonly IUrlGenerator _url; + + public RepositorySignaturesServiceIndexProvider(RepositorySigner signer, IUrlGenerator url) + { + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } + + public IEnumerable GetResources() + { + if (!_signer.IsConfigured) yield break; + + yield return new ServiceIndexItem + { + ResourceUrl = _url.GetRepositorySignaturesUrl(), + Type = "RepositorySignatures/5.0.0", + }; + } + } +} diff --git a/src/BaGet.Validation/RepositorySigner.cs b/src/BaGet.Validation/RepositorySigner.cs new file mode 100644 index 000000000..5cd1d5f34 --- /dev/null +++ b/src/BaGet.Validation/RepositorySigner.cs @@ -0,0 +1,112 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.Options; +using NuGet.Common; +using NuGet.Packaging.Signing; + +namespace BaGet.Validation +{ + /// + /// Repository-signs validated packages with the configured certificate, so a client can + /// tell a package came through this server. See: + /// https://learn.microsoft.com/en-us/nuget/api/repository-signatures-resource + /// + public class RepositorySigner + { + private readonly IOptionsSnapshot _options; + + public RepositorySigner(IOptionsSnapshot options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public bool IsConfigured => !string.IsNullOrEmpty(_options.Value.RepositorySigningCertificatePath); + + /// + /// The configured certificate, without its private key, or null if none is. + /// + public X509Certificate2 GetPublicCertificateOrNull() + { + if (!IsConfigured) return null; + + using var certificate = LoadCertificate(); + + return X509CertificateLoader.LoadCertificate(certificate.RawData); + } + + /// + /// Sign a package, returning the signed copy. A package that already has a + /// repository signature is returned as it is. + /// + /// + /// This server's service index. The signature records it, and a client checks that + /// it matches the source the package came from. + /// + public async Task SignAsync(Stream package, string serviceIndexUrl, CancellationToken cancellationToken) + { + var directory = Path.Combine(Path.GetTempPath(), "BaGetSigning", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + + var input = Path.Combine(directory, "input.nupkg"); + var output = Path.Combine(directory, "output.nupkg"); + + try + { + using (var file = File.Create(input)) + { + package.Position = 0; + await package.CopyToAsync(file, cancellationToken); + } + + using (var certificate = LoadCertificate()) + using (var request = new RepositorySignPackageRequest( + certificate, + NuGet.Common.HashAlgorithmName.SHA256, + NuGet.Common.HashAlgorithmName.SHA256, + new Uri(serviceIndexUrl), + packageOwners: null)) + using (var options = SigningOptions.CreateFromFilePaths( + input, + output, + overwrite: true, + signatureProvider: new X509SignatureProvider(timestampProvider: null), + logger: NullLogger.Instance)) + { + await SigningUtility.SignAsync(options, request, cancellationToken); + } + + var signed = new MemoryStream(); + using (var file = File.OpenRead(output)) + { + await file.CopyToAsync(signed, cancellationToken); + } + + signed.Position = 0; + + return signed; + } + finally + { + try + { + Directory.Delete(directory, recursive: true); + } + catch (IOException) + { + // A temporary file left behind is not worth failing the push for. + } + } + } + + private X509Certificate2 LoadCertificate() + => X509CertificateLoader.LoadPkcs12FromFile( + _options.Value.RepositorySigningCertificatePath, + _options.Value.RepositorySigningCertificatePassword, + X509KeyStorageFlags.EphemeralKeySet); + } +} diff --git a/src/BaGet.Validation/ValidatingPackageSubmissionService.cs b/src/BaGet.Validation/ValidatingPackageSubmissionService.cs new file mode 100644 index 000000000..31e88841b --- /dev/null +++ b/src/BaGet.Validation/ValidatingPackageSubmissionService.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NuGet.Packaging; + +namespace BaGet.Validation +{ + /// + /// With validation on, stages a pushed package and queues it; otherwise indexes it at + /// once, exactly as before. + /// + public class ValidatingPackageSubmissionService : IPackageSubmissionService + { + private readonly IPackageIndexingService _indexer; + private readonly IPackageDatabase _packages; + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IValidationQueue _queue; + private readonly IEnumerable _validators; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + private readonly IOptionsSnapshot _validation; + private readonly ILogger _logger; + + public ValidatingPackageSubmissionService( + IPackageIndexingService indexer, + IPackageDatabase packages, + IContext context, + IStorageService storage, + IValidationQueue queue, + IEnumerable validators, + SystemTime time, + IOptionsSnapshot options, + IOptionsSnapshot validation, + ILogger logger) + { + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _validators = validators ?? throw new ArgumentNullException(nameof(validators)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _validation = validation ?? throw new ArgumentNullException(nameof(validation)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + internal static string StagedPath(string submissionId) => $"validation/{submissionId}.nupkg"; + + public async Task SubmitAsync(Stream package, CancellationToken cancellationToken) + { + if (!_validation.Value.Enabled) + { + return await _indexer.IndexAsync(package, cancellationToken); + } + + string id; + string version; + try + { + using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) + { + var identity = reader.GetIdentity(); + id = identity.Id; + version = identity.Version.ToNormalizedString(); + } + } + catch (Exception e) + { + _logger.LogError(e, "Uploaded package is invalid"); + return PackageIndexingResult.InvalidPackage; + } + + if (!_options.Value.AllowPackageOverwrites + && await _packages.ExistsAsync(id, NuGet.Versioning.NuGetVersion.Parse(version), cancellationToken)) + { + return PackageIndexingResult.PackageAlreadyExists; + } + + // The same version cannot be validated twice at once. + var lowerId = id.ToLowerInvariant(); + if (await _context.PackageValidations.AnyAsync( + v => v.PackageId.ToLower() == lowerId + && v.PackageVersion == version + && v.State == PackageValidationState.Pending, + cancellationToken)) + { + return PackageIndexingResult.PackageAlreadyExists; + } + + var submissionId = Guid.NewGuid().ToString("D"); + + package.Position = 0; + await _storage.PutAsync(StagedPath(submissionId), package, "application/octet-stream", cancellationToken); + + var now = _time.UtcNow; + var steps = _validators.Select(v => v.Name).Append(PackageValidation.IndexType); + foreach (var step in steps) + { + _context.PackageValidations.Add(new PackageValidation + { + SubmissionId = submissionId, + PackageId = id, + PackageVersion = version, + Type = step, + State = PackageValidationState.Pending, + Created = now, + }); + } + + await _context.SaveChangesAsync(cancellationToken); + await _queue.EnqueueAsync(submissionId, cancellationToken); + + _logger.LogInformation( + "Queued package {PackageId} {PackageVersion} for validation as {SubmissionId}", + id, + version, + submissionId); + + return PackageIndexingResult.Accepted; + } + } +} diff --git a/src/BaGet.Validation/ValidationQueue.cs b/src/BaGet.Validation/ValidationQueue.cs new file mode 100644 index 000000000..ed2e3a583 --- /dev/null +++ b/src/BaGet.Validation/ValidationQueue.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; + +namespace BaGet.Validation +{ + /// + /// Hands submissions to the validation worker. The submissions themselves are in the + /// database, so a queue only has to say which to run next; the default one is in + /// memory, and on startup the worker re-queues whatever is still pending. + /// + public interface IValidationQueue + { + ValueTask EnqueueAsync(string submissionId, CancellationToken cancellationToken); + + IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken); + } + + public class InMemoryValidationQueue : IValidationQueue + { + private readonly Channel _channel = Channel.CreateUnbounded( + new UnboundedChannelOptions { SingleReader = true }); + + public ValueTask EnqueueAsync(string submissionId, CancellationToken cancellationToken) + => _channel.Writer.WriteAsync(submissionId, cancellationToken); + + public IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken) + => _channel.Reader.ReadAllAsync(cancellationToken); + } +} diff --git a/src/BaGet.Validation/ValidationServiceCollectionExtensions.cs b/src/BaGet.Validation/ValidationServiceCollectionExtensions.cs new file mode 100644 index 000000000..87a8f22db --- /dev/null +++ b/src/BaGet.Validation/ValidationServiceCollectionExtensions.cs @@ -0,0 +1,30 @@ +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace BaGet.Validation +{ + public static class ValidationServiceCollectionExtensions + { + /// + /// Always registered; whether a push is validated is read from "Validation:Enabled" + /// on every push, so with it off the only difference is an idle worker. + /// + public static IServiceCollection AddBaGetValidation(this IServiceCollection services) + { + services.Replace(ServiceDescriptor.Transient()); + + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); + + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); + + services.AddHostedService(); + + return services; + } + } +} diff --git a/src/BaGet.Validation/ValidationWorker.cs b/src/BaGet.Validation/ValidationWorker.cs new file mode 100644 index 000000000..21b7f4e02 --- /dev/null +++ b/src/BaGet.Validation/ValidationWorker.cs @@ -0,0 +1,78 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace BaGet.Validation +{ + /// + /// Runs queued submissions one at a time. On startup it re-queues every submission still + /// pending, so a restart delays validation but loses nothing. + /// + public class ValidationWorker : BackgroundService + { + private readonly IServiceScopeFactory _scopes; + private readonly IValidationQueue _queue; + private readonly ILogger _logger; + + public ValidationWorker(IServiceScopeFactory scopes, IValidationQueue queue, ILogger logger) + { + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + // Yield so that host startup does not wait on the database. + await Task.Yield(); + + await RequeuePendingAsync(stoppingToken); + + await foreach (var submissionId in _queue.DequeueAllAsync(stoppingToken)) + { + try + { + using var scope = _scopes.CreateScope(); + var runner = scope.ServiceProvider.GetRequiredService(); + + await runner.RunAsync(submissionId, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception e) + { + // Left pending, so the next start retries it. + _logger.LogError(e, "Validation of submission {SubmissionId} failed", submissionId); + } + } + } + + private async Task RequeuePendingAsync(CancellationToken cancellationToken) + { + try + { + using var scope = _scopes.CreateScope(); + if (!scope.ServiceProvider.GetRequiredService>().Value.Enabled) return; + if (scope.ServiceProvider.GetRequiredService() is NullContext) return; + + var runner = scope.ServiceProvider.GetRequiredService(); + foreach (var submissionId in await runner.GetPendingSubmissionIdsAsync(cancellationToken)) + { + await _queue.EnqueueAsync(submissionId, cancellationToken); + } + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + // The database may not be migrated yet on a first start. + _logger.LogWarning(e, "Could not re-queue pending validations"); + } + } + } +} diff --git a/src/BaGet.Validation/Validators.cs b/src/BaGet.Validation/Validators.cs new file mode 100644 index 000000000..b91e99ecc --- /dev/null +++ b/src/BaGet.Validation/Validators.cs @@ -0,0 +1,96 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.Extensions.Options; +using NuGet.Common; +using NuGet.Packaging.Signing; + +namespace BaGet.Validation +{ + /// + /// Every entry's path must be safe to extract: none may escape the package's folder. + /// + public class PackageEntriesValidator : IPackageValidator + { + public string Name => "PackageEntries"; + + public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + { + try + { + await context.Reader.ValidatePackageEntriesAsync(cancellationToken); + + return PackageValidatorResult.Valid; + } + catch (NuGet.Packaging.Core.PackagingException e) + { + return PackageValidatorResult.Invalid(e.Message); + } + } + } + + /// + /// A signed package must have an intact, valid signature; an unsigned one is rejected + /// only when is set. Whether the + /// signing certificate is trusted is not checked: that is the client's policy to apply. + /// + public class PackageSignatureValidator : IPackageValidator + { + private readonly IOptionsSnapshot _options; + + public PackageSignatureValidator(IOptionsSnapshot options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public string Name => "PackageSignature"; + + public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + { + if (!await context.Reader.IsSignedAsync(cancellationToken)) + { + return _options.Value.RequireSignedPackages + ? PackageValidatorResult.Invalid("The package must be signed.") + : PackageValidatorResult.Valid; + } + + var verifier = new PackageSignatureVerifier(new ISignatureVerificationProvider[] + { + new IntegrityVerificationProvider(), + new SignatureTrustAndValidityVerificationProvider(), + }); + + // Untrusted roots are allowed: a private feed's packages are often signed with + // an internal certificate the server's machine does not trust. + var settings = new SignedPackageVerifierSettings( + allowUnsigned: false, + allowIllegal: false, + allowUntrusted: true, + allowIgnoreTimestamp: true, + allowMultipleTimestamps: true, + allowNoTimestamp: true, + allowUnknownRevocation: true, + reportUnknownRevocation: false, + verificationTarget: VerificationTarget.All, + signaturePlacement: SignaturePlacement.Any, + repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.IfExistsAndIsNecessary, + revocationMode: RevocationMode.Offline); + + var result = await verifier.VerifySignaturesAsync(context.Reader, settings, cancellationToken); + if (result.IsValid) + { + return PackageValidatorResult.Valid; + } + + var errors = result.Results + .SelectMany(r => r.GetErrorIssues()) + .Select(i => $"{i.Code}: {i.Message}") + .ToList(); + + return PackageValidatorResult.Invalid( + errors.Count == 0 ? "The package's signature is invalid." : string.Join(" ", errors)); + } + } +} diff --git a/src/BaGet.Web/BaGet.Web.csproj b/src/BaGet.Web/BaGet.Web.csproj index 4f0af778e..0f70dc308 100644 --- a/src/BaGet.Web/BaGet.Web.csproj +++ b/src/BaGet.Web/BaGet.Web.csproj @@ -24,6 +24,7 @@ + diff --git a/src/BaGet.Web/BaGetEndpointBuilder.cs b/src/BaGet.Web/BaGetEndpointBuilder.cs index 7fa1bdea5..31e76d06a 100644 --- a/src/BaGet.Web/BaGetEndpointBuilder.cs +++ b/src/BaGet.Web/BaGetEndpointBuilder.cs @@ -22,6 +22,7 @@ public void MapEndpoints(IEndpointRouteBuilder endpoints) MapPackageMetadataAdminRoutes(endpoints); MapVulnerabilityRoutes(endpoints); MapCatalogRoutes(endpoints); + MapValidationRoutes(endpoints); } /// @@ -49,6 +50,27 @@ public void MapPackageMetadataAdminRoutes(IEndpointRouteBuilder endpoints) constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); } + public void MapValidationRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.RepositorySignaturesRouteName, + pattern: "v3/repository-signatures/index.json", + defaults: new { controller = "RepositorySignatures", action = "Index" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.RepositorySigningCertificateRouteName, + pattern: "v3/repository-signatures/{fingerprint}.crt", + defaults: new { controller = "RepositorySignatures", action = "Certificate" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.ValidationStatusRouteName, + pattern: "v3/package/{id}/{version}/validation", + defaults: new { controller = "ValidationStatus", action = "Get" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + } + public void MapCatalogRoutes(IEndpointRouteBuilder endpoints) { endpoints.MapControllerRoute( diff --git a/src/BaGet.Web/BaGetUrlGenerator.cs b/src/BaGet.Web/BaGetUrlGenerator.cs index 11c9c4cfa..58c030fc8 100644 --- a/src/BaGet.Web/BaGetUrlGenerator.cs +++ b/src/BaGet.Web/BaGetUrlGenerator.cs @@ -183,6 +183,16 @@ public string GetCatalogLeafUrl(string commitId) return AbsoluteUrl($"v3/catalog/data/{Uri.EscapeDataString(commitId)}.json"); } + public string GetRepositorySignaturesUrl() + { + return AbsoluteUrl("v3/repository-signatures/index.json"); + } + + public string GetRepositorySigningCertificateUrl(string fingerprint) + { + return AbsoluteUrl($"v3/repository-signatures/{Uri.EscapeDataString(fingerprint)}.crt"); + } + public string GetReportAbuseUriTemplate() { return AbsoluteUrl("packages/{id}/{version}/report-abuse"); diff --git a/src/BaGet.Web/Controllers/PackagePublishController.cs b/src/BaGet.Web/Controllers/PackagePublishController.cs index 8efb687db..a95aaefa0 100644 --- a/src/BaGet.Web/Controllers/PackagePublishController.cs +++ b/src/BaGet.Web/Controllers/PackagePublishController.cs @@ -13,7 +13,7 @@ public class PackagePublishController : Controller { private readonly IAuthenticationService _authentication; private readonly IPackageAuthorizationService _authorization; - private readonly IPackageIndexingService _indexer; + private readonly IPackageSubmissionService _submissions; private readonly IPackageDatabase _packages; private readonly IPackageDeletionService _deleteService; private readonly IOptionsSnapshot _options; @@ -22,7 +22,7 @@ public class PackagePublishController : Controller public PackagePublishController( IAuthenticationService authentication, - IPackageIndexingService indexer, + IPackageSubmissionService submissions, IPackageDatabase packages, IPackageDeletionService deletionService, IOptionsSnapshot options, @@ -33,7 +33,7 @@ public PackagePublishController( _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); - _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _submissions = submissions ?? throw new ArgumentNullException(nameof(submissions)); _packages = packages ?? throw new ArgumentNullException(nameof(packages)); _deleteService = deletionService ?? throw new ArgumentNullException(nameof(deletionService)); _options = options ?? throw new ArgumentNullException(nameof(options)); @@ -72,8 +72,11 @@ public async Task Upload(CancellationToken cancellationToken) return; } - var result = await _indexer.IndexAsync(uploadStream, cancellationToken); - if (result == PackageIndexingResult.Success) + var result = await _submissions.SubmitAsync(uploadStream, cancellationToken); + + // An accepted package claims its ID now, as it would on nuget.org: it is + // the pusher's even while it is validated. + if (result == PackageIndexingResult.Success || result == PackageIndexingResult.Accepted) { await _authorization.OnPushedAsync(principal, packageId, cancellationToken); } @@ -91,6 +94,10 @@ public async Task Upload(CancellationToken cancellationToken) case PackageIndexingResult.Success: HttpContext.Response.StatusCode = 201; break; + + case PackageIndexingResult.Accepted: + HttpContext.Response.StatusCode = 202; + break; } } } diff --git a/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs b/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs index 5eb1a65a8..9a8a90d34 100644 --- a/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs +++ b/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs @@ -2,6 +2,7 @@ using System.Text.Json.Serialization; using BaGet.Catalog; using BaGet.Core; +using BaGet.Validation; using BaGet.Web; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; @@ -35,6 +36,7 @@ public static IServiceCollection AddBaGetWebApplication( services.AddBaGetApplication(configureAction); services.AddBaGetCatalog(); + services.AddBaGetValidation(); return services; } diff --git a/src/BaGet.Web/Routes.cs b/src/BaGet.Web/Routes.cs index 469578ad5..5742fac6a 100644 --- a/src/BaGet.Web/Routes.cs +++ b/src/BaGet.Web/Routes.cs @@ -35,5 +35,8 @@ public class Routes public const string CatalogIndexRouteName = "catalog-index"; public const string CatalogPageRouteName = "catalog-page"; public const string CatalogLeafRouteName = "catalog-leaf"; + public const string RepositorySignaturesRouteName = "repository-signatures"; + public const string RepositorySigningCertificateRouteName = "repository-signing-certificate"; + public const string ValidationStatusRouteName = "validation-status"; } } diff --git a/tests/BaGet.Tests/Support/BaGetApplication.cs b/tests/BaGet.Tests/Support/BaGetApplication.cs index 6038b08f1..b11d512e1 100644 --- a/tests/BaGet.Tests/Support/BaGetApplication.cs +++ b/tests/BaGet.Tests/Support/BaGetApplication.cs @@ -23,12 +23,15 @@ public class BaGetApplication : WebApplicationFactory private readonly ITestOutputHelper _output; private readonly HttpClient _upstreamClient; private readonly Dictionary _configOverrides; + private readonly Action _configureServices; public BaGetApplication( ITestOutputHelper output, HttpClient upstreamClient = null, - Dictionary configOverrides = null) + Dictionary configOverrides = null, + Action configureServices = null) { + _configureServices = configureServices; _output = output ?? throw new ArgumentNullException(nameof(output)); _upstreamClient = upstreamClient; _configOverrides = configOverrides; @@ -92,6 +95,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) .Returns(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)); services.AddSingleton(time.Object); + _configureServices?.Invoke(services); if (_upstreamClient != null) { services.AddSingleton(_upstreamClient); diff --git a/tests/BaGet.Tests/ValidationIntegrationTests.cs b/tests/BaGet.Tests/ValidationIntegrationTests.cs new file mode 100644 index 000000000..ff1ddbd49 --- /dev/null +++ b/tests/BaGet.Tests/ValidationIntegrationTests.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Validation; +using Microsoft.Extensions.DependencyInjection; +using NuGet.Packaging; +using NuGet.Packaging.Signing; +using Xunit; +using Xunit.Abstractions; + +namespace BaGet.Tests +{ + /// + /// With validation on, a push is accepted, staged and validated, and the package only + /// appears once every validator passes. + /// + public class ValidationIntegrationTests : IDisposable + { + private readonly ITestOutputHelper _output; + private readonly List _disposables = new List(); + + public ValidationIntegrationTests(ITestOutputHelper output) + { + _output = output; + } + + [Fact] + public async Task APackageBeingValidatedIsNotServed() + { + var gate = new GateValidator(); + var client = CreateClient(configureServices: s => s.AddSingleton(gate)); + + Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Gated.Package", "1.0.0")); + await gate.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + + Assert.Equal("Validating", await StatusAsync(client, "Gated.Package", "1.0.0")); + await AssertNotServedAsync(client, "Gated.Package", "1.0.0"); + + gate.Release.SetResult(true); + + Assert.Equal("Available", await WaitForResultAsync(client, "Gated.Package", "1.0.0")); + using var download = await client.GetAsync("v3/package/gated.package/1.0.0/gated.package.1.0.0.nupkg"); + Assert.Equal(HttpStatusCode.OK, download.StatusCode); + } + + [Fact] + public async Task AFailedPackageIsQuarantinedAndNeverServed() + { + var client = CreateClient(configureServices: s => s.AddSingleton(new RejectingValidator())); + + Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Rejected.Package", "1.0.0")); + + Assert.Equal("Quarantined", await WaitForResultAsync(client, "Rejected.Package", "1.0.0")); + await AssertNotServedAsync(client, "Rejected.Package", "1.0.0"); + + using var status = JsonDocument.Parse(await client.GetStringAsync("v3/package/Rejected.Package/1.0.0/validation")); + var rejection = status.RootElement.GetProperty("steps").EnumerateArray() + .Single(s => s.GetProperty("type").GetString() == "Rejecting"); + Assert.Equal("Failed", rejection.GetProperty("state").GetString()); + Assert.Equal("Rejected by the test.", rejection.GetProperty("message").GetString()); + } + + [Fact] + public async Task AnUnsignedPackageIsQuarantinedWhenSignaturesAreRequired() + { + var client = CreateClient(new Dictionary { { "Validation:RequireSignedPackages", "true" } }); + + await PushAsync(client, "Unsigned.Package", "1.0.0"); + + Assert.Equal("Quarantined", await WaitForResultAsync(client, "Unsigned.Package", "1.0.0")); + } + + [Fact] + public async Task TheSameVersionCannotBeValidatedTwiceAtOnce() + { + var gate = new GateValidator(); + var client = CreateClient(configureServices: s => s.AddSingleton(gate)); + + Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Twice.Package", "1.0.0")); + Assert.Equal(HttpStatusCode.Conflict, await PushAsync(client, "Twice.Package", "1.0.0")); + + gate.Release.SetResult(true); + Assert.Equal("Available", await WaitForResultAsync(client, "Twice.Package", "1.0.0")); + } + + [Fact] + public async Task AValidatedPackageIsRepositorySigned() + { + var (path, fingerprint) = CreateSigningCertificate(); + var client = CreateClient(new Dictionary + { + { "Validation:RepositorySigningCertificatePath", path }, + { "Validation:RepositorySigningCertificatePassword", "test" }, + { "Validation:RepositorySigningServiceIndexUrl", "https://localhost/v3/index.json" }, + }); + + await PushAsync(client, "Signed.Package", "1.0.0"); + Assert.Equal("Available", await WaitForResultAsync(client, "Signed.Package", "1.0.0")); + + using var download = await client.GetAsync("v3/package/signed.package/1.0.0/signed.package.1.0.0.nupkg"); + using var package = new MemoryStream(await download.Content.ReadAsByteArrayAsync()); + using var reader = new PackageArchiveReader(package); + + Assert.True(await reader.IsSignedAsync(CancellationToken.None)); + var signature = await reader.GetPrimarySignatureAsync(CancellationToken.None); + Assert.Equal(SignatureType.Repository, signature.Type); + + // The resource lists the certificate that signed it, and serves it. + using var resource = JsonDocument.Parse(await client.GetStringAsync("v3/repository-signatures/index.json")); + var certificate = resource.RootElement.GetProperty("signingCertificates")[0]; + Assert.Equal(fingerprint, certificate.GetProperty("fingerprints").GetProperty("2.16.840.1.101.3.4.2.1").GetString()); + Assert.False(resource.RootElement.GetProperty("allRepositorySigned").GetBoolean()); + + using var crt = await client.GetAsync(certificate.GetProperty("contentUrl").GetString()); + Assert.Equal(HttpStatusCode.OK, crt.StatusCode); + + var index = await client.GetStringAsync("v3/index.json"); + Assert.Contains("RepositorySignatures/5.0.0", index); + } + + [Fact] + public async Task ASignedPackagePassesWhenSignaturesAreRequired() + { + // Sign a package on one server, then push the signed copy to another that + // requires signatures: its signature must verify, untrusted root and all. + var (path, _) = CreateSigningCertificate(); + var signer = CreateClient(new Dictionary + { + { "Validation:RepositorySigningCertificatePath", path }, + { "Validation:RepositorySigningCertificatePassword", "test" }, + { "Validation:RepositorySigningServiceIndexUrl", "https://localhost/v3/index.json" }, + }); + await PushAsync(signer, "Resigned.Package", "1.0.0"); + Assert.Equal("Available", await WaitForResultAsync(signer, "Resigned.Package", "1.0.0")); + var signed = await signer.GetByteArrayAsync("v3/package/resigned.package/1.0.0/resigned.package.1.0.0.nupkg"); + + var strict = CreateClient(new Dictionary { { "Validation:RequireSignedPackages", "true" } }); + using (var package = new MemoryStream(signed)) + using (var request = TestPackages.PushRequest(package, apiKey: null)) + using (var response = await strict.SendAsync(request)) + { + Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); + } + + Assert.Equal("Available", await WaitForResultAsync(strict, "Resigned.Package", "1.0.0")); + } + + [Fact] + public async Task SigningWithAnInsecureSourceUrlQuarantinesWithAReason() + { + var (path, _) = CreateSigningCertificate(); + var client = CreateClient(new Dictionary + { + { "Validation:RepositorySigningCertificatePath", path }, + { "Validation:RepositorySigningCertificatePassword", "test" }, + { "Validation:RepositorySigningServiceIndexUrl", "http://localhost/v3/index.json" }, + }); + + await PushAsync(client, "Insecure.Package", "1.0.0"); + + Assert.Equal("Quarantined", await WaitForResultAsync(client, "Insecure.Package", "1.0.0")); + using var status = JsonDocument.Parse(await client.GetStringAsync("v3/package/Insecure.Package/1.0.0/validation")); + var index = status.RootElement.GetProperty("steps").EnumerateArray().Single(s => s.GetProperty("type").GetString() == "Index"); + Assert.Contains("https", index.GetProperty("message").GetString()); + } + + [Fact] + public async Task WithoutASigningCertificateTheResourceIsAbsent() + { + var client = CreateClient(); + + Assert.DoesNotContain("RepositorySignatures", await client.GetStringAsync("v3/index.json")); + using var response = await client.GetAsync("v3/repository-signatures/index.json"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + private HttpClient CreateClient( + Dictionary config = null, + Action configureServices = null) + { + var settings = new Dictionary { { "Validation:Enabled", "true" } }; + foreach (var pair in config ?? new Dictionary()) + { + settings[pair.Key] = pair.Value; + } + + var app = new BaGetApplication(_output, configOverrides: settings, configureServices: configureServices); + var client = app.CreateClient(); + _disposables.Add(client); + _disposables.Add(app); + + return client; + } + + private static async Task PushAsync(HttpClient client, string id, string version) + { + using var package = TestPackages.Build(id, version); + using var request = TestPackages.PushRequest(package, apiKey: null); + using var response = await client.SendAsync(request); + + return response.StatusCode; + } + + private static async Task StatusAsync(HttpClient client, string id, string version) + { + using var status = JsonDocument.Parse(await client.GetStringAsync($"v3/package/{id}/{version}/validation")); + + return status.RootElement.GetProperty("status").GetString(); + } + + private static async Task WaitForResultAsync(HttpClient client, string id, string version) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (true) + { + var status = await StatusAsync(client, id, version); + if (status != "Validating" || DateTime.UtcNow > deadline) return status; + + await Task.Delay(50); + } + } + + private static async Task AssertNotServedAsync(HttpClient client, string id, string version) + { + var lower = id.ToLowerInvariant(); + + using var download = await client.GetAsync($"v3/package/{lower}/{version}/{lower}.{version}.nupkg"); + Assert.Equal(HttpStatusCode.NotFound, download.StatusCode); + + using var registration = await client.GetAsync($"v3/registration/{lower}/index.json"); + Assert.Equal(HttpStatusCode.NotFound, registration.StatusCode); + } + + /// + /// A self-signed code signing certificate, as a PFX file, and its SHA-256 fingerprint. + /// + private (string Path, string Fingerprint) CreateSigningCertificate() + { + using var rsa = RSA.Create(2048); + var request = new CertificateRequest("CN=BaGet Test Repository", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( + new OidCollection { new Oid("1.3.6.1.5.5.7.3.3") }, // Code signing. + false)); + + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); + + var path = Path.Combine(Path.GetTempPath(), "BaGetTests", Guid.NewGuid().ToString("N") + ".pfx"); + Directory.CreateDirectory(Path.GetDirectoryName(path)); + File.WriteAllBytes(path, certificate.Export(X509ContentType.Pfx, "test")); + + return (path, RepositorySignaturesController.Fingerprint(certificate.RawData)); + } + + public void Dispose() + { + foreach (var disposable in Enumerable.Reverse(_disposables)) + { + disposable.Dispose(); + } + } + + private class GateValidator : IPackageValidator + { + public TaskCompletionSource Entered { get; } = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + public string Name => "Gate"; + + public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + { + Entered.TrySetResult(true); + await Release.Task.WaitAsync(TimeSpan.FromSeconds(30), cancellationToken); + + return PackageValidatorResult.Valid; + } + } + + private class RejectingValidator : IPackageValidator + { + public string Name => "Rejecting"; + + public Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + => Task.FromResult(PackageValidatorResult.Invalid("Rejected by the test.")); + } + } +} From 5df9f707a6bc6a59b5028a8744fb30fdf88b4013 Mon Sep 17 00:00:00 2001 From: pieroviano Date: Sat, 17 Oct 2026 05:06:39 +0300 Subject: [PATCH 048/498] Phase 9: statistics, abuse reports and owner pages Statistics page (/stats) from the per-version download counts. The report abuse page now records reports in a new AbuseReports table (additive migrations for all four providers). With accounts on: public profiles for users and organizations, a manage page per package ID for its owners (owners, unlist/relist, deprecation, open abuse reports), and an organizations page. Changes made there reach the catalog like any other. --- src/BaGet.Core/Entities/AbstractContext.cs | 17 + src/BaGet.Core/Entities/AbuseReport.cs | 41 + src/BaGet.Core/Entities/IContext.cs | 2 + src/BaGet.Core/Entities/NullContext.cs | 2 + src/BaGet.Core/Entities/PackageDeprecation.cs | 10 +- .../DependencyInjectionExtensions.cs | 1 + .../Statistics/StatisticsService.cs | 98 ++ ...20261017020123_AddAbuseReports.Designer.cs | 890 +++++++++++++++++ .../20261017020123_AddAbuseReports.cs | 53 ++ .../Migrations/MySqlContextModelSnapshot.cs | 45 + ...20261017020119_AddAbuseReports.Designer.cs | 891 +++++++++++++++++ .../20261017020119_AddAbuseReports.cs | 47 + .../PostgreSqlContextModelSnapshot.cs | 45 + ...20261017020116_AddAbuseReports.Designer.cs | 893 ++++++++++++++++++ .../20261017020116_AddAbuseReports.cs | 46 + .../SqlServerContextModelSnapshot.cs | 45 + ...20261017020112_AddAbuseReports.Designer.cs | 855 +++++++++++++++++ .../20261017020112_AddAbuseReports.cs | 46 + .../Migrations/SqliteContextModelSnapshot.cs | 43 + .../Pages/Account/Organizations.cshtml | 56 ++ .../Pages/Account/Organizations.cshtml.cs | 115 +++ .../Pages/Account/Profile.cshtml | 2 + .../Pages/Account/Profile.cshtml.cs | 14 + .../Pages/Profiles/Profile.cshtml | 47 + .../Pages/Profiles/Profile.cshtml.cs | 86 ++ .../PackageMetadataAdminController.cs | 10 +- src/BaGet.Web/Pages/Package.cshtml | 18 + src/BaGet.Web/Pages/ReportAbuse.cshtml | 50 +- src/BaGet.Web/Pages/ReportAbuse.cshtml.cs | 95 ++ src/BaGet.Web/Pages/Shared/_Layout.cshtml | 1 + src/BaGet.Web/Pages/Statistics.cshtml | 57 ++ src/BaGet.Web/Pages/Statistics.cshtml.cs | 28 + tests/BaGet.Tests/Support/Browser.cs | 62 ++ tests/BaGet.Tests/WebUiIntegrationTests.cs | 288 ++++++ 34 files changed, 4981 insertions(+), 18 deletions(-) create mode 100644 src/BaGet.Core/Entities/AbuseReport.cs create mode 100644 src/BaGet.Core/Statistics/StatisticsService.cs create mode 100644 src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.Designer.cs create mode 100644 src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.cs create mode 100644 src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.Designer.cs create mode 100644 src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.cs create mode 100644 src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.Designer.cs create mode 100644 src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.cs create mode 100644 src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.Designer.cs create mode 100644 src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.cs create mode 100644 src/BaGet.Identity/Pages/Account/Organizations.cshtml create mode 100644 src/BaGet.Identity/Pages/Account/Organizations.cshtml.cs create mode 100644 src/BaGet.Identity/Pages/Account/Profile.cshtml create mode 100644 src/BaGet.Identity/Pages/Account/Profile.cshtml.cs create mode 100644 src/BaGet.Identity/Pages/Profiles/Profile.cshtml create mode 100644 src/BaGet.Identity/Pages/Profiles/Profile.cshtml.cs create mode 100644 src/BaGet.Web/Pages/ReportAbuse.cshtml.cs create mode 100644 src/BaGet.Web/Pages/Statistics.cshtml create mode 100644 src/BaGet.Web/Pages/Statistics.cshtml.cs create mode 100644 tests/BaGet.Tests/Support/Browser.cs create mode 100644 tests/BaGet.Tests/WebUiIntegrationTests.cs diff --git a/src/BaGet.Core/Entities/AbstractContext.cs b/src/BaGet.Core/Entities/AbstractContext.cs index 9432aa0a7..b4804d4f0 100644 --- a/src/BaGet.Core/Entities/AbstractContext.cs +++ b/src/BaGet.Core/Entities/AbstractContext.cs @@ -36,6 +36,9 @@ public abstract class AbstractContext : IdentityDbContext, public const int MaxValidationTypeLength = 64; + public const int MaxAbuseReasonLength = 128; + public const int MaxEmailLength = 256; + public AbstractContext(DbContextOptions options) : base(options) { } @@ -52,6 +55,7 @@ public AbstractContext(DbContextOptions options) public DbSet PackageOwners { get; set; } public DbSet ApiKeys { get; set; } public DbSet PackageValidations { get; set; } + public DbSet AbuseReports { get; set; } public Task SaveChangesAsync() => SaveChangesAsync(default); @@ -78,6 +82,7 @@ protected override void OnModelCreating(ModelBuilder builder) builder.Entity(BuildPackageOwnerEntity); builder.Entity(BuildApiKeyEntity); builder.Entity(BuildPackageValidationEntity); + builder.Entity(BuildAbuseReportEntity); } private void BuildPackageEntity(EntityTypeBuilder package) @@ -280,6 +285,18 @@ private void BuildPackageValidationEntity(EntityTypeBuilder v .IsRequired(false); } + private void BuildAbuseReportEntity(EntityTypeBuilder report) + { + report.HasKey(r => r.Key); + report.HasIndex(r => r.PackageId); + + report.Property(r => r.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + report.Property(r => r.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + report.Property(r => r.Reason).HasMaxLength(MaxAbuseReasonLength).IsRequired(); + report.Property(r => r.Details).HasMaxLength(DefaultMaxStringLength).IsRequired(); + report.Property(r => r.ReporterEmail).HasMaxLength(MaxEmailLength); + } + private void BuildPackageDependencyEntity(EntityTypeBuilder dependency) { dependency.HasKey(d => d.Key); diff --git a/src/BaGet.Core/Entities/AbuseReport.cs b/src/BaGet.Core/Entities/AbuseReport.cs new file mode 100644 index 000000000..19f6363f8 --- /dev/null +++ b/src/BaGet.Core/Entities/AbuseReport.cs @@ -0,0 +1,41 @@ +using System; + +namespace BaGet.Core +{ + /// + /// A report that a package version is abusive, for its owners and the server's + /// administrator to act on. + /// + public class AbuseReport + { + /// + /// The reasons a report may give, as nuget.org offers them. + /// + public static readonly string[] Reasons = + { + "Contains malicious code", + "Violates a license or copyright", + "Contains private or confidential data", + "Other", + }; + + public int Key { get; set; } + + public string PackageId { get; set; } + + public string PackageVersion { get; set; } + + public string Reason { get; set; } + + public string Details { get; set; } + + /// + /// Where to reply, if the reporter gave an address. + /// + public string ReporterEmail { get; set; } + + public DateTime Created { get; set; } + + public DateTime? Resolved { get; set; } + } +} diff --git a/src/BaGet.Core/Entities/IContext.cs b/src/BaGet.Core/Entities/IContext.cs index 29528f0fc..b60c496b0 100644 --- a/src/BaGet.Core/Entities/IContext.cs +++ b/src/BaGet.Core/Entities/IContext.cs @@ -40,6 +40,8 @@ public interface IContext DbSet PackageValidations { get; set; } + DbSet AbuseReports { get; set; } + /// /// Identity's users. Declared here so that account services can query them through /// the same context as everything else. diff --git a/src/BaGet.Core/Entities/NullContext.cs b/src/BaGet.Core/Entities/NullContext.cs index 2f8451bef..af364593c 100644 --- a/src/BaGet.Core/Entities/NullContext.cs +++ b/src/BaGet.Core/Entities/NullContext.cs @@ -30,6 +30,8 @@ public class NullContext : IContext public DbSet PackageValidations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet AbuseReports { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet Users { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public bool SupportsLimitInSubqueries => throw new NotImplementedException(); diff --git a/src/BaGet.Core/Entities/PackageDeprecation.cs b/src/BaGet.Core/Entities/PackageDeprecation.cs index 5167d8d65..1c8008ce9 100644 --- a/src/BaGet.Core/Entities/PackageDeprecation.cs +++ b/src/BaGet.Core/Entities/PackageDeprecation.cs @@ -1,4 +1,6 @@ -namespace BaGet.Core +using System.Collections.Generic; + +namespace BaGet.Core { /// /// A package version marked as deprecated. @@ -6,6 +8,12 @@ /// public class PackageDeprecation { + /// + /// The deprecation reasons the protocol defines. + /// See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation + /// + public static readonly IReadOnlyList KnownReasons = new[] { "Legacy", "CriticalBugs", "Other" }; + public int Key { get; set; } /// diff --git a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs index 09c45e12c..1a941dabd 100644 --- a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs +++ b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs @@ -89,6 +89,7 @@ private static void AddBaGetServices(this IServiceCollection services) services.TryAddSingleton(NuGetClientFactoryFactory); services.TryAddScoped(); + services.TryAddScoped(); services.TryAddTransient(); services.TryAddTransient(); diff --git a/src/BaGet.Core/Statistics/StatisticsService.cs b/src/BaGet.Core/Statistics/StatisticsService.cs new file mode 100644 index 000000000..59117d8a8 --- /dev/null +++ b/src/BaGet.Core/Statistics/StatisticsService.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace BaGet.Core +{ + public class FeedStatistics + { + public int PackageIds { get; set; } + + public int PackageVersions { get; set; } + + public long Downloads { get; set; } + + /// + /// The most downloaded package IDs, all versions together. + /// + public IReadOnlyList TopPackages { get; set; } + + /// + /// The most recently published versions. + /// + public IReadOnlyList RecentVersions { get; set; } + } + + public class PackageDownloads + { + public string Id { get; set; } + + /// + /// Null when the downloads are a whole package ID's. + /// + public string Version { get; set; } + + public long Downloads { get; set; } + + public DateTime? Published { get; set; } + } + + /// + /// Feed-wide download statistics, from the per-version counts the database keeps. + /// There is no per-day history: a count only ever goes up. + /// + public class StatisticsService + { + private const int ListSize = 10; + + private readonly IContext _context; + + public StatisticsService(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// + /// False when the database cannot be queried for aggregates, such as Azure Table storage. + /// + public bool IsSupported => !(_context is NullContext); + + public async Task GetAsync(CancellationToken cancellationToken) + { + var listed = _context.Packages.AsNoTracking().Where(p => p.Listed); + + var top = await listed + .GroupBy(p => p.Id) + .Select(g => new PackageDownloads { Id = g.Key, Downloads = g.Sum(p => p.Downloads) }) + .OrderByDescending(p => p.Downloads) + .ThenBy(p => p.Id) + .Take(ListSize) + .ToListAsync(cancellationToken); + + var recent = await listed + .OrderByDescending(p => p.Published) + .ThenByDescending(p => p.Key) + .Take(ListSize) + .Select(p => new PackageDownloads + { + Id = p.Id, + Version = p.OriginalVersionString ?? p.NormalizedVersionString, + Downloads = p.Downloads, + Published = p.Published, + }) + .ToListAsync(cancellationToken); + + return new FeedStatistics + { + PackageIds = await listed.Select(p => p.Id).Distinct().CountAsync(cancellationToken), + PackageVersions = await listed.CountAsync(cancellationToken), + Downloads = await listed.SumAsync(p => p.Downloads, cancellationToken), + TopPackages = top, + RecentVersions = recent, + }; + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.Designer.cs b/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.Designer.cs new file mode 100644 index 000000000..1f3f9c23b --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.Designer.cs @@ -0,0 +1,890 @@ +// +using System; +using BaGet.Database.MySql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + [DbContext(typeof(MySqlContext))] + [Migration("20261017020123_AddAbuseReports")] + partial class AddAbuseReports + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime(6)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("tinyint(1)"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("varchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("tinyint(1)"); + + b.Property("HasReadme") + .HasColumnType("tinyint(1)"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("tinyint(1)"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Listed") + .HasColumnType("tinyint(1)"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("varchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("varchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Published") + .HasColumnType("datetime(6)"); + + b.Property("ReleaseNotes") + .HasColumnType("longtext") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("tinyint(1)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("timestamp(6)"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("longtext"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("tinyint(1)"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("varchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime(6)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("varchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.cs b/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.cs new file mode 100644 index 000000000..25c5423b3 --- /dev/null +++ b/src/BaGet.Database.MySql/Migrations/20261017020123_AddAbuseReports.cs @@ -0,0 +1,53 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.MySql.Migrations +{ + /// + public partial class AddAbuseReports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AbuseReports", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + PackageId = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + PackageVersion = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Reason = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Details = table.Column(type: "varchar(4000)", maxLength: 4000, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + ReporterEmail = table.Column(type: "varchar(256)", maxLength: 256, nullable: true) + .Annotation("MySql:CharSet", "utf8mb4"), + Created = table.Column(type: "datetime(6)", nullable: false), + Resolved = table.Column(type: "datetime(6)", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AbuseReports", x => x.Key); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AbuseReports"); + } + } +} diff --git a/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs b/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs index 6335d7126..a524f9398 100644 --- a/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs +++ b/src/BaGet.Database.MySql/Migrations/MySqlContextModelSnapshot.cs @@ -22,6 +22,51 @@ protected override void BuildModel(ModelBuilder modelBuilder) MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("varchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Resolved") + .HasColumnType("datetime(6)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + modelBuilder.Entity("BaGet.Core.ApiKey", b => { b.Property("Key") diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.Designer.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.Designer.cs new file mode 100644 index 000000000..2416bcc28 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.Designer.cs @@ -0,0 +1,891 @@ +// +using System; +using BaGet.Database.PostgreSql; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlContext))] + [Migration("20261017020119_AddAbuseReports")] + partial class AddAbuseReports + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("OrganizationKey") + .HasColumnType("integer"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("character varying(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("boolean"); + + b.Property("HasReadme") + .HasColumnType("boolean"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("IsPrerelease") + .HasColumnType("boolean"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Listed") + .HasColumnType("boolean"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("character varying(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("citext") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Published") + .HasColumnType("timestamp with time zone"); + + b.Property("ReleaseNotes") + .HasColumnType("text") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("boolean"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("bytea"); + + b.Property("SemVerLevel") + .HasColumnType("integer"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("boolean"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("timestamp with time zone"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("character varying(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.Property("Severity") + .HasColumnType("integer"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("citext"); + + b.Property("PackageKey") + .HasColumnType("integer"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.cs b/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.cs new file mode 100644 index 000000000..82aa26416 --- /dev/null +++ b/src/BaGet.Database.PostgreSql/Migrations/20261017020119_AddAbuseReports.cs @@ -0,0 +1,47 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace BaGet.Database.PostgreSql.Migrations +{ + /// + public partial class AddAbuseReports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AbuseReports", + columns: table => new + { + Key = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + PackageId = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Reason = table.Column(type: "character varying(128)", maxLength: 128, nullable: false), + Details = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: false), + ReporterEmail = table.Column(type: "character varying(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "timestamp with time zone", nullable: false), + Resolved = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AbuseReports", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AbuseReports"); + } + } +} diff --git a/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs b/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs index 967881e4e..e71954c39 100644 --- a/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs +++ b/src/BaGet.Database.PostgreSql/Migrations/PostgreSqlContextModelSnapshot.cs @@ -23,6 +23,51 @@ protected override void BuildModel(ModelBuilder modelBuilder) NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "citext"); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Resolved") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + modelBuilder.Entity("BaGet.Core.ApiKey", b => { b.Property("Key") diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.Designer.cs b/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.Designer.cs new file mode 100644 index 000000000..1f747cf94 --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.Designer.cs @@ -0,0 +1,893 @@ +// +using System; +using BaGet.Database.SqlServer; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20261017020116_AddAbuseReports")] + partial class AddAbuseReports + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.21") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("CommitTimestamp") + .HasColumnType("datetime2"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsAdmin") + .HasColumnType("bit"); + + b.Property("OrganizationKey") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Downloads") + .HasColumnType("bigint"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("bit"); + + b.Property("HasReadme") + .HasColumnType("bit"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsPrerelease") + .HasColumnType("bit"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Listed") + .HasColumnType("bit"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("nvarchar(44)"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Published") + .HasColumnType("datetime2"); + + b.Property("ReleaseNotes") + .HasColumnType("nvarchar(max)") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SemVerLevel") + .HasColumnType("int"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique() + .HasFilter("[PackageKey] IS NOT NULL"); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("IsVerified") + .HasColumnType("bit"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Completed") + .HasColumnType("datetime2"); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("State") + .HasColumnType("int"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("nvarchar(36)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PackageKey") + .HasColumnType("int"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.cs b/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.cs new file mode 100644 index 000000000..511caca4d --- /dev/null +++ b/src/BaGet.Database.SqlServer/Migrations/20261017020116_AddAbuseReports.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.SqlServer.Migrations +{ + /// + public partial class AddAbuseReports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AbuseReports", + columns: table => new + { + Key = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PackageId = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + Reason = table.Column(type: "nvarchar(128)", maxLength: 128, nullable: false), + Details = table.Column(type: "nvarchar(4000)", maxLength: 4000, nullable: false), + ReporterEmail = table.Column(type: "nvarchar(256)", maxLength: 256, nullable: true), + Created = table.Column(type: "datetime2", nullable: false), + Resolved = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AbuseReports", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AbuseReports"); + } + } +} diff --git a/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs b/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs index bfd94884b..2d3fed6a0 100644 --- a/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs +++ b/src/BaGet.Database.SqlServer/Migrations/SqlServerContextModelSnapshot.cs @@ -22,6 +22,51 @@ protected override void BuildModel(ModelBuilder modelBuilder) SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Key")); + + b.Property("Created") + .HasColumnType("datetime2"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Resolved") + .HasColumnType("datetime2"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + modelBuilder.Entity("BaGet.Core.ApiKey", b => { b.Property("Key") diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.Designer.cs b/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.Designer.cs new file mode 100644 index 000000000..ed292c480 --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.Designer.cs @@ -0,0 +1,855 @@ +// +using System; +using BaGet.Database.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + [DbContext(typeof(SqliteContext))] + [Migration("20261017020112_AddAbuseReports")] + partial class AddAbuseReports + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + + modelBuilder.Entity("BaGet.Core.ApiKey", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Expires") + .HasColumnType("TEXT"); + + b.Property("HashedKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PackageGlobPattern") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Scopes") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("HashedKey") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("ApiKeys"); + }); + + modelBuilder.Entity("BaGet.Core.BaGetUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.CatalogEntry", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CommitId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("CommitTimestamp") + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("CommitId") + .IsUnique(); + + b.ToTable("CatalogLeafs"); + }); + + modelBuilder.Entity("BaGet.Core.Organization", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Organizations"); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsAdmin") + .HasColumnType("INTEGER"); + + b.Property("OrganizationKey") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(450) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OrganizationKey"); + + b.HasIndex("UserId"); + + b.ToTable("OrganizationMembers"); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Authors") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Downloads") + .HasColumnType("INTEGER"); + + b.Property("HasEmbeddedIcon") + .HasColumnType("INTEGER"); + + b.Property("HasReadme") + .HasColumnType("INTEGER"); + + b.Property("IconUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("IsPrerelease") + .HasColumnType("INTEGER"); + + b.Property("Language") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b.Property("LicenseUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Listed") + .HasColumnType("INTEGER"); + + b.Property("MinClientVersion") + .HasMaxLength(44) + .HasColumnType("TEXT"); + + b.Property("NormalizedVersionString") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT COLLATE NOCASE") + .HasColumnName("Version"); + + b.Property("OriginalVersionString") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnName("OriginalVersion"); + + b.Property("ProjectUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Published") + .HasColumnType("TEXT"); + + b.Property("ReleaseNotes") + .HasColumnType("TEXT") + .HasColumnName("ReleaseNotes"); + + b.Property("RepositoryType") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RepositoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("RequireLicenseAcceptance") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("BLOB"); + + b.Property("SemVerLevel") + .HasColumnType("INTEGER"); + + b.Property("Summary") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Tags") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("Title") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("Id", "NormalizedVersionString") + .IsUnique(); + + b.ToTable("Packages"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Id") + .HasMaxLength(128) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("TargetFramework") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Id"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageDependencies"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AlternatePackageId") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("AlternateVersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Reasons") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey") + .IsUnique(); + + b.ToTable("PackageDeprecations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageOwner", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("IsVerified") + .HasColumnType("INTEGER"); + + b.Property("OwnerName") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("OwnerName"); + + b.HasIndex("PackageId"); + + b.ToTable("PackageOwners"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Name") + .HasMaxLength(512) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Version") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("Name"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageTypes"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Completed") + .HasColumnType("TEXT"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Message") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("SubmissionId") + .IsRequired() + .HasMaxLength(36) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.HasIndex("PackageKey"); + + b.HasIndex("SubmissionId"); + + b.ToTable("PackageValidations"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AdvisoryUrl") + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.Property("Severity") + .HasColumnType("INTEGER"); + + b.Property("VersionRange") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageKey"); + + b.ToTable("PackageVulnerabilities"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Moniker") + .HasMaxLength(256) + .HasColumnType("TEXT COLLATE NOCASE"); + + b.Property("PackageKey") + .HasColumnType("INTEGER"); + + b.HasKey("Key"); + + b.HasIndex("Moniker"); + + b.HasIndex("PackageKey"); + + b.ToTable("TargetFrameworks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasColumnType("TEXT"); + + b.Property("Name") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("BaGet.Core.OrganizationMember", b => + { + b.HasOne("BaGet.Core.Organization", "Organization") + .WithMany() + .HasForeignKey("OrganizationKey"); + + b.Navigation("Organization"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDependency", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Dependencies") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageDeprecation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithOne("Deprecation") + .HasForeignKey("BaGet.Core.PackageDeprecation", "PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageType", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("PackageTypes") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageValidation", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany() + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.PackageVulnerability", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("Vulnerabilities") + .HasForeignKey("PackageKey"); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("BaGet.Core.TargetFramework", b => + { + b.HasOne("BaGet.Core.Package", "Package") + .WithMany("TargetFrameworks") + .HasForeignKey("PackageKey") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Package"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("BaGet.Core.BaGetUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BaGet.Core.Package", b => + { + b.Navigation("Dependencies"); + + b.Navigation("Deprecation"); + + b.Navigation("PackageTypes"); + + b.Navigation("TargetFrameworks"); + + b.Navigation("Vulnerabilities"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.cs b/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.cs new file mode 100644 index 000000000..0f5f7db3a --- /dev/null +++ b/src/BaGet.Database.Sqlite/Migrations/20261017020112_AddAbuseReports.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace BaGet.Database.Sqlite.Migrations +{ + /// + public partial class AddAbuseReports : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AbuseReports", + columns: table => new + { + Key = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + PackageId = table.Column(type: "TEXT", maxLength: 128, nullable: false), + PackageVersion = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Reason = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Details = table.Column(type: "TEXT", maxLength: 4000, nullable: false), + ReporterEmail = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Created = table.Column(type: "TEXT", nullable: false), + Resolved = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AbuseReports", x => x.Key); + }); + + migrationBuilder.CreateIndex( + name: "IX_AbuseReports_PackageId", + table: "AbuseReports", + column: "PackageId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AbuseReports"); + } + } +} diff --git a/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs b/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs index 45ba2aa9c..f92a92a0f 100644 --- a/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs +++ b/src/BaGet.Database.Sqlite/Migrations/SqliteContextModelSnapshot.cs @@ -17,6 +17,49 @@ protected override void BuildModel(ModelBuilder modelBuilder) #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "9.0.21"); + modelBuilder.Entity("BaGet.Core.AbuseReport", b => + { + b.Property("Key") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Created") + .HasColumnType("TEXT"); + + b.Property("Details") + .IsRequired() + .HasMaxLength(4000) + .HasColumnType("TEXT"); + + b.Property("PackageId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("PackageVersion") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ReporterEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Resolved") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.HasIndex("PackageId"); + + b.ToTable("AbuseReports"); + }); + modelBuilder.Entity("BaGet.Core.ApiKey", b => { b.Property("Key") diff --git a/src/BaGet.Identity/Pages/Account/Organizations.cshtml b/src/BaGet.Identity/Pages/Account/Organizations.cshtml new file mode 100644 index 000000000..d7a361c00 --- /dev/null +++ b/src/BaGet.Identity/Pages/Account/Organizations.cshtml @@ -0,0 +1,56 @@ +@page +@model BaGet.Identity.Pages.Account.OrganizationsModel +@{ + ViewData["Title"] = "Organizations"; +} + +
+

Organizations

+ + + @if (Model.Message != null) + { + + } + + @foreach (var organization in Model.Organizations) + { +

@organization.Name

+ + + @foreach (var member in organization.Members) + { + + + + + } + +
@member.UserName@(member.IsAdmin ? " (administrator)" : "") + @if (organization.IsAdmin || member.UserName == User.Identity.Name) + { +
+ + + +
+ } +
+ + @if (organization.IsAdmin) + { +
+ + + + +
+ } + } + +

Create an organization

+
+ + +
+
diff --git a/src/BaGet.Identity/Pages/Account/Organizations.cshtml.cs b/src/BaGet.Identity/Pages/Account/Organizations.cshtml.cs new file mode 100644 index 000000000..24342bedc --- /dev/null +++ b/src/BaGet.Identity/Pages/Account/Organizations.cshtml.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Mvc; + +namespace BaGet.Identity.Pages.Account +{ + /// + /// The signed in user's organizations: create one, and manage the members of those + /// the user administers. + /// + public class OrganizationsModel : AccountPageModel + { + protected override bool RequiresSignIn => true; + + public IReadOnlyList Organizations { get; private set; } = Array.Empty(); + + public string Message { get; private set; } + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + await LoadAsync(cancellationToken); + } + + public async Task OnPostCreateAsync(string name, CancellationToken cancellationToken) + { + var created = await Ownership.CreateOrganizationAsync(name, UserManager.GetUserId(User), cancellationToken); + + return await DoneAsync(created ? $"Created {name}." : "That name is taken.", cancellationToken); + } + + public async Task OnPostAddMemberAsync(string organization, string userName, bool isAdmin, CancellationToken cancellationToken) + { + if (!await Ownership.IsOrganizationAdminAsync(organization, UserManager.GetUserId(User), cancellationToken)) + { + return StatusCode(403); + } + + var user = string.IsNullOrWhiteSpace(userName) ? null : await UserManager.FindByNameAsync(userName.Trim()); + if (user == null) + { + return await DoneAsync("There is no user with that name.", cancellationToken); + } + + var added = await Ownership.AddMemberAsync(organization, user.Id, isAdmin, cancellationToken); + + return await DoneAsync(added ? $"{user.UserName} joined {organization}." : $"{user.UserName} is already a member.", cancellationToken); + } + + public async Task OnPostRemoveMemberAsync(string organization, string userName, CancellationToken cancellationToken) + { + var currentUserId = UserManager.GetUserId(User); + var user = await UserManager.FindByNameAsync(userName ?? string.Empty); + + // An administrator may remove anyone; any member may leave. + if (user == null + || (user.Id != currentUserId && !await Ownership.IsOrganizationAdminAsync(organization, currentUserId, cancellationToken))) + { + return StatusCode(403); + } + + var removed = await Ownership.RemoveMemberAsync(organization, user.Id, cancellationToken); + + return await DoneAsync( + removed ? $"{user.UserName} left {organization}." : "An organization must keep at least one administrator.", + cancellationToken); + } + + private async Task DoneAsync(string message, CancellationToken cancellationToken) + { + Message = message; + await LoadAsync(cancellationToken); + + return Page(); + } + + private async Task LoadAsync(CancellationToken cancellationToken) + { + var userId = UserManager.GetUserId(User); + var views = new List(); + + foreach (var organization in await Ownership.GetOrganizationsAsync(userId, cancellationToken)) + { + var members = await Ownership.GetMembersAsync(organization.Name, cancellationToken); + var names = new List<(string, bool)>(); + foreach (var member in members) + { + var user = await UserManager.FindByIdAsync(member.UserId); + if (user != null) names.Add((user.UserName, member.IsAdmin)); + } + + views.Add(new OrganizationView + { + Name = organization.Name, + IsAdmin = members.Any(m => m.UserId == userId && m.IsAdmin), + Members = names.OrderBy(n => n.Item1, StringComparer.OrdinalIgnoreCase).ToList(), + }); + } + + Organizations = views; + } + + public class OrganizationView + { + public string Name { get; set; } + + public bool IsAdmin { get; set; } + + public IReadOnlyList<(string UserName, bool IsAdmin)> Members { get; set; } + } + } +} diff --git a/src/BaGet.Identity/Pages/Account/Profile.cshtml b/src/BaGet.Identity/Pages/Account/Profile.cshtml new file mode 100644 index 000000000..371abd850 --- /dev/null +++ b/src/BaGet.Identity/Pages/Account/Profile.cshtml @@ -0,0 +1,2 @@ +@page +@model BaGet.Identity.Pages.Account.MyProfileModel diff --git a/src/BaGet.Identity/Pages/Account/Profile.cshtml.cs b/src/BaGet.Identity/Pages/Account/Profile.cshtml.cs new file mode 100644 index 000000000..958f31584 --- /dev/null +++ b/src/BaGet.Identity/Pages/Account/Profile.cshtml.cs @@ -0,0 +1,14 @@ +using Microsoft.AspNetCore.Mvc; + +namespace BaGet.Identity.Pages.Account +{ + /// + /// The signed in user's own profile. + /// + public class MyProfileModel : AccountPageModel + { + protected override bool RequiresSignIn => true; + + public IActionResult OnGet() => LocalRedirect(Url.Content($"~/profiles/{System.Uri.EscapeDataString(User.Identity.Name)}")); + } +} diff --git a/src/BaGet.Identity/Pages/Profiles/Profile.cshtml b/src/BaGet.Identity/Pages/Profiles/Profile.cshtml new file mode 100644 index 000000000..daed5eca9 --- /dev/null +++ b/src/BaGet.Identity/Pages/Profiles/Profile.cshtml @@ -0,0 +1,47 @@ +@page "/profiles/{name}" +@model BaGet.Identity.Pages.Profiles.ProfileModel +@{ + ViewData["Title"] = Model.Name; +} + +
+

@Model.Name

+ + + @if (Model.IsOrganization) + { +

Organization with @Model.Members.Count member@(Model.Members.Count == 1 ? "" : "s"): + @foreach (var member in Model.Members) + { + @member + } +

+ } + + @if (Model.IsCurrentUser) + { +

API keys · Organizations

+ } + +

Packages

+ @if (Model.Packages.Count == 0) + { +

No packages.

+ } + else + { + + + + @foreach (var package in Model.Packages) + { + + + + + + } + +
PackageDownloads
@package.Id@package.Downloads.ToString("N0")@if (Model.IsCurrentUser || Model.IsOrganization) { Manage }
+ } +
diff --git a/src/BaGet.Identity/Pages/Profiles/Profile.cshtml.cs b/src/BaGet.Identity/Pages/Profiles/Profile.cshtml.cs new file mode 100644 index 000000000..eb1103198 --- /dev/null +++ b/src/BaGet.Identity/Pages/Profiles/Profile.cshtml.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity.Pages.Account; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace BaGet.Identity.Pages.Profiles +{ + /// + /// A user's or an organization's public page: the packages it owns. + /// + public class ProfileModel : AccountPageModel + { + [BindProperty(SupportsGet = true)] + public string Name { get; set; } + + public bool IsOrganization { get; private set; } + + public IReadOnlyList Packages { get; private set; } = Array.Empty(); + + public IReadOnlyList Members { get; private set; } = Array.Empty(); + + public bool IsCurrentUser { get; private set; } + + public async Task OnGetAsync(CancellationToken cancellationToken) + { + var context = HttpContext.RequestServices.GetRequiredService(); + var user = await UserManager.FindByNameAsync(Name); + + IReadOnlyList ids; + if (user != null) + { + Name = user.UserName; + IsCurrentUser = User.Identity?.IsAuthenticated == true && UserManager.GetUserId(User) == user.Id; + + // Only the packages owned in the user's own name: an organization's are on its page. + var lowerName = user.UserName.ToLowerInvariant(); + ids = await context.PackageOwners + .AsNoTracking() + .Where(o => o.OwnerName.ToLower() == lowerName) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken); + } + else + { + var members = await Ownership.GetMembersAsync(Name, cancellationToken); + var lowerName = Name.ToLowerInvariant(); + var organization = await context.Organizations.AsNoTracking().FirstOrDefaultAsync(o => o.Name.ToLower() == lowerName, cancellationToken); + if (organization == null) return NotFound(); + + Name = organization.Name; + IsOrganization = true; + + var memberIds = members.Select(m => m.UserId).ToList(); + Members = await context.Users + .AsNoTracking() + .Where(u => memberIds.Contains(u.Id)) + .Select(u => u.UserName) + .OrderBy(n => n) + .ToListAsync(cancellationToken); + + ids = await context.PackageOwners + .AsNoTracking() + .Where(o => o.OwnerName.ToLower() == lowerName) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken); + } + + var lowerIds = ids.Select(i => i.ToLowerInvariant()).Distinct().ToList(); + Packages = await context.Packages + .AsNoTracking() + .Where(p => lowerIds.Contains(p.Id.ToLower())) + .GroupBy(p => p.Id) + .Select(g => new PackageDownloads { Id = g.Key, Downloads = g.Sum(p => p.Downloads) }) + .OrderBy(p => p.Id) + .ToListAsync(cancellationToken); + + return Page(); + } + } +} diff --git a/src/BaGet.Web/Controllers/PackageMetadataAdminController.cs b/src/BaGet.Web/Controllers/PackageMetadataAdminController.cs index 8f23192bf..c8bc691e0 100644 --- a/src/BaGet.Web/Controllers/PackageMetadataAdminController.cs +++ b/src/BaGet.Web/Controllers/PackageMetadataAdminController.cs @@ -19,12 +19,6 @@ namespace BaGet.Web ///
public class PackageMetadataAdminController : Controller { - /// - /// The deprecation reasons the protocol defines. - /// See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation - /// - internal static readonly IReadOnlyList KnownReasons = new[] { "Legacy", "CriticalBugs", "Other" }; - private readonly IAuthenticationService _authentication; private readonly IPackageAuthorizationService _authorization; private readonly IPackageDatabase _packages; @@ -131,10 +125,10 @@ internal static string Validate(DeprecationRequest request) return "At least one deprecation reason is required."; } - var unknown = request.Reasons.FirstOrDefault(r => !KnownReasons.Contains(r, StringComparer.Ordinal)); + var unknown = request.Reasons.FirstOrDefault(r => !PackageDeprecation.KnownReasons.Contains(r, StringComparer.Ordinal)); if (unknown != null) { - return $"Unknown deprecation reason '{unknown}'. Use one of: {string.Join(", ", KnownReasons)}."; + return $"Unknown deprecation reason '{unknown}'. Use one of: {string.Join(", ", PackageDeprecation.KnownReasons)}."; } if (request.Message?.Length > AbstractContext.DefaultMaxStringLength) diff --git a/src/BaGet.Web/Pages/Package.cshtml b/src/BaGet.Web/Pages/Package.cshtml index 9f489642d..109d597a1 100644 --- a/src/BaGet.Web/Pages/Package.cshtml +++ b/src/BaGet.Web/Pages/Package.cshtml @@ -258,6 +258,24 @@ else +
+

Owners

+ + +
+ @if (Model.Package.Authors.Any()) {
diff --git a/src/BaGet.Web/Pages/ReportAbuse.cshtml b/src/BaGet.Web/Pages/ReportAbuse.cshtml index d803af406..01d728521 100644 --- a/src/BaGet.Web/Pages/ReportAbuse.cshtml +++ b/src/BaGet.Web/Pages/ReportAbuse.cshtml @@ -1,9 +1,7 @@ @page "/packages/{id}/{version}/report-abuse" +@model BaGet.Web.ReportAbuseModel @{ - var id = (string)RouteData.Values["id"]; - var version = (string)RouteData.Values["version"]; - ViewData["Title"] = "Report abuse"; } @@ -13,14 +11,48 @@

You are reporting - @id @version. + @Model.Id @Model.Version.

-

- This feed has no abuse reporting workflow of its own. Contact whoever - administers it, quoting the package ID and version above, and they can unlist - or delete the package. -

+ @if (Model.Submitted) + { + + } + else if (!Model.CanReport) + { +

+ This feed cannot record reports. Contact whoever administers it, quoting the + package ID and version above, and they can unlist or delete the package. +

+ } + else + { +
+
+
+ + +
+
+ + +
+
+ + +
+ +
+ }

If the package was mirrored from an upstream feed, report it there as well: diff --git a/src/BaGet.Web/Pages/ReportAbuse.cshtml.cs b/src/BaGet.Web/Pages/ReportAbuse.cshtml.cs new file mode 100644 index 000000000..c1c32c993 --- /dev/null +++ b/src/BaGet.Web/Pages/ReportAbuse.cshtml.cs @@ -0,0 +1,95 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; +using NuGet.Versioning; + +namespace BaGet.Web +{ + ///

+ /// Records a report against a package version, for its owners and the administrator. + /// The page works for any ID and version: a client expands the report abuse template + /// from whatever it is looking at. + /// + public class ReportAbuseModel : PageModel + { + private readonly IContext _context; + private readonly SystemTime _time; + + public ReportAbuseModel(IContext context, SystemTime time) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } + + [BindProperty(SupportsGet = true)] + public string Id { get; set; } + + [BindProperty(SupportsGet = true)] + public string Version { get; set; } + + [BindProperty] + [Required] + public string Reason { get; set; } + + [BindProperty] + [Required] + [StringLength(AbstractContext.DefaultMaxStringLength)] + public string Details { get; set; } + + [BindProperty] + [EmailAddress] + [StringLength(AbstractContext.MaxEmailLength)] + [Display(Name = "Your email (optional)")] + public string ReporterEmail { get; set; } + + public bool Submitted { get; private set; } + + /// + /// Reports are kept in the database, which Azure Table storage cannot do. + /// + public bool CanReport => !(_context is NullContext); + + public void OnGet() + { + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + if (!CanReport) return NotFound(); + + if (!AbuseReport.Reasons.Contains(Reason, StringComparer.Ordinal)) + { + ModelState.AddModelError(nameof(Reason), "Choose one of the reasons listed."); + } + + if (Id == null || Id.Length > AbstractContext.MaxPackageIdLength + || !NuGetVersion.TryParse(Version, out var version)) + { + return NotFound(); + } + + if (!ModelState.IsValid) return Page(); + + _context.AbuseReports.Add(new AbuseReport + { + PackageId = Id, + PackageVersion = version.ToNormalizedString(), + Reason = Reason, + Details = Details, + ReporterEmail = string.IsNullOrWhiteSpace(ReporterEmail) ? null : ReporterEmail.Trim(), + Created = _time.UtcNow, + }); + await _context.SaveChangesAsync(cancellationToken); + + Submitted = true; + + return Page(); + } + } +} diff --git a/src/BaGet.Web/Pages/Shared/_Layout.cshtml b/src/BaGet.Web/Pages/Shared/_Layout.cshtml index 3134be80d..58a94165a 100644 --- a/src/BaGet.Web/Pages/Shared/_Layout.cshtml +++ b/src/BaGet.Web/Pages/Shared/_Layout.cshtml @@ -25,6 +25,7 @@
+} +@if (!Model.IsReadOnlyMode) +{ +} diff --git a/src/BaGet.Web/Pages/Upload.cshtml.cs b/src/BaGet.Web/Pages/Upload.cshtml.cs index a3dc57d14..fe0dd1a4c 100644 --- a/src/BaGet.Web/Pages/Upload.cshtml.cs +++ b/src/BaGet.Web/Pages/Upload.cshtml.cs @@ -42,6 +42,11 @@ public class UploadModel : PageModel internal const string ApiKeyRejectedMessage = "That API key was not accepted."; + internal const string NoApiKeyMessage = + "This server has no API key configured and no accounts, so there is nothing to " + + "tell one visitor from another and nothing to authenticate an upload with. " + + "Set \"ApiKey\", or enable \"Accounts:Enabled\", to upload through the browser."; + internal const string UnknownTokenMessage = "This upload is no longer staged. It was cancelled, already published, or staged " + "by someone else - upload the file again."; @@ -57,6 +62,14 @@ public class UploadModel : PageModel "This symbol package is not valid (its entries, a PDB that is not portable, or " + "PDBs that do not match the package)."; + internal const string NotASymbolPackageMessage = + "A .snupkg must declare the SymbolsPackage package type in its own nuspec. This " + + "file does not, so it is not a symbol package - and a symbols archive is not a " + + "package either. Repack it as a symbol package, or upload the .nupkg instead."; + + internal const string CouldNotStageMessage = + "The server could not store this upload. Try again."; + private readonly IOptionsSnapshot _options; private readonly IOptions _accounts; private readonly IAuthenticationService _authentication; @@ -110,10 +123,27 @@ public UploadModel( public bool NeedsApiKey => !AccountsEnabled; /// - /// Whether to render the form at all. Read-only mode and an anonymous visitor get an - /// explanation instead of a file picker that could only fail. + /// Nothing on this server can tell one caller from another: accounts are off and no + /// global API key is configured, which is how BaGet ships. The browser upload is + /// closed there rather than offered as a publish button to whoever finds the page, + /// and the API key box - which would accept anything, including nothing - is not + /// rendered to claim otherwise. dotnet nuget push is unaffected: this page is + /// a convenience, not the authorization model. + /// + public bool NothingCanAuthenticate => !AccountsEnabled && string.IsNullOrEmpty(_options.Value.ApiKey); + + /// + /// What the page says in that state, so the explanation and the refusal are one + /// sentence rather than two that could drift apart. + /// + public string NoApiKeyExplanation => NoApiKeyMessage; + + /// + /// Whether to render the form at all. Read-only mode, a server nothing can + /// authenticate against, and an anonymous visitor each get an explanation instead of + /// a file picker that could only fail. /// - public bool CanUpload => !IsReadOnlyMode && (!AccountsEnabled || SignedIn); + public bool CanUpload => !IsReadOnlyMode && !NothingCanAuthenticate && (!AccountsEnabled || SignedIn); /// /// The staged upload awaiting confirmation, or null while on step one. @@ -139,6 +169,7 @@ public async Task OnPostStageAsync( CancellationToken cancellationToken) { if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); var principal = await AuthenticateAsync(apiKey, cancellationToken); if (principal == null) return Refuse(401, NotAuthenticatedMessage); @@ -165,6 +196,16 @@ public async Task OnPostStageAsync( var staged = await ReadOrNullAsync(content, cancellationToken); if (staged == null) return Refuse(400, UnreadableMessage); + // The content decides the pipeline, never the file's name. A .snupkg whose + // nuspec does not declare the symbols package type is therefore not a symbol + // package - and publishing it as a package would store a symbols archive as the + // .nupkg of that ID and version, while the symbol endpoint reads the identical + // bytes as symbols. Refused rather than published as something it is not. + if (extension.Equals(".snupkg", StringComparison.OrdinalIgnoreCase) && !staged.IsSymbolPackage) + { + return Refuse(400, NotASymbolPackageMessage); + } + // Authorized before the upload is stored: there is no point keeping a file its // uploader may not publish. if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, staged.Id, cancellationToken)) @@ -175,7 +216,20 @@ public async Task OnPostStageAsync( await DescribeSymbolTargetAsync(staged, cancellationToken); content.Position = 0; - staged.Token = await _staging.StageAsync(content, principal.UserId, cancellationToken); + + try + { + staged.Token = await _staging.StageAsync(content, principal.UserId, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + // A failure the server owns, reported the way the equivalent failure on the + // confirm step is: a sentence with a status code, never a bare 500 or a + // stack trace. + _logger.LogError(e, "Could not stage an upload of {PackageId} {PackageVersion}", staged.Id, staged.Version); + + return Refuse(500, CouldNotStageMessage); + } Staged = staged; @@ -189,6 +243,7 @@ public async Task OnPostSubmitAsync( CancellationToken cancellationToken) { if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); var principal = await AuthenticateAsync(apiKey, cancellationToken); if (principal == null) return Refuse(401, NotAuthenticatedMessage); @@ -203,7 +258,7 @@ public async Task OnPostSubmitAsync( var staged = await ReadOrNullAsync(content, cancellationToken); if (staged == null) { - await _staging.RemoveAsync(token, cancellationToken); + await _staging.RemoveAsync(token, principal.UserId, cancellationToken); return Refuse(400, UnreadableMessage); } @@ -222,22 +277,41 @@ public async Task OnPostSubmitAsync( // screen, and the first check guarded the store, not the publish. if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, staged.Id, cancellationToken)) { - await _staging.RemoveAsync(token, cancellationToken); + await _staging.RemoveAsync(token, principal.UserId, cancellationToken); return Refuse(403, Denied(staged.Id)); } content.Position = 0; return staged.IsSymbolPackage - ? await PublishSymbolsAsync(staged, content, cancellationToken) + ? await PublishSymbolsAsync(staged, content, principal, cancellationToken) : await PublishPackageAsync(staged, content, principal, cancellationToken); } - public async Task OnPostCancelAsync(string token, CancellationToken cancellationToken) + /// + /// Discard a staged upload. Authenticated, owner-checked and refused in read-only + /// mode, exactly as the other two handlers are: the token is the only handle on an + /// upload, so anyone who learned one - from a log, a screenshot, a shared screen - + /// could otherwise make its owner upload the whole file again, and the deletion is a + /// write to the store that read-only mode is meant to freeze. + /// + public async Task OnPostCancelAsync( + string token, + string apiKey, + CancellationToken cancellationToken) { - // Cancelling needs no authorization: the token is unguessable, and removing an - // upload only discards it. - await _staging.RemoveAsync(token, cancellationToken); + if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); + + var principal = await AuthenticateAsync(apiKey, cancellationToken); + if (principal == null) return Refuse(401, NotAuthenticatedMessage); + + // Another user's token is indistinguishable from one that never existed, as it + // is when submitting. + if (!await _staging.RemoveAsync(token, principal.UserId, cancellationToken)) + { + return Refuse(404, UnknownTokenMessage); + } Message = "The upload was discarded."; @@ -272,7 +346,7 @@ private async Task PublishPackageAsync( await _authorization.OnPushedAsync(principal, staged.Id, cancellationToken); } - await _staging.RemoveAsync(staged.Token, cancellationToken); + await _staging.RemoveAsync(staged.Token, principal.UserId, cancellationToken); switch (result) { @@ -299,6 +373,7 @@ private async Task PublishPackageAsync( private async Task PublishSymbolsAsync( StagedUpload staged, Stream content, + BaGetPrincipal principal, CancellationToken cancellationToken) { // Branched on the indexing result, not on a status code: a malformed symbol @@ -306,7 +381,7 @@ private async Task PublishSymbolsAsync( // endpoint reports the first as 400 and every exception as 400 as well. var result = await _symbols.IndexAsync(content, cancellationToken); - await _staging.RemoveAsync(staged.Token, cancellationToken); + await _staging.RemoveAsync(staged.Token, principal.UserId, cancellationToken); switch (result) { diff --git a/src/BaGet/Program.cs b/src/BaGet/Program.cs index 07710554f..d7cd3a0f8 100644 --- a/src/BaGet/Program.cs +++ b/src/BaGet/Program.cs @@ -15,6 +15,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace BaGet @@ -204,6 +205,8 @@ private static void ConfigurePipeline(WebApplication app) // cheaper than depending on the builder's choices. app.UseHostFiltering(); + WarnIfNothingAuthenticates(app, options); + if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); @@ -248,6 +251,27 @@ private static void ConfigurePipeline(WebApplication app) new BaGetEndpointBuilder().MapEndpoints(app); } + /// + /// Say once, at startup, that this server accepts packages from anyone. With no + /// global API key and no accounts there is nothing to tell one caller from another, + /// so every push, overwrite and delete is open to whoever can reach the server. That + /// is a legitimate configuration on a private network and the shipped default, which + /// is exactly why it must not be silent. + /// + private static void WarnIfNothingAuthenticates(WebApplication app, BaGetOptions options) + { + if (options.IsReadOnlyMode) return; + if (!string.IsNullOrEmpty(options.ApiKey)) return; + + var accounts = app.Configuration.GetSection(nameof(BaGetOptions.Accounts)).Get(); + if (accounts?.Enabled == true) return; + + app.Logger.LogWarning( + "No API key is configured and accounts are disabled, so anyone who can reach this " + + "server may publish packages, claim package IDs and delete versions. Set \"ApiKey\", " + + "or turn on \"Accounts:Enabled\", to require authentication."); + } + /// /// Turn a configured path base into one the request pipeline can use. An absent /// value, "." and "/" all mean "no path base"; anything else is given the leading diff --git a/tests/BaGet.Core.Tests/Authentication/ApiKeyAuthenticationServiceTests.cs b/tests/BaGet.Core.Tests/Authentication/ApiKeyAuthenticationServiceTests.cs index 767966654..27c1f28aa 100644 --- a/tests/BaGet.Core.Tests/Authentication/ApiKeyAuthenticationServiceTests.cs +++ b/tests/BaGet.Core.Tests/Authentication/ApiKeyAuthenticationServiceTests.cs @@ -50,6 +50,26 @@ public async Task RejectsAnApiKeyWithSurroundingWhitespace() Assert.False(await Authenticate("secret", " secret ")); } + [Theory] + // Same length, differing at the first character and at the last: the comparison is + // fixed time, so neither can be told from the other by how long the answer took. + [InlineData("Xecret")] + [InlineData("secreX")] + [InlineData("XXXXXX")] + public async Task RejectsAKeyOfTheRightLengthThatIsWrong(string providedApiKey) + { + Assert.False(await Authenticate("secret", providedApiKey)); + } + + [Fact] + public async Task AcceptsAKeyWhoseCharactersAreNotAscii() + { + // The comparison is over the UTF-8 bytes, so a multi-byte key still matches + // itself and nothing else. + Assert.True(await Authenticate("sécret-🔑", "sécret-🔑")); + Assert.False(await Authenticate("sécret-🔑", "sécret-🔒")); + } + [Theory] [InlineData(null)] [InlineData("")] diff --git a/tests/BaGet.Core.Tests/Services/StoragePackageStagingServiceTests.cs b/tests/BaGet.Core.Tests/Services/StoragePackageStagingServiceTests.cs index b3e6083d1..ee22b47a2 100644 --- a/tests/BaGet.Core.Tests/Services/StoragePackageStagingServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/StoragePackageStagingServiceTests.cs @@ -50,6 +50,22 @@ public async Task RejectsANullPackage() await Assert.ThrowsAsync( () => _target.StageAsync(null, "alice", CancellationToken.None)); } + + [Fact] + public async Task NeverLogsTheTokenAboveDebug() + { + // The token is the whole capability over a staged upload. A log at + // Information is on by default and usually shipped to a store read by more + // people than the uploader, so the token must not travel there. + var logger = new RecordingLogger(); + var target = new StoragePackageStagingService(_storage, _time.Object, logger); + + var token = await target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); + await target.OpenAsync(token, "bob", CancellationToken.None); + await target.SweepAsync(_now.AddDays(1), CancellationToken.None); + + Assert.Empty(logger.Entries.Where(e => e.Level > LogLevel.Debug && e.Message.Contains(token))); + } } public class OpenAsync : FactsBase @@ -120,17 +136,30 @@ public async Task ForgetsTheUploadAndLeavesNothingStored() { var token = await _target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); - await _target.RemoveAsync(token, CancellationToken.None); + Assert.True(await _target.RemoveAsync(token, "alice", CancellationToken.None)); Assert.Null(await _target.OpenAsync(token, "alice", CancellationToken.None)); Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); } + [Fact] + public async Task AnotherUserCannotForgetAStagedUpload() + { + // The token is the only handle on a staged upload, so anyone who learned one + // could otherwise make its owner upload the whole file again. + var token = await _target.StageAsync(StringStream("a staged package"), "alice", CancellationToken.None); + + Assert.False(await _target.RemoveAsync(token, "bob", CancellationToken.None)); + + using var kept = await _target.OpenAsync(token, "alice", CancellationToken.None); + Assert.Equal("a staged package", await ToStringAsync(kept)); + } + [Fact] public async Task AnUnknownTokenIsNotAnError() { - await _target.RemoveAsync("0123456789abcdef0123456789abcdef", CancellationToken.None); - await _target.RemoveAsync("../packages/secret", CancellationToken.None); + Assert.False(await _target.RemoveAsync("0123456789abcdef0123456789abcdef", "alice", CancellationToken.None)); + Assert.False(await _target.RemoveAsync("../packages/secret", "alice", CancellationToken.None)); } } @@ -182,6 +211,49 @@ public async Task TouchesNothingOutsideStaging() Assert.Single(await _storage.ListAsync("packages", CancellationToken.None))); } + [Fact] + public async Task KeepsAnUploadWhoseMetadataCannotBeReadRightNow() + { + // A metadata read can fail for reasons that have nothing to do with the + // upload being abandoned - a backup or a scanner holding the file, a store + // that is briefly unreachable. Collecting it then would discard an upload + // staged a minute ago, whose preview is still open. + var token = await _target.StageAsync(StringStream("staged a moment ago"), "alice", CancellationToken.None); + var metadataPath = Path.Combine(_storePath, "staging", token + ".json"); + + using (File.Open(metadataPath, FileMode.Open, FileAccess.Read, FileShare.None)) + { + Assert.Equal(0, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); + } + + using var kept = await _target.OpenAsync(token, "alice", CancellationToken.None); + Assert.Equal("staged a moment ago", await ToStringAsync(kept)); + } + + [Fact] + public async Task CollectsAnUploadWhoseMetadataIsGone() + { + // Nobody can open an upload whose metadata is absent, so there is nothing to + // keep: the owner it belonged to is unknowable. + var token = await _target.StageAsync(StringStream("half staged"), "alice", CancellationToken.None); + File.Delete(Path.Combine(_storePath, "staging", token + ".json")); + + Assert.Equal(1, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); + Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); + } + + [Fact] + public async Task CollectsAnUploadWhoseMetadataCanNeverBeRead() + { + // Unreadable content, unlike an unreadable file, does not become readable on + // the next pass. + var token = await _target.StageAsync(StringStream("corrupt"), "alice", CancellationToken.None); + File.WriteAllText(Path.Combine(_storePath, "staging", token + ".json"), "not json"); + + Assert.Equal(1, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); + Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); + } + [Fact] public async Task SaysSoWhenTheStoreCannotBeSwept() { diff --git a/tests/BaGet.Tests/AccountsWithoutGlobalKeyTests.cs b/tests/BaGet.Tests/AccountsWithoutGlobalKeyTests.cs new file mode 100644 index 000000000..5fe1eba08 --- /dev/null +++ b/tests/BaGet.Tests/AccountsWithoutGlobalKeyTests.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Xunit; +using Xunit.Abstractions; + +namespace BaGet.Tests +{ + /// + /// Accounts enabled with no global API key configured. Enabling accounts is asking for + /// ownership to decide who may push what, so an unset global key must mean "there is no + /// global key" - not "every caller is the superuser", which would bypass ownership + /// entirely. + /// + public class AccountsWithoutGlobalKeyTests : IDisposable + { + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public AccountsWithoutGlobalKeyTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary + { + // As src/BaGet/appsettings.json ships it, with accounts turned on. + { "ApiKey", "" }, + { "Accounts:Enabled", "true" }, + }); + _client = _app.CreateClient(); + } + + [Fact] + public async Task APushWithNoApiKeyIsRefused() + { + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Anonymous.Package", "1.0.0", apiKey: null)); + } + + [Fact] + public async Task APushWithAnUnknownApiKeyIsRefused() + { + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Anonymous.Package", "1.0.0", "not-a-key")); + } + + [Fact] + public async Task AUsersOwnKeyStillPushes() + { + var alice = await CreateUserAsync("alice"); + + Assert.Equal( + HttpStatusCode.Created, + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); + } + + [Fact] + public async Task OwnershipStillGatesAnIdSomeoneElseOwns() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); + + Assert.Equal( + HttpStatusCode.Created, + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); + + // Bob's own key is refused, and so is no key at all: without the second check a + // keyless push would be the superuser and would overwrite Alice's ID. + Assert.Equal( + HttpStatusCode.Forbidden, + await PushAsync("Alice.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Push))); + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "3.0.0", apiKey: null)); + + Assert.Equal(new[] { "alice" }, await OwnersAsync("Alice.Package")); + } + + [Fact] + public async Task ADeleteWithNoApiKeyIsRefused() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + + using var request = new HttpRequestMessage(HttpMethod.Delete, "api/v2/package/Alice.Package/1.0.0"); + using var response = await _client.SendAsync(request); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + private async Task PushAsync(string id, string version, string apiKey) + { + using var package = TestPackages.Build(id, version); + using var request = TestPackages.PushRequest(package, apiKey); + using var response = await _client.SendAsync(request); + + return response.StatusCode; + } + + private async Task> OwnersAsync(string id) + { + using var scope = _app.Services.CreateScope(); + var ownership = scope.ServiceProvider.GetRequiredService(); + + var owners = await ownership.GetOwnersAsync(id, CancellationToken.None); + var names = new List(); + foreach (var owner in owners) names.Add(owner.OwnerName); + + return names; + } + + private async Task CreateUserAsync(string userName) + { + using var scope = _app.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + + var user = new BaGetUser { UserName = userName, Created = DateTime.UtcNow }; + var result = await users.CreateAsync(user, "Passw0rd!"); + + Assert.True(result.Succeeded, string.Join(", ", result.Errors)); + + return user; + } + + private async Task CreateKeyAsync(BaGetUser user, string scope) + { + using var serviceScope = _app.Services.CreateScope(); + var keys = serviceScope.ServiceProvider.GetRequiredService(); + + return await keys.CreateAsync(user.Id, "test", new[] { scope }, "*", expires: null, CancellationToken.None); + } + + public void Dispose() + { + _client.Dispose(); + _app.Dispose(); + } + } +} diff --git a/tests/BaGet.Tests/BrowserUploadSecurityTests.cs b/tests/BaGet.Tests/BrowserUploadSecurityTests.cs new file mode 100644 index 000000000..e11d9b010 --- /dev/null +++ b/tests/BaGet.Tests/BrowserUploadSecurityTests.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Identity; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using NuGet.Versioning; +using Xunit; +using Xunit.Abstractions; + +namespace BaGet.Tests +{ + /// + /// The shipped default: no API key and no accounts. Nothing can tell one caller from + /// another there, so the browser upload is closed rather than a publish button for + /// whoever finds the page. + /// + public class BrowserUploadWithoutAnyApiKeyTests : IDisposable + { + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public BrowserUploadWithoutAnyApiKeyTests(ITestOutputHelper output) + { + // Exactly src/BaGet/appsettings.json as it ships: ApiKey "" and no accounts. + _app = new BaGetApplication(output, configOverrides: new Dictionary + { + { "ApiKey", "" }, + }); + _client = _app.CreateClient(); + } + + [Fact] + public async Task TheFormIsNotOfferedWhenNothingCanAuthenticateAnUpload() + { + using var browser = new Browser(_app); + + using var response = await browser.GetAsync("upload"); + var html = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + // No file picker, and no API key box that would be ignored if filled in. + Assert.DoesNotContain("name=\"package\"", html); + Assert.DoesNotContain("name=\"apiKey\"", html); + Assert.Contains("upload-no-api-key", html); + } + + [Fact] + public async Task AnAnonymousVisitorCannotStageAnything() + { + using var browser = new Browser(_app); + + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + apiKey: null, + tokenPage: BrowserUpload.TokenPage); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotMatch("name=\"token\" value=\"[0-9a-f]{32}\"", await response.Content.ReadAsStringAsync()); + Assert.False(await ExistsAsync("TestData", "1.2.3")); + } + + [Fact] + public async Task AnEmptyApiKeyBoxIsNotAWayIn() + { + using var browser = new Browser(_app); + + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + apiKey: "", + tokenPage: BrowserUpload.TokenPage); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.False(await ExistsAsync("TestData", "1.2.3")); + } + + [Fact] + public async Task ThePushEndpointIsUnchanged() + { + // Closing the browser form must not close the API an open server already has: + // the page is a convenience, not the authorization model. + using var package = TestPackages.Build("Open.Package", "1.0.0"); + using var request = TestPackages.PushRequest(package, apiKey: null); + using var response = await _client.SendAsync(request); + + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + private async Task ExistsAsync(string id, string version) + { + using var scope = _app.Services.CreateScope(); + var packages = scope.ServiceProvider.GetRequiredService(); + + return await packages.ExistsAsync(id, NuGetVersion.Parse(version), CancellationToken.None); + } + + public void Dispose() + { + _client.Dispose(); + _app.Dispose(); + } + } + + /// + /// A store that fails while an upload is being staged is reported as a sentence, as the + /// equivalent failure on the confirm step already is - not as a bare 500 or a stack + /// trace. + /// + public class BrowserUploadStorageFailureTests : IDisposable + { + private const string GlobalKey = "global-key"; + + private readonly BaGetApplication _app; + + public BrowserUploadStorageFailureTests(ITestOutputHelper output) + { + _app = new BaGetApplication( + output, + configOverrides: new Dictionary { { "ApiKey", GlobalKey } }, + configureServices: services => services.Replace( + ServiceDescriptor.Scoped(_ => new UnwritableStaging()))); + } + + [Fact] + public async Task AStoreThatCannotHoldTheUploadIsReportedAsASentence() + { + using var browser = new Browser(_app); + + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + GlobalKey); + var html = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.Contains("could not store", html); + Assert.DoesNotContain(" at ", html); + Assert.DoesNotContain("the disk is full", html); + } + + public void Dispose() => _app.Dispose(); + + private sealed class UnwritableStaging : IPackageStagingService + { + public Task StageAsync(Stream package, string ownerId, CancellationToken cancellationToken = default) + => throw new IOException("the disk is full"); + + public Task OpenAsync(string token, string ownerId, CancellationToken cancellationToken = default) + => Task.FromResult(null); + + public Task RemoveAsync(string token, string ownerId, CancellationToken cancellationToken = default) + => Task.FromResult(false); + + public Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default) + => Task.FromResult(0); + } + } + + /// + /// Discarding a staged upload is a write to storage and a loss to its owner, so it is + /// refused on a read-only server exactly as publishing is. + /// + public class BrowserUploadCancelReadOnlyTests : IDisposable + { + private readonly BaGetApplication _app; + + public BrowserUploadCancelReadOnlyTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary + { + { "ApiKey", "global-key" }, + { "Accounts:Enabled", "true" }, + { "IsReadOnlyMode", "true" }, + }); + } + + [Fact] + public async Task AReadOnlyServerRefusesToDiscardAStagedUpload() + { + using var alice = new Browser(_app); + await alice.RegisterAsync("alice"); + + // Staged through the service: a read-only server refuses the upload itself, and + // the case being pinned is a server switched to read-only while a preview is open. + var aliceId = await WithScopeAsync(async s => + (await s.GetRequiredService>().FindByNameAsync("alice")).Id); + + var staging = _app.Services.GetRequiredService(); + var token = await staging.StageAsync(Package(), aliceId, CancellationToken.None); + + using var response = await alice.CancelAsync(token, tokenPage: BrowserUpload.TokenPage); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Contains("read-only", await response.Content.ReadAsStringAsync()); + + // The upload is still there, so nothing in storage was written. + using var kept = await staging.OpenAsync(token, aliceId, CancellationToken.None); + Assert.NotNull(kept); + } + + private async Task WithScopeAsync(Func> action) + { + using var scope = _app.Services.CreateScope(); + + return await action(scope.ServiceProvider); + } + + private static Stream Package() => TestResources.GetResourceStream(TestResources.Package); + + public void Dispose() => _app.Dispose(); + } + + /// + /// Abandoned staged uploads are only ever reclaimed by the sweep, and the sweep can only + /// reclaim what the store can enumerate. A store that cannot be swept grows without + /// bound, so every store BaGet ships must be listable. + /// + public class StorageCanBeSweptTests + { + [Theory] + [InlineData(typeof(FileStorageService))] + [InlineData(typeof(NullStorageService))] + [InlineData(typeof(BaGet.Azure.BlobStorageService))] + [InlineData(typeof(BaGet.Aws.S3StorageService))] + [InlineData(typeof(BaGet.Gcp.GoogleCloudStorageService))] + [InlineData(typeof(BaGet.Aliyun.AliyunStorageService))] + public void EveryStoreCanListWhatItHolds(Type storage) + { + Assert.True( + typeof(IListableStorageService).IsAssignableFrom(storage), + $"{storage.Name} cannot be swept: it does not implement {nameof(IListableStorageService)}, " + + "so abandoned staged uploads would accumulate in it forever."); + } + } +} diff --git a/tests/BaGet.Tests/BrowserUploadTests.cs b/tests/BaGet.Tests/BrowserUploadTests.cs index 9911fc9bc..62440efe8 100644 --- a/tests/BaGet.Tests/BrowserUploadTests.cs +++ b/tests/BaGet.Tests/BrowserUploadTests.cs @@ -62,11 +62,17 @@ public static Task SubmitAsync( return browser.PostAsync("upload", fields, "upload?handler=Submit", tokenPage); } - public static Task CancelAsync(this Browser browser, string token) - => browser.PostAsync( - "upload", - new Dictionary { { "token", token } }, - "upload?handler=Cancel"); + public static Task CancelAsync( + this Browser browser, + string token, + string apiKey = null, + string tokenPage = null) + { + var fields = new Dictionary { { "token", token } }; + if (apiKey != null) fields["apiKey"] = apiKey; + + return browser.PostAsync("upload", fields, "upload?handler=Cancel", tokenPage); + } /// /// The staging token the preview is carrying, which is the only handle on a staged @@ -311,6 +317,71 @@ public async Task SymbolsForAVersionThatDoesNotExistAreRefusedAndClaimNothing() Assert.Empty(await OwnersAsync("TestData")); } + [Fact] + public async Task AnotherUsersTokenCannotDiscardTheirUpload() + { + using var alice = await SignInAsync("alice"); + using var bob = await SignInAsync("bob"); + + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Alice.1.0.0.nupkg", TestPackages.Build("Alice.Discard", "1.0.0"))); + + using (var stolen = await bob.CancelAsync(token)) + { + // Indistinguishable from a token that never existed, as submitting is. + Assert.Equal(HttpStatusCode.NotFound, stolen.StatusCode); + Assert.Contains(UploadModel.UnknownTokenMessage, await stolen.Content.ReadAsStringAsync()); + } + + // Alice's upload is untouched, so Bob could not make her upload the file again. + using var mine = await alice.SubmitAsync(token); + + Assert.Equal(HttpStatusCode.OK, mine.StatusCode); + Assert.True(await ExistsAsync("Alice.Discard", "1.0.0")); + } + + [Fact] + public async Task AnAnonymousVisitorCannotDiscardAStagedUpload() + { + using var alice = await SignInAsync("alice"); + using var anonymous = new Browser(_app); + + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Alice.1.0.0.nupkg", TestPackages.Build("Alice.Anonymous", "1.0.0"))); + + using (var attempt = await anonymous.PostAsync( + "upload", + new Dictionary { { "token", token } }, + "upload?handler=Cancel", + BrowserUpload.TokenPage)) + { + Assert.Equal(HttpStatusCode.Unauthorized, attempt.StatusCode); + } + + using var mine = await alice.SubmitAsync(token); + + Assert.Equal(HttpStatusCode.OK, mine.StatusCode); + Assert.True(await ExistsAsync("Alice.Anonymous", "1.0.0")); + } + + [Fact] + public async Task AFileNamedSnupkgThatIsNotASymbolPackageIsRefused() + { + using var alice = await SignInAsync("alice"); + + // The content decides the pipeline, so a symbols file name over package content + // must not be published as a package under that ID - the symbol endpoint would + // read the very same bytes as symbols. + using var response = await alice.StageAsync( + "NotSymbols.1.0.0.snupkg", + TestPackages.Build("NotSymbols", "1.0.0")); + var html = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Contains("SymbolsPackage", html); + Assert.False(await ExistsAsync("NotSymbols", "1.0.0")); + } + [Fact] public async Task AnAnonymousVisitorIsAskedToSignIn() { @@ -451,9 +522,15 @@ public async Task TheApiKeyIsNeverWrittenIntoThePage() "TestData.1.2.3.nupkg", TestResources.GetResourceStream(TestResources.Package), GlobalKey); + var html = await staged.Content.ReadAsStringAsync(); + + // Asserted first: a refusal's body carries no API key either, so without this the + // test would stay green against an upload page that never previewed anything. + Assert.Equal(HttpStatusCode.OK, staged.StatusCode); + BrowserUpload.StagedToken(html); // The preview asks for the key again rather than carrying it in a hidden field. - Assert.DoesNotContain(GlobalKey, await staged.Content.ReadAsStringAsync()); + Assert.DoesNotContain(GlobalKey, html); } public void Dispose() => _app.Dispose(); @@ -503,6 +580,20 @@ public async Task ASignedInSessionIsRefused() Assert.Contains(UploadModel.ReadOnlyMessage, await response.Content.ReadAsStringAsync()); } + [Fact] + public async Task ThePushInstructionsAreNotOfferedWhilePushingIsRefused() + { + using var app = Application(accounts: false); + using var browser = new Browser(app); + + var html = await browser.GetPageAsync("upload"); + + // The page must not refuse an upload and then hand out commands that answer 401. + Assert.Contains("upload-read-only", html); + Assert.DoesNotContain("You can push packages using the service index", html); + Assert.DoesNotContain("nuget push -Source", html); + } + private BaGetApplication Application(bool accounts) => new BaGetApplication(_output, configOverrides: new Dictionary { diff --git a/tests/BaGet.Tests/PackageManagementPageTests.cs b/tests/BaGet.Tests/PackageManagementPageTests.cs index 71899b9df..96f4e1ed6 100644 --- a/tests/BaGet.Tests/PackageManagementPageTests.cs +++ b/tests/BaGet.Tests/PackageManagementPageTests.cs @@ -220,6 +220,40 @@ public async Task TheManagePageLinksToUploadingANewVersion() Assert.Contains("id=Alice.Package", html); } + [Fact] + public async Task MyPackagesListsIdsOwnedThroughAnOrganization() + { + await Alice.RegisterAsync("alice"); + + var aliceId = await WithScopeAsync(async s => + (await s.GetRequiredService>().FindByNameAsync("alice")).Id); + + await WithScopeAsync(async s => + { + var ownership = s.GetRequiredService(); + + Assert.True(await ownership.CreateOrganizationAsync("acme", aliceId, CancellationToken.None)); + + return true; + }); + + using (var package = TestPackages.Build("Acme.Package", "1.0.0")) + { + await App.AddPackageAsync(package); + } + + Assert.Equal( + OwnerChangeResult.Success, + await WithScopeAsync(s => s.GetRequiredService() + .AddOwnerAsync("Acme.Package", "acme", CancellationToken.None))); + + var html = await Alice.GetPageAsync("account/packages"); + + // The organization owns the ID, not Alice: the list unions her own name with + // every organization she belongs to, which is the non-obvious half of the query. + Assert.Contains("Acme.Package", html); + } + [Fact] public async Task UploadingANewVersionArrivesWithTheIdAsAHint() { @@ -320,5 +354,98 @@ public async Task AReadOnlyServerRefusesToDelete() Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); Assert.NotNull(await FindAsync("Alice.Package", "1.0.0")); } + + [Fact] + public async Task AReadOnlyServerRefusesToUnlist() + { + await Alice.RegisterAsync("alice"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); + + using var response = await PostAsync("Unlist", new Dictionary + { + { "version", "1.0.0" }, + }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + + // Unlisting is the very operation the Delete button is said to perform, so a + // server that refuses one must refuse the other. + Assert.True((await FindAsync("Alice.Package", "1.0.0")).Listed); + } + + [Fact] + public async Task AReadOnlyServerRefusesToRelist() + { + await Alice.RegisterAsync("alice"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); + + await WithScopeAsync(s => s.GetRequiredService() + .UnlistPackageAsync("Alice.Package", NuGetVersion.Parse("1.0.0"), CancellationToken.None)); + + using var response = await PostAsync("Relist", new Dictionary + { + { "version", "1.0.0" }, + }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + Assert.False((await FindAsync("Alice.Package", "1.0.0")).Listed); + } + + [Fact] + public async Task AReadOnlyServerRefusesToDeprecate() + { + await Alice.RegisterAsync("alice"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); + + using var response = await PostAsync("Deprecate", new Dictionary + { + { "version", "1.0.0" }, + { "reasons", PackageDeprecation.KnownReasons[0] }, + }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + Assert.Null((await FindAsync("Alice.Package", "1.0.0")).Deprecation); + } + + [Fact] + public async Task AReadOnlyServerRefusesToChangeTheOwners() + { + await Alice.RegisterAsync("alice"); + await Bob.RegisterAsync("bob"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); + + using var response = await PostAsync("AddOwner", new Dictionary + { + { "ownerName", "bob" }, + }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + + var owners = await WithScopeAsync(s => s.GetRequiredService() + .GetOwnersAsync("Alice.Package", CancellationToken.None)); + + Assert.Equal("alice", Assert.Single(owners).OwnerName); + } + + [Fact] + public async Task AReadOnlyManagePageSaysSo() + { + await Alice.RegisterAsync("alice"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); + + var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); + + Assert.Contains("manage-read-only", html); + } + + private Task PostAsync(string handler, Dictionary fields) + => Alice.PostAsync( + "packages/Alice.Package/manage", + fields, + action: $"packages/Alice.Package/manage?handler={handler}"); } } diff --git a/tests/BaGet.Tests/StagingIntegrationTests.cs b/tests/BaGet.Tests/StagingIntegrationTests.cs index 77afdffce..8d74e16b9 100644 --- a/tests/BaGet.Tests/StagingIntegrationTests.cs +++ b/tests/BaGet.Tests/StagingIntegrationTests.cs @@ -39,7 +39,7 @@ public async Task StagesAndForgetsAPackageWithoutAccounts() Assert.NotNull(staged); } - await staging.RemoveAsync(token, CancellationToken.None); + Assert.True(await staging.RemoveAsync(token, ownerId: null, CancellationToken.None)); Assert.Null(await staging.OpenAsync(token, ownerId: null, CancellationToken.None)); } From f3874623857b831a665ca50a0625597af286cd32 Mon Sep 17 00:00:00 2001 From: pieroviano Date: Sat, 17 Oct 2026 08:20:42 +0300 Subject: [PATCH 068/498] Removed files --- .../browser-upload-and-package-management.md | 223 ------------------ 1 file changed, 223 deletions(-) delete mode 100644 docs/plans/browser-upload-and-package-management.md diff --git a/docs/plans/browser-upload-and-package-management.md b/docs/plans/browser-upload-and-package-management.md deleted file mode 100644 index 1c4b5e47a..000000000 --- a/docs/plans/browser-upload-and-package-management.md +++ /dev/null @@ -1,223 +0,0 @@ -# Browser upload and package management UI - -Give signed-in users a nuget.org-like flow: upload a package through the browser with a metadata -preview, and manage the packages they own. - -## Already built — do not rebuild - -| Capability | Where | -|---|---| -| Register, Login, Logout, account Profile, API keys, Organizations | `src/BaGet.Identity/Pages/Account/` | -| Public profile | `src/BaGet.Identity/Pages/Profiles/Profile.cshtml` | -| Per-package owner page: owners, unlist, relist, deprecate, abuse reports | `src/BaGet.Identity/Pages/Packages/Manage.cshtml.cs:62-110` | -| List the IDs a user owns (incl. via organization) | `PackageOwnershipService.GetOwnedPackageIdsAsync` — `src/BaGet.Identity/PackageOwnershipService.cs:83` | -| Submission pipeline (validation-aware) | `IPackageSubmissionService` — `src/BaGet.Core/Indexing/IPackageSubmissionService.cs` | -| Push authorization + first-push ownership | `IPackageAuthorizationService` — `src/BaGet.Core/Authentication/IPackageAuthorizationService.cs:22` | -| Multipart limit already unbounded | `ConfigureBaGetOptions.Configure(FormOptions)` — `src/BaGet/ConfigureBaGetOptions.cs:80-83` | -| Sign in / API keys nav | `src/BaGet.Web/Pages/Shared/_Layout.cshtml:35-49` | - -**So the real gaps are:** a browser upload, a "my packages" list, version delete, and symbols in the UI. -`Unlist`/`Relist` already exist (`Manage.cshtml.cs:78-81`, rendered at `Manage.cshtml:50-52`) and only -need to be reachable from the new list. - -## Decisions - -| # | Decision | Consequence | -|---|---|---| -| D1 | Two-step upload with metadata preview | Needs the `.nupkg` staged between two requests. No session or TempData exists in the repo today, so staging is new infrastructure — see C2. | -| D2 | A signed-in session gets `ApiKeyScopes.All`, `isSuperuser: false`, glob `*` | Ownership still decides: `OwnershipAuthorizationService.cs:44-48` requires `IsOwnerAsync` for an existing ID, so a user can push a new ID or one they own, nothing else. Not an escalation over the API-key path. | -| D3 | With `Accounts:Enabled=false`, show the form with a pasted API key | The upload page **cannot** derive from `AccountPageModel`: that base answers 404 whenever accounts are disabled (`AccountPageModel.cs:42-46`). It needs its own base handling both modes. | -| D4 | Management covers: my-packages list, version delete, upload-a-version from the package page, `.snupkg` | Delete must honour `BaGetOptions.PackageDeletionBehavior`; `Unlist`/`Relist` are reuse, not new work. | - -## Blocking verification — before writing code - -| # | Check | Why it blocks | How | -|---|---|---|---| -| B1 | A staged `.nupkg` must not be downloadable by anyone who guesses its name | Staging in `IStorageService` shares a store with served packages. | Inspect `BaGetEndpointBuilder.MapPackageContentRoutes` and `FileStorageService` path handling; add a test requesting the staging path over HTTP. | -| B2 | `.snupkg` push requires the package to already exist | Decides the UI's error text and whether symbols can be a first upload. | Read `SymbolIndexingService.IndexAsync` for its "package not found" result. | -| B3 | `PackageDeletionBehavior` semantics | `Unlist` vs `HardDelete` makes "Delete" mean two different things; the button must say which. | `src/BaGet.Core/Configuration/BaGetOptions.cs:43` and `PackageDeletionService`. | -| B4 | Antiforgery with a large multipart body | Razor Pages validate the token before model binding; with a several-hundred-MB file the token must still be read first. | Prototype a 200 MB multipart POST against a stub page; confirm nothing beyond `FormOptions` is needed. | -| B5 | `IStorageService` resolves when accounts are disabled | The API-key mode of D3 stages files too. | Provider-resolved in `Program.ConfigureServices`; assert with an integration test at `Accounts:Enabled=false`. | - -B1 and B5 passed, so the temp-file fallback is dropped: no route in BaGet turns a request into a -storage path, and `IStorageService` is provider-resolved independently of `Accounts:Enabled`. - -## Changes - -### C1 — Session principal (`src/BaGet.Identity/`) - -New `SessionPrincipalFactory`, so the browser path reuses the same authorization as API keys. - -```csharp -/// -/// The principal for a signed-in browser session. A session carries every scope - ownership -/// still decides which IDs it may touch - so the UI can do what the user's own API key could. -/// -public BaGetPrincipal Create(ClaimsPrincipal user) - => new BaGetPrincipal( - userId: _users.GetUserId(user), - userName: user.Identity.Name, - isSuperuser: false, - scopes: ApiKeyScopes.All, - packageGlobPattern: "*"); -``` - -### C2 — Staging (`src/BaGet.Core/`) - -New `IPackageStagingService` plus a storage-backed implementation, so the preview step survives a -multi-instance deployment and works on all four storage providers. - -```csharp -public interface IPackageStagingService -{ - /// An opaque token identifying the staged upload. - Task StageAsync(Stream package, string ownerId, CancellationToken cancellationToken); - - /// Null if the token is unknown, expired, or was staged by a different user. - Task OpenAsync(string token, string ownerId, CancellationToken cancellationToken); - - Task RemoveAsync(string token, CancellationToken cancellationToken); -} -``` - -Built (`src/BaGet.Core/Staging/`), with `Task SweepAsync(DateTime stagedBefore, ...)` added to the -interface above: - -| Point | As built | -|---|---| -| Token | 128 bits from `RandomNumberGenerator`, hex encoded (`StoragePackageStagingService.CreateToken`) — a token reaches storage, so `OpenAsync`/`RemoveAsync` refuse anything that is not 32 lowercase hex characters before it becomes a path. It is logged only at `Debug`; above that a short SHA-256 correlation id stands in, so a log reader cannot act on what they read | -| Owner | Recorded in `staging/{token}.json`; `OpenAsync` **and** `RemoveAsync` compare it ordinally and refuse otherwise, so one user can neither confirm nor discard another's upload. With accounts off every upload shares the empty owner, as the API-key path has no user either | -| Paths | `staging/{token}.json` (metadata, written first so the sweep can always find the upload) and `staging/{token}.nupkg` | -| Null store | `Storage:Type=Null` reads back nothing, so a staged upload reports itself as an unknown token instead of yielding a null stream | -| Sweep | `SweepAsync` removes every upload staged before a cutoff; `StagingSweepWorker` (`src/BaGet.Web/`) runs it hourly with a 24-hour cutoff. An upload whose metadata is **absent** or will never parse is collected whatever its age — nobody can open it. One whose metadata is merely unreadable *this time* (a store briefly unreachable, a file a backup holds open) is kept: "unreadable now" must not discard an upload staged a minute ago. The two are told apart from the sweep's own listing | -| Listing | The sweep needs to enumerate a prefix, which `IStorageService` cannot. New optional capability `IListableStorageService`, implemented by **every** store BaGet ships: `FileStorageService`, `NullStorageService`, `BlobStorageService`, `S3StorageService`, `GoogleCloudStorageService`, `AliyunStorageService`. A store that does not implement it logs a warning and is not swept; `StorageCanBeSweptTests` pins that none of the shipped ones is in that state | - -### C3 — Upload page (`src/BaGet.Web/Pages/Upload.cshtml`) - -Built. The CLI tabs stay, below the form. `UploadModel` is a plain `PageModel`, **not** an -`AccountPageModel` (D3): that base answers 404 while accounts are disabled. - -| Handler | As built | -|---|---| -| `OnPostStageAsync(IFormFile package, string apiKey)` | Refuse read-only (401) → refuse a server nothing can authenticate against (401) → authenticate (401) → reject anything but `.nupkg`/`.snupkg` (400) → read the archive (400 if unreadable) → reject a `.snupkg` whose nuspec does not declare `SymbolsPackage` (400) → `AuthorizeAsync(Push, id)` **before** storing (403) → `StageAsync`, a storage failure reported as a sentence (500) → render the preview | -| `OnPostSubmitAsync(string token, string apiKey, bool acceptTerms)` | Refuse read-only (401) → refuse a server nothing can authenticate against (401) → authenticate (401) → `OpenAsync(token, userId)`, null ⇒ 404 "no longer staged" → re-read the archive → require the checkbox (400, upload kept) → `AuthorizeAsync` again (403) → `SubmitAsync`, `OnPushedAsync`, `RemoveAsync` | -| `OnPostCancelAsync(string token, string apiKey)` | Refuse read-only (401) → refuse a server nothing can authenticate against (401) → authenticate (401) → `RemoveAsync(token, userId)`, false ⇒ 404 "no longer staged". Owner-checked like the other two: the token is the only handle on an upload, so anyone who learned one could otherwise make its owner upload the whole file again, and the deletion is a store write read-only mode is meant to freeze. The button posts from the confirm form, so the one API key field serves both | - -**A server nothing can authenticate against** is accounts off with no `ApiKey`, which is how -BaGet ships. Nothing there tells one visitor from another, so the page explains that instead -of rendering a file picker and an API key box that would accept anything, including nothing. -`PUT /api/v2/package` is untouched — the page is a convenience, not the authorization model — -and `Program.WarnIfNothingAuthenticates` says so once at startup. - -| Point | As built | -|---|---| -| Preview | ID, version, description, authors, license (expression, else URL), dependencies by framework, readme. `PackageDependencies.GroupByFramework` and `ReadmeMarkdown` are shared with the package page, so a preview cannot describe the package differently from how it will be served | -| Terms | Alpine disables the button until the box is ticked, **and** the handler refuses without it - with the upload kept staged, so ticking the box is all that is needed | -| Mode | `AccountsEnabled` ⇒ `SessionPrincipalFactory.Create(User)`, resolved from `HttpContext.RequestServices` because the factory is only registered when accounts are on. Otherwise `AuthenticatePrincipalAsync(apiKey)` | -| API key | Asked again on the confirm form rather than carried in a hidden field, so the key is never written into HTML (the risk table's last row) | -| Authorization | Checked at both steps: the first spares the store a file nobody may publish, the second is the one that gates publishing (ownership can change while a preview is open) | -| Antiforgery | Nothing added, per B4: the form tag helper's single hidden token plus the existing `FormOptions` and Kestrel settings are sufficient, and field order is irrelevant. No `[RequestSizeLimit]`/`[RequestFormLimits]` | -| Failure | Every refusal is a sentence on the page with a matching status code (401/403/404/400/409/500), never a stack trace | - -### C4 — Symbols - -Built into the same page. The **content** decides the pipeline, not the file name: a symbol package -declares `packageType="SymbolsPackage"` in its own nuspec, so renaming a file cannot route it to a -pipeline its content does not belong to. - -| Point | As built | -|---|---| -| Preview | The target ID and version, and the `.pdb` entries found. `IPackageDatabase.FindOrNullAsync(id, version, includeUnlisted: true)` runs at **step one**, so a missing target is reported before the upload is confirmed (B2) | -| Result | Branched on `SymbolIndexingResult`, not on a status code: `PackageNotFound` ⇒ "Symbols can only be uploaded for a package version already on this server. Push {id} {version} first."; `InvalidSymbolPackage` ⇒ a message about entries, non-portable PDBs or PDBs that do not match. The push endpoint reports both as 400, so a status-driven UI would say the wrong thing | -| Ownership | No `OnPushedAsync` on this path, as on the symbol endpoint: a symbol upload claims no ID and grants no ownership. Pinned by a test | - -### C5 — My packages (`src/BaGet.Identity/Pages/Account/Packages.cshtml`) - -Built. `PackagesModel : AccountPageModel`, `RequiresSignIn => true`, linked from the signed-in nav -(`_Layout.cshtml:41`, between the profile and the API keys). - -| Point | As built | -|---|---| -| Source | `Ownership.GetOwnedPackageIdsAsync(userId, userName)`, so organization-owned IDs are listed too. Ownership decides, not the package table: an ID whose every version was hard-deleted keeps its owners and stays listed, with "None" as its latest version | -| Per ID | One `IContext.Packages` projection over every owned ID, giving latest version (highest, listed or not, marked "(unlisted)"), version count and summed downloads. `IContext`, not `IPackageDatabase`: the ownership query the page starts from already needs `IContext`, so a per-ID `FindAsync` loop bought nothing and cost six round trips per ID (it eagerly loads dependencies, package types, target frameworks, deprecation and vulnerabilities to compute three numbers). Highest version is still chosen in memory — SemVer ordering is not SQL's | -| Links | `Manage` for the ID, and "Upload new version" (`/Upload?id=…`) per row | - -### C6 — Delete and upload-a-version on `Manage` - -Built. `Unlist`/`Relist` are untouched and reachable from the new list. - -| Point | As built | -|---|---| -| `OnPostDeleteAsync(string version)` | Read-only ⇒ a message and nothing touched, mirroring the DELETE endpoint → parse the version (404) → `IPackageDeletionService.TryDeletePackageAsync`. No notification here: `PackageDeletionService` notifies the catalog itself | -| Label (B3) | `Unlist` ⇒ "Unlist this version", "Hidden from search and from the version list; anyone who knows the exact version can still restore it." `HardDelete` ⇒ "Delete this version permanently", plus the caveats B3 establishes: the rows and the `.nupkg`/`.nuspec`/readme/icon go, indexed PDBs keep being served, and an external search index keeps the version until reindexed. The button never claims to delete on a server that unlists | -| Confirmation | `onclick="return confirm(…)"` carrying that same label and caption | -| `false` from the service | Reported as "was not in the database", not as "nothing happened": a hard delete removes the files either way | -| Upload a version | `asp-page="/Upload" asp-route-id="@Model.Id"`; `UploadModel.Id` is a bound hint the page shows, never a source of the published ID — that is read from the file | - -`src/BaGet.Identity/Pages/Packages/` was matched by `.gitignore`'s `**/packages/*`, so `Manage` had -never been committed. A negation was added and the page is now tracked. - -## Verification - -| # | Step | Expected | -|---|---|---| -| 1 | `dotnet test BaGet.sln -p:GeneratePackageOnBuild=false` | 928 green (880 before C5/C6, plus 12, plus 36 for the review fixes below) | -| 2 | Stage, preview, submit while signed in | 200 and a published message (a page, not the API's 201), the package served, the token unknown afterwards | -| 3 | Stage as user A, submit with user B's cookie | Rejected; A's file untouched | -| 4 | Submit an ID owned by another user | 403, nothing indexed | -| 5 | Push a brand-new ID through the browser | Succeeds, pusher becomes owner (`OnPushedAsync`) | -| 6 | `Accounts:Enabled=false` with a correct and an incorrect API key | Accepted / 401, and the page never 404s | -| 7 | `IsReadOnlyMode=true` | Both modes refuse | -| 8 | Request a staged file's storage path over HTTP | 404 (B1) | -| 9 | Cancel, then reuse the token | Token unknown | -| 10 | Upload the same version twice | 409 as a readable message, not a stack trace | -| 11 | `.snupkg` for a package that does not exist | The message B2 establishes | -| 12 | Delete a version under each `PackageDeletionBehavior` | Unlisted or hard-deleted accordingly, and the button says which | -| 13 | A real `dotnet nuget push` after a browser upload | Unaffected; the API path must not regress | -| 14 | A signed-in user's "my packages" list | Only the IDs they own; sign-in required | - -Steps 2-11 are pinned by `tests/BaGet.Tests/BrowserUploadTests.cs`; step 8 by -`StagingIntegrationTests`, step 13 by the existing push tests, which stayed green, and steps 12 and -14 by `tests/BaGet.Tests/PackageManagementPageTests.cs` (one application per `PackageDeletionBehavior`, -since a test host configuration is fixed when it is built). - -## Risks - -| Risk | Likelihood | Handling | -|---|---|---| -| Staged files accumulate | **High if unmanaged** | The sweep in C2 is in scope; verification 2 and 9 assert removal | -| Staging reachable as a download | Medium | B1 is blocking; the temp-file fallback is stated above | -| Antiforgery versus large multipart | Medium | B4 before coding | -| Two-step doubles wall time for large packages | Low | Staging writes once; `SubmitAsync` reads from storage, not the network | -| D2 misread as granting superuser | Low | `isSuperuser: false` is explicit and verification 4 pins it | -| API key posted in a form body when accounts are off | Low | Same exposure as the `X-NuGet-ApiKey` header over the same channel; must not be logged | - -## Deviations and follow-ups - -Found by review after C1-C6 and resolved in the same branch. - -| # | Change | Why it matters | -|---|---|---| -| R1 | `AccountAuthenticationService` no longer treats an empty `ApiKey` as "every caller is the superuser" while accounts are on | **Behavioural break.** An accounts-enabled server with no global key now refuses a keyless push (401) instead of accepting it as the superuser. Without it the ownership gate the new pages rely on was bypassable by sending no key at all: `dotnet nuget push` with no key could overwrite an ID someone else owned. Accounts off is unchanged — `ApiKeyAuthenticationService` still leaves an unset key open | -| R2 | Browser upload closed when accounts are off and no `ApiKey` is set | The shipped default. The page was a one-click publish button for any visitor, with a password box that was ignored. `PUT /api/v2/package` is deliberately left as it was, and startup now warns that the server accepts packages from anyone | -| R3 | `IPackageStagingService.RemoveAsync` takes an `ownerId` and returns whether it removed anything | **Interface break** (`BaGet.Core` is packed). `OpenAsync` checked the owner and `RemoveAsync` did not, so a leaked token discarded someone else's pending upload | -| R4 | The staging token is logged at `Debug`; a correlation id is logged above it | The token was the only secret over a staged upload and was written at `Information` on every upload | -| R5 | Every write handler on `Manage` is refused in read-only mode, in one page filter | Only `Delete` checked. `Unlist` — which the page's own caption calls the same operation — still wrote, as did relist, deprecate, undeprecate, add/remove owner and resolve report. The API refuses all of them with 401 | -| R6 | The upload page's push instructions are suppressed in read-only mode | It said nothing can be pushed and then offered copy-paste commands that answer 401 | -| R7 | `IListableStorageService` on all four cloud stores | `SweepAsync` was a no-op on Azure, S3, GCS and Aliyun, so staged uploads accumulated there forever | -| R8 | A `.snupkg` whose nuspec does not declare `SymbolsPackage` is refused (400) | It was published as a package, storing a symbols archive as that ID and version's `.nupkg`, while the symbol endpoint read the identical bytes as symbols | -| R9 | A storage failure while staging is a sentence and a 500 | It was an unhandled exception: a bare 500 in production, a stack trace under the developer exception page | -| R10 | `CryptographicOperations.FixedTimeEquals` for the global API key | Hardening, not a usable attack in this shape; the browser form is a new caller of that comparison | - -Known and not changed: - -| Point | Why | -|---|---| -| Public surface | `PackageModel.DependencyGroupModel` and `PackageModel.DependencyModel` were nested public types and are now top-level `BaGet.Web.DependencyGroupModel` / `DependencyModel`, shared with the upload preview (C3). `BaGet.Web` is packed, so this breaks a consumer that compiled against the previous package. Accepted: the preview and the package page must describe a package the same way, and a nested display model cannot be shared. Recorded here because it was not called out when it was made | -| No staging quota | An authorized caller can park unbounded bytes under `staging/` until the 24-hour sweep reclaims them, and nothing counts them against the package store. `IStorageService` has no quota, and a per-owner cap would need either a per-owner prefix in the staging layout or one metadata read per staged upload on every stage. Comparable to pushing many distinct IDs, which is equally unbounded. R7 at least makes retention effective on every store; R2 removes the anonymous half of it | - -## Out of scope - -- Email confirmation, password reset, external login providers. -- Editing package metadata after upload — nuget.org does not allow it either. -- Organization-level upload UI beyond the ownership `GetOwnedPackageIdsAsync` already resolves. From 586ee5a39c6b94ced003a2ee259a931c59822add Mon Sep 17 00:00:00 2001 From: pieroviano Date: Sat, 17 Oct 2026 08:24:24 +0300 Subject: [PATCH 069/498] Introduced file scope namespace --- .../Sample01_Download.cs | 49 +- .../Sample02_Search.cs | 87 +- .../Sample03_Metadata.cs | 89 +- samples/BaGetWebApplication/Program.cs | 31 +- samples/BaGetWebApplication/Startup.cs | 49 +- .../AliyunApplicationExtensions.cs | 55 +- src/BaGet.Aliyun/AliyunStorageOptions.cs | 27 +- src/BaGet.Aliyun/AliyunStorageService.cs | 251 +++-- src/BaGet.Aws/AwsApplicationExtensions.cs | 139 ++- src/BaGet.Aws/S3StorageOptions.cs | 31 +- src/BaGet.Aws/S3StorageService.cs | 259 +++-- src/BaGet.Azure/AzureApplicationExtensions.cs | 265 +++-- .../Configuration/AzureBlobStorageOptions.cs | 115 ++- .../Configuration/AzureSearchOptions.cs | 17 +- .../Configuration/AzureTableOptions.cs | 13 +- .../Extensions/StorageExceptionExtensions.cs | 43 +- .../Search/AzureSearchBatchIndexer.cs | 123 ++- src/BaGet.Azure/Search/AzureSearchIndexer.cs | 55 +- src/BaGet.Azure/Search/AzureSearchService.cs | 669 +++++++------ .../Search/ExactMatchCustomAnalyzer.cs | 31 +- src/BaGet.Azure/Search/IndexActionBuilder.cs | 185 ++-- src/BaGet.Azure/Search/PackageDocument.cs | 165 ++-- src/BaGet.Azure/Search/SearchFilters.cs | 49 +- src/BaGet.Azure/Storage/BlobStorageService.cs | 203 ++-- src/BaGet.Azure/Table/PackageEntity.cs | 169 ++-- .../Table/PackageEntityExtensions.cs | 131 ++- src/BaGet.Azure/Table/TableJson.cs | 33 +- .../Table/TableOperationBuilder.cs | 203 ++-- src/BaGet.Azure/Table/TablePackageDatabase.cs | 373 ++++--- src/BaGet.Azure/Table/TableSearchService.cs | 473 +++++---- src/BaGet.Catalog/CatalogController.cs | 105 +- src/BaGet.Catalog/CatalogDatabase.cs | 157 ++- src/BaGet.Catalog/CatalogReader.cs | 175 ++-- src/BaGet.Catalog/CatalogRebuilder.cs | 155 ++- .../CatalogServiceCollectionExtensions.cs | 35 +- .../CatalogServiceIndexProvider.cs | 43 +- src/BaGet.Catalog/CatalogWriter.cs | 421 ++++---- src/BaGet.Catalog/ICatalogDatabase.cs | 49 +- .../ApiKeyAuthenticationService.cs | 49 +- .../Authentication/BaGetPrincipal.cs | 89 +- .../Authentication/IAuthenticationService.cs | 23 +- .../IPackageAuthorizationService.cs | 79 +- src/BaGet.Core/BaGetApplication.cs | 17 +- .../Configuration/AccountsOptions.cs | 87 +- src/BaGet.Core/Configuration/BaGetOptions.cs | 145 ++- src/BaGet.Core/Configuration/BindOptions.cs | 33 +- .../Configuration/DatabaseOptions.cs | 37 +- src/BaGet.Core/Configuration/FeedsOptions.cs | 27 +- .../Configuration/FileSystemStorageOptions.cs | 35 +- src/BaGet.Core/Configuration/MirrorOptions.cs | 57 +- .../Configuration/PackageDeletionBehavior.cs | 35 +- src/BaGet.Core/Configuration/SearchOptions.cs | 11 +- .../Configuration/StorageOptions.cs | 11 +- .../Configuration/ValidationOptions.cs | 59 +- .../Content/DefaultPackageContentService.cs | 127 ++- .../Content/IPackageContentService.cs | 143 ++- src/BaGet.Core/Entities/AbstractContext.cs | 635 ++++++------ src/BaGet.Core/Entities/AbuseReport.cs | 53 +- src/BaGet.Core/Entities/Accounts.cs | 193 ++-- src/BaGet.Core/Entities/CatalogEntry.cs | 75 +- .../Converters/StringArrayComparer.cs | 23 +- .../Converters/StringArrayToJsonConverter.cs | 21 +- .../Converters/UriToStringConverter.cs | 21 +- src/BaGet.Core/Entities/IContext.cs | 101 +- src/BaGet.Core/Entities/NullContext.cs | 59 +- src/BaGet.Core/Entities/Package.cs | 157 ++- src/BaGet.Core/Entities/PackageDependency.cs | 33 +- src/BaGet.Core/Entities/PackageDeprecation.cs | 87 +- src/BaGet.Core/Entities/PackageType.cs | 19 +- src/BaGet.Core/Entities/PackageValidation.cs | 91 +- .../Entities/PackageVulnerability.cs | 53 +- src/BaGet.Core/Entities/SemVerLevel.cs | 25 +- src/BaGet.Core/Entities/TargetFramework.cs | 15 +- .../Extensions/BaGetApplicationExtensions.cs | 53 +- ...DependencyInjectionExtensions.Providers.cs | 215 ++-- .../DependencyInjectionExtensions.cs | 361 ++++--- src/BaGet.Core/Extensions/IProvider.cs | 69 +- .../PackageArchiveReaderExtensions.cs | 335 ++++--- src/BaGet.Core/Extensions/StreamExtensions.cs | 83 +- src/BaGet.Core/Extensions/SystemTime.cs | 17 +- src/BaGet.Core/IPackageDatabase.cs | 267 +++-- src/BaGet.Core/IPackageService.cs | 115 ++- src/BaGet.Core/IUrlGenerator.cs | 323 +++--- .../Indexing/FrameworkCompatibilityService.cs | 119 ++- .../IFrameworkCompatibilityService.cs | 23 +- .../Indexing/IPackageChangeHandler.cs | 29 +- .../Indexing/IPackageDeletionService.cs | 25 +- .../Indexing/IPackageIndexingService.cs | 67 +- .../Indexing/IPackageSubmissionService.cs | 53 +- .../Indexing/ISymbolIndexingService.cs | 59 +- .../Indexing/PackageChangeNotifier.cs | 87 +- .../Indexing/PackageDeletionService.cs | 157 ++- .../Indexing/PackageIndexingService.cs | 315 +++--- .../Indexing/SymbolIndexingService.cs | 683 +++++++------ .../Metadata/BaGetPackageMetadata.cs | 47 +- .../Metadata/BaGetRegistrationIndexPage.cs | 29 +- .../BaGetRegistrationIndexPageItem.cs | 29 +- .../BaGetRegistrationIndexResponse.cs | 47 +- .../Metadata/DefaultPackageMetadataService.cs | 73 +- .../Metadata/IPackageMetadataService.cs | 53 +- .../Metadata/PackageRegistration.cs | 49 +- .../Metadata/RegistrationBuilder.cs | 271 +++--- src/BaGet.Core/PackageDatabase.cs | 407 ++++---- src/BaGet.Core/PackageService.cs | 217 ++--- src/BaGet.Core/Search/AutocompleteRequest.cs | 61 +- .../Search/DatabaseSearchService.cs | 429 ++++---- src/BaGet.Core/Search/DependentsResponse.cs | 71 +- src/BaGet.Core/Search/ISearchIndexer.cs | 23 +- .../Search/ISearchResponseBuilder.cs | 51 +- src/BaGet.Core/Search/ISearchService.cs | 81 +- src/BaGet.Core/Search/NullSearchIndexer.cs | 19 +- src/BaGet.Core/Search/NullSearchService.cs | 101 +- src/BaGet.Core/Search/SearchRequest.cs | 69 +- .../Search/SearchResponseBuilder.cs | 129 ++- src/BaGet.Core/Search/VersionsRequest.cs | 37 +- .../ServiceIndex/BaGetServiceIndex.cs | 93 +- .../IServiceIndexResourceProvider.cs | 17 +- .../ServiceIndex/IServiceIndexService.cs | 27 +- .../Staging/IPackageStagingService.cs | 71 +- .../Staging/StoragePackageStagingService.cs | 573 ++++++----- .../Statistics/StatisticsService.cs | 149 ++- src/BaGet.Core/Storage/FileStorageService.cs | 199 ++-- .../Storage/IListableStorageService.cs | 49 +- .../Storage/IPackageStorageService.cs | 143 ++- src/BaGet.Core/Storage/IStorageService.cs | 135 ++- .../Storage/ISymbolStorageService.cs | 53 +- src/BaGet.Core/Storage/NullStorageService.cs | 63 +- .../Storage/PackageStorageService.cs | 361 ++++--- .../Storage/SymbolStorageService.cs | 109 +-- .../Clients/DisabledUpstreamClient.cs | 47 +- .../Upstream/Clients/V2UpstreamClient.cs | 309 +++--- .../Upstream/Clients/V3UpstreamClient.cs | 271 +++--- src/BaGet.Core/Upstream/DownloadsImporter.cs | 87 +- .../Upstream/IPackageDownloadsSource.cs | 11 +- src/BaGet.Core/Upstream/IUpstreamClient.cs | 77 +- .../Upstream/PackageDownloadsJsonSource.cs | 139 ++- .../Validation/RequiredIfAttribute.cs | 235 +++-- .../Validation/ValidateBaGetOptions.cs | 69 +- .../Validation/ValidateStartupOptions.cs | 83 +- .../MySqlApplicationExtensions.cs | 49 +- src/BaGet.Database.MySql/MySqlContext.cs | 101 +- .../MySqlContextFactory.cs | 45 +- .../PostgreSqlApplicationExtensions.cs | 37 +- .../PostgreSqlContext.cs | 101 +- .../PostgreSqlContextFactory.cs | 37 +- .../SqlServerApplicationExtensions.cs | 37 +- .../SqlServerContext.cs | 49 +- .../SqlServerContextFactory.cs | 37 +- .../SqliteApplicationExtensions.cs | 37 +- src/BaGet.Database.Sqlite/SqliteContext.cs | 83 +- .../SqliteContextFactory.cs | 37 +- .../GoogleCloudApplicationExtensions.cs | 45 +- src/BaGet.Gcp/GoogleCloudStorageOptions.cs | 13 +- src/BaGet.Gcp/GoogleCloudStorageService.cs | 169 ++-- .../AccountAuthenticationService.cs | 97 +- .../AccountsServiceCollectionExtensions.cs | 113 ++- src/BaGet.Identity/ApiKeyService.cs | 185 ++-- .../OwnershipAuthorizationService.cs | 135 ++- src/BaGet.Identity/PackageOwnershipService.cs | 395 ++++---- .../Pages/Account/AccountPageModel.cs | 93 +- .../Pages/Account/ApiKeys.cshtml.cs | 121 ++- .../Pages/Account/Login.cshtml.cs | 209 ++-- .../Pages/Account/Logout.cshtml.cs | 27 +- .../Pages/Account/Organizations.cshtml.cs | 153 ++- .../Pages/Account/Packages.cshtml.cs | 227 +++-- .../Pages/Account/Profile.cshtml.cs | 19 +- .../Pages/Account/Register.cshtml.cs | 121 ++- .../Pages/Packages/Manage.cshtml.cs | 397 ++++---- .../Pages/Profiles/Profile.cshtml.cs | 119 ++- src/BaGet.Identity/Pages/_ViewImports.cshtml | 2 +- src/BaGet.Identity/SessionPrincipalFactory.cs | 63 +- src/BaGet.Protocol/Catalog/CatalogClient.cs | 59 +- .../Catalog/CatalogProcessor.cs | 317 +++--- .../Catalog/CatalogProcessorOptions.cs | 55 +- src/BaGet.Protocol/Catalog/FileCursor.cs | 79 +- src/BaGet.Protocol/Catalog/ICatalogClient.cs | 91 +- .../Catalog/ICatalogLeafProcessor.cs | 59 +- src/BaGet.Protocol/Catalog/ICursor.cs | 43 +- .../Catalog/NullCatalogClient.cs | 45 +- src/BaGet.Protocol/Catalog/NullCursor.cs | 31 +- .../Catalog/RawCatalogClient.cs | 91 +- .../PackageDependencyRangeJsonConverter.cs | 77 +- .../StringOrStringArrayJsonConverter.cs | 77 +- src/BaGet.Protocol/EndpointFailover.cs | 197 ++-- .../Extensions/CatalogModelExtensions.cs | 381 ++++---- .../Extensions/HttpClientExtensions.cs | 105 +- .../NuGetClientFactoryExtensions.cs | 55 +- .../PackageContentModelExtensions.cs | 31 +- .../PackageMetadataModelExtensions.cs | 91 +- .../Extensions/SearchModelExtensions.cs | 43 +- .../Extensions/ServiceIndexModelExtensions.cs | 235 +++-- src/BaGet.Protocol/Models/AlternatePackage.cs | 47 +- .../Models/AutocompleteContext.cs | 19 +- .../Models/AutocompleteResponse.cs | 41 +- src/BaGet.Protocol/Models/CatalogIndex.cs | 50 +- src/BaGet.Protocol/Models/CatalogLeaf.cs | 100 +- src/BaGet.Protocol/Models/CatalogLeafItem.cs | 68 +- src/BaGet.Protocol/Models/CatalogPage.cs | 60 +- src/BaGet.Protocol/Models/CatalogPageItem.cs | 48 +- .../Models/DependencyGroupItem.cs | 35 +- src/BaGet.Protocol/Models/DependencyItem.cs | 37 +- src/BaGet.Protocol/Models/ICatalogLeafItem.cs | 44 +- .../Models/PackageDeleteCatalogLeaf.cs | 24 +- .../Models/PackageDeprecation.cs | 57 +- .../Models/PackageDetailsCatalogLeaf.cs | 328 ++++--- src/BaGet.Protocol/Models/PackageMetadata.cs | 257 +++-- .../Models/PackageNotFoundException.cs | 47 +- .../Models/PackageVersionsResponse.cs | 25 +- .../Models/PackageVulnerabilityMetadata.cs | 39 +- .../Models/ProtocolException.cs | 81 +- .../Models/RegistrationIndexPage.cs | 71 +- .../Models/RegistrationIndexPageItem.cs | 45 +- .../Models/RegistrationIndexResponse.cs | 71 +- .../Models/RegistrationLeafResponse.cs | 99 +- .../Models/RegistrationPageResponse.cs | 19 +- src/BaGet.Protocol/Models/SearchContext.cs | 29 +- src/BaGet.Protocol/Models/SearchResponse.cs | 41 +- src/BaGet.Protocol/Models/SearchResult.cs | 235 +++-- .../Models/SearchResultPackageType.cs | 25 +- .../Models/SearchResultVersion.cs | 45 +- src/BaGet.Protocol/Models/ServiceIndexItem.cs | 45 +- .../Models/ServiceIndexResponse.cs | 35 +- src/BaGet.Protocol/NuGetClient.cs | 851 ++++++++-------- src/BaGet.Protocol/NuGetClientFactory.cs | 437 +++++---- .../PackageContent/IPackageContentClient.cs | 91 +- .../PackageContent/PackageContentClient.cs | 77 +- .../PackageContent/RawPackageContentClient.cs | 119 ++- .../PackageMetadata/IPackageMetadataClient.cs | 69 +- .../PackageMetadata/PackageMetadataClient.cs | 73 +- .../RawPackageMetadataClient.cs | 77 +- .../Search/AutocompleteClient.cs | 79 +- .../Search/IAutocompleteClient.cs | 79 +- src/BaGet.Protocol/Search/ISearchClient.cs | 51 +- .../Search/NullAutocompleteClient.cs | 33 +- .../Search/RawAutocompleteClient.cs | 105 +- src/BaGet.Protocol/Search/RawSearchClient.cs | 131 ++- src/BaGet.Protocol/Search/SearchClient.cs | 51 +- .../ServiceIndex/IServiceIndexClient.cs | 27 +- .../ServiceIndex/RawServiceIndexClient.cs | 51 +- .../ServiceIndex/ServiceIndexClient.cs | 27 +- src/BaGet.Validation/IPackageValidator.cs | 93 +- .../PackageValidationRunner.cs | 279 +++--- .../RepositorySignaturesController.cs | 333 ++++--- src/BaGet.Validation/RepositorySigner.cs | 161 ++- .../ValidatingPackageSubmissionService.cs | 195 ++-- src/BaGet.Validation/ValidationQueue.cs | 41 +- .../ValidationServiceCollectionExtensions.cs | 37 +- src/BaGet.Validation/ValidationWorker.cs | 105 +- src/BaGet.Validation/Validators.cs | 137 ++- src/BaGet.Web.V2/V2FeedController.cs | 477 +++++---- src/BaGet.Web.V2/V2FeedPackage.cs | 185 ++-- src/BaGet.Web.V2/V2FeedWriter.cs | 431 ++++---- src/BaGet.Web/BaGetEndpointBuilder.cs | 509 +++++----- src/BaGet.Web/BaGetUrlGenerator.cs | 445 +++++---- .../Controllers/PackageContentController.cs | 137 ++- .../PackageMetadataAdminController.cs | 375 ++++--- .../Controllers/PackageMetadataController.cs | 69 +- .../Controllers/PackagePublishController.cs | 293 +++--- src/BaGet.Web/Controllers/SearchController.cs | 137 ++- .../Controllers/ServiceIndexController.cs | 35 +- src/BaGet.Web/Controllers/SymbolController.cs | 145 ++- .../Controllers/VulnerabilityController.cs | 179 ++-- .../Extensions/HttpRequestExtensions.cs | 89 +- .../IApplicationBuilderExtensions.cs | 15 +- src/BaGet.Web/Extensions/IHostExtensions.cs | 57 +- .../IServiceCollectionExtensions.cs | 57 +- src/BaGet.Web/Extensions/RazorExtensions.cs | 13 +- src/BaGet.Web/NavLinkTagHelper.cs | 117 ++- src/BaGet.Web/OperationCancelledMiddleware.cs | 73 +- src/BaGet.Web/PackageDependencies.cs | 157 ++- src/BaGet.Web/Pages/Index.cshtml.cs | 83 +- src/BaGet.Web/Pages/Package.cshtml.cs | 209 ++-- src/BaGet.Web/Pages/ReportAbuse.cshtml.cs | 133 ++- src/BaGet.Web/Pages/Statistics.cshtml.cs | 29 +- src/BaGet.Web/Pages/Upload.cshtml.cs | 919 +++++++++--------- src/BaGet.Web/Pages/_ViewImports.cshtml | 2 +- src/BaGet.Web/ReadmeMarkdown.cs | 27 +- src/BaGet.Web/Routes.cs | 77 +- src/BaGet.Web/StagingSweepWorker.cs | 101 +- src/BaGet/ConfigureBaGetOptions.cs | 263 +++-- src/BaGet/ConfigureRazorRuntimeCompilation.cs | 35 +- src/BaGet/Program.cs | 443 +++++---- .../Search/AzureAutocompleteQueryTests.cs | 171 ++-- .../Search/AzureSearchFilterTests.cs | 127 ++- .../Search/AzureSearchQueryBuilderTests.cs | 293 +++--- .../Search/AzureSearchQueryTests.cs | 321 +++--- .../BaGet.Azure.Tests/Table/TableJsonTests.cs | 137 ++- .../ApiKeyAuthenticationServiceTests.cs | 131 ++- .../BaGet.Core.Tests/Entities/PackageTests.cs | 85 +- .../Entities/StringArrayComparerTests.cs | 173 ++-- .../Entities/ValueConverterTests.cs | 161 ++- .../PackageArchiveReaderExtensionsTests.cs | 597 ++++++------ .../Extensions/StreamExtensionsTests.cs | 211 ++-- .../FrameworkCompatibilityServiceTests.cs | 197 ++-- .../Indexing/PackageChangeNotifierTests.cs | 103 +- tests/BaGet.Core.Tests/Metadata/ModelTests.cs | 397 ++++---- .../Metadata/RegistrationBuilderTests.cs | 95 +- .../Search/SearchResponseBuilderTests.cs | 379 ++++---- .../ServiceIndex/BaGetServiceIndexTests.cs | 211 ++-- .../Services/FileStorageServiceTests.cs | 409 ++++---- .../Services/PackageDatabaseTests.cs | 709 +++++++------- .../Services/PackageDeletionServiceTests.cs | 205 ++-- .../Services/PackageIndexingServiceTests.cs | 757 +++++++-------- .../Services/PackageServiceTests.cs | 561 ++++++----- .../Services/PackageStorageServiceTests.cs | 905 +++++++++-------- .../StoragePackageStagingServiceTests.cs | 463 +++++---- .../Services/SymbolFileValidationTests.cs | 185 ++-- .../Services/SymbolIndexingServiceTests.cs | 611 ++++++------ .../Services/SymbolStorageServiceTests.cs | 99 +- .../Support/RecordingLogger.cs | 79 +- .../BaGet.Core.Tests/Support/TestAssembly.cs | 99 +- tests/BaGet.Core.Tests/Support/TestPackage.cs | 209 ++-- .../PackageDownloadsJsonSourceTests.cs | 225 +++-- .../Upstream/V3UpstreamClientTests.cs | 405 ++++---- .../Validation/RequiredIfAttributeTests.cs | 205 ++-- .../Validation/ValidateBaGetOptionsTests.cs | 121 ++- ...ackageDependencyRangeJsonConverterTests.cs | 121 ++- .../StringOrStringArrayJsonConverterTests.cs | 171 ++-- .../NuGetClientFactoryTests.cs | 333 ++++--- .../BaGet.Protocol.Tests/NuGetClientTests.cs | 337 ++++--- .../RawAutocompleteClientTests.cs | 227 +++-- .../RawCatalogClientTests.cs | 107 +- .../RawPackageContentClientTests.cs | 183 ++-- .../RawPackageMetadataClientTests.cs | 315 +++--- .../RawSearchClientTests.cs | 203 ++-- .../RawServiceIndexClientTests.cs | 41 +- .../SearchFailoverTests.cs | 455 +++++---- .../ServiceIndexRefreshTests.cs | 227 +++-- .../Support/CountingHttpMessageHandler.cs | 63 +- .../Support/FakeHttpMessageHandler.cs | 209 ++-- .../Support/FakeServiceIndex.cs | 55 +- .../Support/ProtocolFixture.cs | 47 +- .../Support/RecordingHttpMessageHandler.cs | 73 +- .../Support/TestDataHttpMessageHandler.cs | 119 ++- .../Support/TestQueryString.cs | 59 +- tests/BaGet.Tests/AccountsDisabledTests.cs | 79 +- tests/BaGet.Tests/AccountsIntegrationTests.cs | 477 +++++---- .../AccountsWithoutGlobalKeyTests.cs | 201 ++-- .../AllowedHostsIntegrationTests.cs | 315 +++--- tests/BaGet.Tests/ApiIntegrationTests.cs | 405 ++++---- .../BaGetClientIntegrationTests.cs | 343 ++++--- tests/BaGet.Tests/BrowserUploadReviewTests.cs | 200 ++++ .../BaGet.Tests/BrowserUploadSecurityTests.cs | 363 ++++--- tests/BaGet.Tests/BrowserUploadTests.cs | 911 +++++++++-------- tests/BaGet.Tests/CatalogIntegrationTests.cs | 317 +++--- tests/BaGet.Tests/CatalogWriterTests.cs | 87 +- .../BaGet.Tests/DatabaseSearchServiceTests.cs | 643 ++++++------ tests/BaGet.Tests/HostIntegrationTests.cs | 107 +- tests/BaGet.Tests/MirrorIntegrationTests.cs | 149 ++- .../NuGetClientIntegrationTests.cs | 499 +++++----- .../NuGetV2ClientIntegrationTests.cs | 205 ++-- .../BaGet.Tests/PackageManagementPageTests.cs | 671 +++++++------ .../BaGet.Tests/PackageMetadataAdminTests.cs | 309 +++--- tests/BaGet.Tests/PathBaseIntegrationTests.cs | 189 ++-- tests/BaGet.Tests/ReportAbusePageTests.cs | 103 +- tests/BaGet.Tests/SessionPrincipalTests.cs | 235 +++-- tests/BaGet.Tests/StagingIntegrationTests.cs | 97 +- tests/BaGet.Tests/StaticAssetsTests.cs | 77 +- tests/BaGet.Tests/Support/BaGetApplication.cs | 269 +++-- tests/BaGet.Tests/Support/Browser.cs | 173 ++-- .../HttpSourceResourceProviderTestHost.cs | 59 +- tests/BaGet.Tests/Support/StreamExtensions.cs | 29 +- tests/BaGet.Tests/Support/TestPackages.cs | 99 +- tests/BaGet.Tests/Support/TestResources.cs | 71 +- .../BaGet.Tests/Support/TestableHttpSource.cs | 75 +- tests/BaGet.Tests/Support/XunitLogger.cs | 51 +- .../Support/XunitLoggerProvider.cs | 27 +- tests/BaGet.Tests/UploadPageTests.cs | 283 +++--- tests/BaGet.Tests/V2FeedIntegrationTests.cs | 437 +++++---- .../BaGet.Tests/ValidationIntegrationTests.cs | 445 +++++---- tests/BaGet.Tests/WebUiIntegrationTests.cs | 437 +++++---- .../BaGet.Web.Tests/NavLinkTagHelperTests.cs | 313 +++--- .../BaGet.Web.Tests/Pages/IndexModelFacts.cs | 105 +- .../Pages/PackageModelFacts.cs | 599 ++++++------ 374 files changed, 29439 insertions(+), 29568 deletions(-) create mode 100644 tests/BaGet.Tests/BrowserUploadReviewTests.cs diff --git a/samples/BaGet.Protocol.Samples.Tests/Sample01_Download.cs b/samples/BaGet.Protocol.Samples.Tests/Sample01_Download.cs index e3488f9af..dd6bab73f 100644 --- a/samples/BaGet.Protocol.Samples.Tests/Sample01_Download.cs +++ b/samples/BaGet.Protocol.Samples.Tests/Sample01_Download.cs @@ -4,38 +4,37 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Samples.Tests +namespace BaGet.Protocol.Samples.Tests; + +public class Sample01_Download { - public class Sample01_Download + [Fact] + public async Task DownloadPackage() { - [Fact] - public async Task DownloadPackage() - { - // Downloads a package file (.nupkg) - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + // Downloads a package file (.nupkg) + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - string packageId = "Newtonsoft.Json"; - NuGetVersion packageVersion = new NuGetVersion("12.0.1"); + string packageId = "Newtonsoft.Json"; + NuGetVersion packageVersion = new NuGetVersion("12.0.1"); - using (Stream packageStream = await client.DownloadPackageAsync(packageId, packageVersion)) - { - Console.WriteLine($"Downloaded package {packageId} {packageVersion}"); - } + using (Stream packageStream = await client.DownloadPackageAsync(packageId, packageVersion)) + { + Console.WriteLine($"Downloaded package {packageId} {packageVersion}"); } + } - [Fact] - public async Task DownloadPackageManifest() - { - // Downloads a package manifest (.nuspec) - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + [Fact] + public async Task DownloadPackageManifest() + { + // Downloads a package manifest (.nuspec) + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - string packageId = "Newtonsoft.Json"; - NuGetVersion packageVersion = new NuGetVersion("12.0.1"); + string packageId = "Newtonsoft.Json"; + NuGetVersion packageVersion = new NuGetVersion("12.0.1"); - using (Stream manifestStream = await client.DownloadPackageManifestAsync(packageId, packageVersion)) - { - Console.WriteLine($"Downloaded package {packageId} {packageVersion}'s nuspec"); - } + using (Stream manifestStream = await client.DownloadPackageManifestAsync(packageId, packageVersion)) + { + Console.WriteLine($"Downloaded package {packageId} {packageVersion}'s nuspec"); } } -} +} \ No newline at end of file diff --git a/samples/BaGet.Protocol.Samples.Tests/Sample02_Search.cs b/samples/BaGet.Protocol.Samples.Tests/Sample02_Search.cs index 2d3cc8acb..2ca277efa 100644 --- a/samples/BaGet.Protocol.Samples.Tests/Sample02_Search.cs +++ b/samples/BaGet.Protocol.Samples.Tests/Sample02_Search.cs @@ -5,60 +5,59 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Samples.Tests +namespace BaGet.Protocol.Samples.Tests; + +public class Sample02_Search { - public class Sample02_Search + [Fact] + public async Task Exists() { - [Fact] - public async Task Exists() - { - // Check if a package exists. - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - - if (!await client.ExistsAsync("newtonsoft.json")) - { - Console.WriteLine("Package 'newtonsoft.json' does not exist!"); - } + // Check if a package exists. + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - var packageVersion = NuGetVersion.Parse("12.0.1"); - if (!await client.ExistsAsync("newtonsoft.json", packageVersion)) - { - Console.WriteLine("Package 'newtonsoft.json' version '12.0.1' does not exist!"); - } + if (!await client.ExistsAsync("newtonsoft.json")) + { + Console.WriteLine("Package 'newtonsoft.json' does not exist!"); } - [Fact] - public async Task Search() + var packageVersion = NuGetVersion.Parse("12.0.1"); + if (!await client.ExistsAsync("newtonsoft.json", packageVersion)) { - // Search for packages that are relevant to "json". - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - IReadOnlyList results = await client.SearchAsync("json"); + Console.WriteLine("Package 'newtonsoft.json' version '12.0.1' does not exist!"); + } + } - var index = 1; - foreach (SearchResult result in results) - { - Console.WriteLine($"Result #{index}"); - Console.WriteLine($"Package id: {result.PackageId}"); - Console.WriteLine($"Package version: {result.Version}"); - Console.WriteLine($"Package downloads: {result.TotalDownloads}"); - Console.WriteLine($"Package versions: {result.Versions.Count}"); - Console.WriteLine(); + [Fact] + public async Task Search() + { + // Search for packages that are relevant to "json". + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + IReadOnlyList results = await client.SearchAsync("json"); - index++; - } + var index = 1; + foreach (SearchResult result in results) + { + Console.WriteLine($"Result #{index}"); + Console.WriteLine($"Package id: {result.PackageId}"); + Console.WriteLine($"Package version: {result.Version}"); + Console.WriteLine($"Package downloads: {result.TotalDownloads}"); + Console.WriteLine($"Package versions: {result.Versions.Count}"); + Console.WriteLine(); + + index++; } + } - [Fact] - public async Task Autocomplete() - { - // Search for packages whose names' start with "Newt". - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - IReadOnlyList packageIds = await client.AutocompleteAsync("Newt"); + [Fact] + public async Task Autocomplete() + { + // Search for packages whose names' start with "Newt". + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + IReadOnlyList packageIds = await client.AutocompleteAsync("Newt"); - foreach (string packageId in packageIds) - { - Console.WriteLine($"Found package ID '{packageId}'"); - } + foreach (string packageId in packageIds) + { + Console.WriteLine($"Found package ID '{packageId}'"); } } -} +} \ No newline at end of file diff --git a/samples/BaGet.Protocol.Samples.Tests/Sample03_Metadata.cs b/samples/BaGet.Protocol.Samples.Tests/Sample03_Metadata.cs index da959f4e9..2fcc69c09 100644 --- a/samples/BaGet.Protocol.Samples.Tests/Sample03_Metadata.cs +++ b/samples/BaGet.Protocol.Samples.Tests/Sample03_Metadata.cs @@ -6,63 +6,62 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Samples.Tests +namespace BaGet.Protocol.Samples.Tests; + +public class Sample03_Metadata { - public class Sample03_Metadata + [Fact] + public async Task GetAllPackageMetadata() { - [Fact] - public async Task GetAllPackageMetadata() - { - // Find the metadata for all versions of a package. - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - - IReadOnlyList items = await client.GetPackageMetadataAsync("Newtonsoft.Json"); - if (!items.Any()) - { - Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); - return; - } + // Find the metadata for all versions of a package. + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - // There is an item for each version of the package. - foreach (var metadata in items) - { - Console.WriteLine($"Version: {metadata.Version}"); - Console.WriteLine($"Listed: {metadata.Listed}"); - Console.WriteLine($"Tags: {metadata.Tags}"); - Console.WriteLine($"Description: {metadata.Description}"); - } + IReadOnlyList items = await client.GetPackageMetadataAsync("Newtonsoft.Json"); + if (!items.Any()) + { + Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); + return; } - [Fact] - public async Task GetPackageMetadata() + // There is an item for each version of the package. + foreach (var metadata in items) { - // Find the metadata for a single version of a package. - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - - string packageId = "Newtonsoft.Json"; - NuGetVersion packageVersion = new NuGetVersion("12.0.1"); - - PackageMetadata metadata = await client.GetPackageMetadataAsync(packageId, packageVersion); - + Console.WriteLine($"Version: {metadata.Version}"); Console.WriteLine($"Listed: {metadata.Listed}"); Console.WriteLine($"Tags: {metadata.Tags}"); Console.WriteLine($"Description: {metadata.Description}"); } + } - [Fact] - public async Task ListVersions() - { - // Find all versions of a package (including unlisted versions). - NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + [Fact] + public async Task GetPackageMetadata() + { + // Find the metadata for a single version of a package. + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); + + string packageId = "Newtonsoft.Json"; + NuGetVersion packageVersion = new NuGetVersion("12.0.1"); + + PackageMetadata metadata = await client.GetPackageMetadataAsync(packageId, packageVersion); + + Console.WriteLine($"Listed: {metadata.Listed}"); + Console.WriteLine($"Tags: {metadata.Tags}"); + Console.WriteLine($"Description: {metadata.Description}"); + } - IReadOnlyList packageVersions = await client.ListPackageVersionsAsync("Newtonsoft.Json", includeUnlisted: true); - if (!packageVersions.Any()) - { - Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); - return; - } + [Fact] + public async Task ListVersions() + { + // Find all versions of a package (including unlisted versions). + NuGetClient client = new NuGetClient("https://api.nuget.org/v3/index.json"); - Console.WriteLine($"Found {packageVersions.Count} versions"); + IReadOnlyList packageVersions = await client.ListPackageVersionsAsync("Newtonsoft.Json", includeUnlisted: true); + if (!packageVersions.Any()) + { + Console.WriteLine($"Package 'Newtonsoft.Json' does not exist"); + return; } + + Console.WriteLine($"Found {packageVersions.Count} versions"); } -} +} \ No newline at end of file diff --git a/samples/BaGetWebApplication/Program.cs b/samples/BaGetWebApplication/Program.cs index a91fee8b8..224e2fec6 100644 --- a/samples/BaGetWebApplication/Program.cs +++ b/samples/BaGetWebApplication/Program.cs @@ -3,23 +3,22 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; -namespace BaGetWebApplication +namespace BaGetWebApplication; + +public class Program { - public class Program + public static async Task Main(string[] args) { - public static async Task Main(string[] args) - { - var host = CreateHostBuilder(args).Build(); - - await host.RunMigrationsAsync(); - await host.RunAsync(); - } + var host = CreateHostBuilder(args).Build(); - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); + await host.RunMigrationsAsync(); + await host.RunAsync(); } -} + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); +} \ No newline at end of file diff --git a/samples/BaGetWebApplication/Startup.cs b/samples/BaGetWebApplication/Startup.cs index fe11415a0..f64f6048a 100644 --- a/samples/BaGetWebApplication/Startup.cs +++ b/samples/BaGetWebApplication/Startup.cs @@ -4,37 +4,36 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -namespace BaGetWebApplication +namespace BaGetWebApplication; + +public class Startup { - public class Startup + public void ConfigureServices(IServiceCollection services) { - public void ConfigureServices(IServiceCollection services) + services.AddBaGetWebApplication(app => { - services.AddBaGetWebApplication(app => - { - // Use SQLite as BaGet's database and store packages on the local file system. - app.AddSqliteDatabase(); - app.AddFileStorage(); - }); - } + // Use SQLite as BaGet's database and store packages on the local file system. + app.AddSqliteDatabase(); + app.AddFileStorage(); + }); + } - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } + app.UseDeveloperExceptionPage(); + } - app.UseStaticFiles(); - app.UseRouting(); + app.UseStaticFiles(); + app.UseRouting(); - app.UseEndpoints(endpoints => - { - // Add BaGet's endpoints. - var baget = new BaGetEndpointBuilder(); + app.UseEndpoints(endpoints => + { + // Add BaGet's endpoints. + var baget = new BaGetEndpointBuilder(); - baget.MapEndpoints(endpoints); - }); - } + baget.MapEndpoints(endpoints); + }); } -} +} \ No newline at end of file diff --git a/src/BaGet.Aliyun/AliyunApplicationExtensions.cs b/src/BaGet.Aliyun/AliyunApplicationExtensions.cs index eb8a6e745..a15b66f56 100644 --- a/src/BaGet.Aliyun/AliyunApplicationExtensions.cs +++ b/src/BaGet.Aliyun/AliyunApplicationExtensions.cs @@ -6,41 +6,40 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class AliyunApplicationExtensions { - public static class AliyunApplicationExtensions + public static BaGetApplication AddAliyunOssStorage(this BaGetApplication app) { - public static BaGetApplication AddAliyunOssStorage(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddSingleton(provider => - { - var options = provider.GetRequiredService>().Value; + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; - return new OssClient(options.Endpoint, options.AccessKey, options.AccessKeySecret); - }); + return new OssClient(options.Endpoint, options.AccessKey, options.AccessKeySecret); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasStorageType("AliyunOss")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasStorageType("AliyunOss")) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddAliyunOssStorage( - this BaGetApplication app, - Action configure) - { - app.AddAliyunOssStorage(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddAliyunOssStorage( + this BaGetApplication app, + Action configure) + { + app.AddAliyunOssStorage(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Aliyun/AliyunStorageOptions.cs b/src/BaGet.Aliyun/AliyunStorageOptions.cs index 2357bdd61..9dc86a153 100644 --- a/src/BaGet.Aliyun/AliyunStorageOptions.cs +++ b/src/BaGet.Aliyun/AliyunStorageOptions.cs @@ -1,21 +1,20 @@ using System.ComponentModel.DataAnnotations; -namespace BaGet.Aliyun +namespace BaGet.Aliyun; + +public class AliyunStorageOptions { - public class AliyunStorageOptions - { - [Required] - public string AccessKey { get; set; } + [Required] + public string AccessKey { get; set; } - [Required] - public string AccessKeySecret { get; set; } + [Required] + public string AccessKeySecret { get; set; } - [Required] - public string Endpoint { get; set; } + [Required] + public string Endpoint { get; set; } - [Required] - public string Bucket { get; set; } + [Required] + public string Bucket { get; set; } - public string Prefix { get; set; } - } -} + public string Prefix { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Aliyun/AliyunStorageService.cs b/src/BaGet.Aliyun/AliyunStorageService.cs index 8e7e9131f..2f5eaa762 100644 --- a/src/BaGet.Aliyun/AliyunStorageService.cs +++ b/src/BaGet.Aliyun/AliyunStorageService.cs @@ -7,161 +7,160 @@ using BaGet.Core; using Microsoft.Extensions.Options; -namespace BaGet.Aliyun +namespace BaGet.Aliyun; + +public class AliyunStorageService : IStorageService, IListableStorageService { - public class AliyunStorageService : IStorageService, IListableStorageService - { - private const string Separator = "/"; + private const string Separator = "/"; - // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 - private const int DefaultCopyBufferSize = 81920; + // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 + private const int DefaultCopyBufferSize = 81920; - private readonly string _bucket; - private readonly string _prefix; - private readonly OssClient _client; + private readonly string _bucket; + private readonly string _prefix; + private readonly OssClient _client; - public AliyunStorageService(IOptionsSnapshot options, OssClient client) - { - if (options == null) - throw new ArgumentNullException(nameof(options)); + public AliyunStorageService(IOptionsSnapshot options, OssClient client) + { + if (options == null) + throw new ArgumentNullException(nameof(options)); - _bucket = options.Value.Bucket; - _prefix = options.Value.Prefix; - _client = client ?? throw new ArgumentNullException(nameof(client)); + _bucket = options.Value.Bucket; + _prefix = options.Value.Prefix; + _client = client ?? throw new ArgumentNullException(nameof(client)); - if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Separator)) - _prefix += Separator; - } + if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Separator)) + _prefix += Separator; + } - private string PrepareKey(string path) - { - return _prefix + path.Replace("\\", Separator); - } + private string PrepareKey(string path) + { + return _prefix + path.Replace("\\", Separator); + } - public async Task GetAsync(string path, CancellationToken cancellationToken = default) + public async Task GetAsync(string path, CancellationToken cancellationToken = default) + { + try { - try - { - var ossObject = await Task.Factory.FromAsync(_client.BeginGetObject, _client.EndGetObject, _bucket, PrepareKey(path), null); + var ossObject = await Task.Factory.FromAsync(_client.BeginGetObject, _client.EndGetObject, _bucket, PrepareKey(path), null); - return ossObject.ResponseStream; - } - catch (Exception) - { - // Unresolved: IStorageService.GetAsync is documented to return null when the - // content is missing, but no implementation does - FileStorageService throws - // FileNotFoundException and callers such as - // SymbolStorageService.GetPortablePdbContentStreamOrNullAsync catch instead of - // null-checking. Mapping OSS's NoSuchKey to null here alone would hide missing - // content from PackageStorageService, so the mismatch belongs to the interface - // and is left for a change that fixes every implementation at once. - throw; - } + return ossObject.ResponseStream; } - - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + catch (Exception) { - var uri = _client.GeneratePresignedUri(_bucket, PrepareKey(path)); - - return Task.FromResult(uri); + // Unresolved: IStorageService.GetAsync is documented to return null when the + // content is missing, but no implementation does - FileStorageService throws + // FileNotFoundException and callers such as + // SymbolStorageService.GetPortablePdbContentStreamOrNullAsync catch instead of + // null-checking. Mapping OSS's NoSuchKey to null here alone would hide missing + // content from PackageStorageService, so the mismatch belongs to the interface + // and is left for a change that fixes every implementation at once. + throw; } + } - public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) - { - if (content == null) throw new ArgumentNullException(nameof(content)); + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + var uri = _client.GeneratePresignedUri(_bucket, PrepareKey(path)); + + return Task.FromResult(uri); + } - var key = PrepareKey(path); + public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + + var key = PrepareKey(path); - using (var seekableContent = new MemoryStream()) + using (var seekableContent = new MemoryStream()) + { + await content.CopyToAsync(seekableContent, DefaultCopyBufferSize, cancellationToken); + + // Storing the same content twice is not a failure, storing different content + // at a taken key is. OSS does signal the latter itself, through the + // "x-oss-forbid-overwrite" request header and a 409 "FileAlreadyExists" + // response, but this SDK exposes neither: ObjectMetadata has no such header + // and OssException carries only ErrorCode, with no HTTP status code to match + // on. So the check is made here instead, which leaves the window between the + // check and the put open to a concurrent upload - unlike FileStorageService, + // BlobStorageService and GoogleCloudStorageService, which all decide this + // atomically in the store. + // TODO: make this atomic once the SDK sends "x-oss-forbid-overwrite" and + // surfaces the 409, or once it is confirmed against a live OSS account that + // ObjectMetadata.AddHeader reaches the request unprefixed. + if (_client.DoesObjectExist(_bucket, key)) { - await content.CopyToAsync(seekableContent, DefaultCopyBufferSize, cancellationToken); - - // Storing the same content twice is not a failure, storing different content - // at a taken key is. OSS does signal the latter itself, through the - // "x-oss-forbid-overwrite" request header and a 409 "FileAlreadyExists" - // response, but this SDK exposes neither: ObjectMetadata has no such header - // and OssException carries only ErrorCode, with no HTTP status code to match - // on. So the check is made here instead, which leaves the window between the - // check and the put open to a concurrent upload - unlike FileStorageService, - // BlobStorageService and GoogleCloudStorageService, which all decide this - // atomically in the store. - // TODO: make this atomic once the SDK sends "x-oss-forbid-overwrite" and - // surfaces the 409, or once it is confirmed against a live OSS account that - // ObjectMetadata.AddHeader reaches the request unprefixed. - if (_client.DoesObjectExist(_bucket, key)) + using (var targetStream = await GetAsync(path, cancellationToken)) { - using (var targetStream = await GetAsync(path, cancellationToken)) - { - seekableContent.Seek(0, SeekOrigin.Begin); - - return seekableContent.Matches(targetStream) - ? StoragePutResult.AlreadyExists - : StoragePutResult.Conflict; - } + seekableContent.Seek(0, SeekOrigin.Begin); + + return seekableContent.Matches(targetStream) + ? StoragePutResult.AlreadyExists + : StoragePutResult.Conflict; } + } - seekableContent.Seek(0, SeekOrigin.Begin); + seekableContent.Seek(0, SeekOrigin.Begin); - var metadata = new ObjectMetadata - { - ContentType = contentType, - }; - - // PutObjectResult.HttpStatusCode is not inspected. The branches that used to - // read it ("check sdk documents") mapped 409 to Conflict and 302 to - // AlreadyExists, and neither is reachable: OSS reports a refused put by - // throwing OssException, and PutObjectResult is not documented to carry any - // status that means conflict. - await Task.Factory.FromAsync( - _client.BeginPutObject, _client.EndPutObject, _bucket, key, seekableContent, metadata); - - return StoragePutResult.Success; - } + var metadata = new ObjectMetadata + { + ContentType = contentType, + }; + + // PutObjectResult.HttpStatusCode is not inspected. The branches that used to + // read it ("check sdk documents") mapped 409 to Conflict and 302 to + // AlreadyExists, and neither is reachable: OSS reports a refused put by + // throwing OssException, and PutObjectResult is not documented to carry any + // status that means conflict. + await Task.Factory.FromAsync( + _client.BeginPutObject, _client.EndPutObject, _bucket, key, seekableContent, metadata); + + return StoragePutResult.Success; } + } + + /// + /// Every object under a prefix, paged until OSS says there is no more. The sweep of + /// abandoned staged uploads is the only caller, and without this a bucket would keep + /// them forever. + /// + public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + // A prefix is a path segment, not a string prefix: "staging" must not also match + // "staging-archive/...". + var prefix = PrepareKey(pathPrefix.TrimEnd('/') + Separator); + var paths = new List(); + string marker = null; - /// - /// Every object under a prefix, paged until OSS says there is no more. The sweep of - /// abandoned staged uploads is the only caller, and without this a bucket would keep - /// them forever. - /// - public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + do { - // A prefix is a path segment, not a string prefix: "staging" must not also match - // "staging-archive/...". - var prefix = PrepareKey(pathPrefix.TrimEnd('/') + Separator); - var paths = new List(); - string marker = null; + cancellationToken.ThrowIfCancellationRequested(); - do + // Listed synchronously, as DoesObjectExist above is: this SDK's asynchronous + // surface is the Begin/End pairs, which it does not offer for listing. + var listing = _client.ListObjects(new ListObjectsRequest(_bucket) { - cancellationToken.ThrowIfCancellationRequested(); + Prefix = prefix, + Marker = marker, + }); - // Listed synchronously, as DoesObjectExist above is: this SDK's asynchronous - // surface is the Begin/End pairs, which it does not offer for listing. - var listing = _client.ListObjects(new ListObjectsRequest(_bucket) - { - Prefix = prefix, - Marker = marker, - }); - - foreach (var item in listing.ObjectSummaries) - { - // Reported as the paths IStorageService takes, so the configured bucket - // prefix is removed again. - paths.Add(string.IsNullOrEmpty(_prefix) ? item.Key : item.Key.Substring(_prefix.Length)); - } - - marker = listing.IsTruncated ? listing.NextMarker : null; + foreach (var item in listing.ObjectSummaries) + { + // Reported as the paths IStorageService takes, so the configured bucket + // prefix is removed again. + paths.Add(string.IsNullOrEmpty(_prefix) ? item.Key : item.Key.Substring(_prefix.Length)); } - while (!string.IsNullOrEmpty(marker)); - return Task.FromResult>(paths); + marker = listing.IsTruncated ? listing.NextMarker : null; } + while (!string.IsNullOrEmpty(marker)); - public Task DeleteAsync(string path, CancellationToken cancellationToken = default) - { - _client.DeleteObject(_bucket, PrepareKey(path)); - return Task.CompletedTask; - } + return Task.FromResult>(paths); + } + + public Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + _client.DeleteObject(_bucket, PrepareKey(path)); + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Aws/AwsApplicationExtensions.cs b/src/BaGet.Aws/AwsApplicationExtensions.cs index 6b07f8682..c69e0ce35 100644 --- a/src/BaGet.Aws/AwsApplicationExtensions.cs +++ b/src/BaGet.Aws/AwsApplicationExtensions.cs @@ -9,88 +9,87 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class AwsApplicationExtensions { - public static class AwsApplicationExtensions + public static BaGetApplication AddAwsS3Storage(this BaGetApplication app) { - public static BaGetApplication AddAwsS3Storage(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddProvider((provider, config) => - { - if (!config.HasStorageType("AwsS3")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasStorageType("AwsS3")) return null; + + return provider.GetRequiredService(); + }); - return provider.GetRequiredService(); - }); + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; - app.Services.AddSingleton(provider => + var config = new AmazonS3Config { - var options = provider.GetRequiredService>().Value; - - var config = new AmazonS3Config - { - RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region) - }; - - if (options.UseInstanceProfile) - { - var credentials = FallbackCredentialsFactory.GetCredentials(); - return new AmazonS3Client(credentials, config); - } - - if (!string.IsNullOrEmpty(options.AssumeRoleArn)) - { - var credentials = FallbackCredentialsFactory.GetCredentials(); - var assumedCredentials = AssumeRoleAsync( - credentials, - options.AssumeRoleArn, - $"BaGet-Session-{Guid.NewGuid()}") - .GetAwaiter() - .GetResult(); - - return new AmazonS3Client(assumedCredentials, config); - } - - if (!string.IsNullOrEmpty(options.AccessKey)) - { - return new AmazonS3Client( - new BasicAWSCredentials( - options.AccessKey, - options.SecretKey), - config); - } - - return new AmazonS3Client(config); - }); - - return app; - } + RegionEndpoint = RegionEndpoint.GetBySystemName(options.Region) + }; - public static BaGetApplication AddAwsS3Storage(this BaGetApplication app, Action configure) - { - app.AddAwsS3Storage(); - app.Services.Configure(configure); - return app; - } + if (options.UseInstanceProfile) + { + var credentials = FallbackCredentialsFactory.GetCredentials(); + return new AmazonS3Client(credentials, config); + } - private static async Task AssumeRoleAsync( - AWSCredentials credentials, - string roleArn, - string roleSessionName) - { - var assumedCredentials = new AssumeRoleAWSCredentials(credentials, roleArn, roleSessionName); - var immutableCredentials = await credentials.GetCredentialsAsync(); + if (!string.IsNullOrEmpty(options.AssumeRoleArn)) + { + var credentials = FallbackCredentialsFactory.GetCredentials(); + var assumedCredentials = AssumeRoleAsync( + credentials, + options.AssumeRoleArn, + $"BaGet-Session-{Guid.NewGuid()}") + .GetAwaiter() + .GetResult(); + + return new AmazonS3Client(assumedCredentials, config); + } - if (string.IsNullOrWhiteSpace(immutableCredentials.Token)) + if (!string.IsNullOrEmpty(options.AccessKey)) { - throw new InvalidOperationException($"Unable to assume role {roleArn}"); + return new AmazonS3Client( + new BasicAWSCredentials( + options.AccessKey, + options.SecretKey), + config); } - return assumedCredentials; + return new AmazonS3Client(config); + }); + + return app; + } + + public static BaGetApplication AddAwsS3Storage(this BaGetApplication app, Action configure) + { + app.AddAwsS3Storage(); + app.Services.Configure(configure); + return app; + } + + private static async Task AssumeRoleAsync( + AWSCredentials credentials, + string roleArn, + string roleSessionName) + { + var assumedCredentials = new AssumeRoleAWSCredentials(credentials, roleArn, roleSessionName); + var immutableCredentials = await credentials.GetCredentialsAsync(); + + if (string.IsNullOrWhiteSpace(immutableCredentials.Token)) + { + throw new InvalidOperationException($"Unable to assume role {roleArn}"); } + + return assumedCredentials; } -} +} \ No newline at end of file diff --git a/src/BaGet.Aws/S3StorageOptions.cs b/src/BaGet.Aws/S3StorageOptions.cs index 025340d20..96b16975c 100644 --- a/src/BaGet.Aws/S3StorageOptions.cs +++ b/src/BaGet.Aws/S3StorageOptions.cs @@ -1,26 +1,25 @@ using System.ComponentModel.DataAnnotations; using BaGet.Core; -namespace BaGet.Aws +namespace BaGet.Aws; + +public class S3StorageOptions { - public class S3StorageOptions - { - [RequiredIf(nameof(SecretKey), null, IsInverted = true)] - public string AccessKey { get; set; } + [RequiredIf(nameof(SecretKey), null, IsInverted = true)] + public string AccessKey { get; set; } - [RequiredIf(nameof(AccessKey), null, IsInverted = true)] - public string SecretKey { get; set; } + [RequiredIf(nameof(AccessKey), null, IsInverted = true)] + public string SecretKey { get; set; } - [Required] - public string Region { get; set; } + [Required] + public string Region { get; set; } - [Required] - public string Bucket { get; set; } + [Required] + public string Bucket { get; set; } - public string Prefix { get; set; } + public string Prefix { get; set; } - public bool UseInstanceProfile { get; set; } + public bool UseInstanceProfile { get; set; } - public string AssumeRoleArn { get; set; } - } -} + public string AssumeRoleArn { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Aws/S3StorageService.cs b/src/BaGet.Aws/S3StorageService.cs index 99bc0f8be..784c5fe8e 100644 --- a/src/BaGet.Aws/S3StorageService.cs +++ b/src/BaGet.Aws/S3StorageService.cs @@ -9,168 +9,167 @@ using BaGet.Core; using Microsoft.Extensions.Options; -namespace BaGet.Aws -{ - public class S3StorageService : IStorageService, IListableStorageService - { - private const string Separator = "/"; +namespace BaGet.Aws; - /// - /// The value S3 expects in the If-None-Match header to mean "only if the key - /// is unused". See . - /// - private const string IfKeyIsUnused = "*"; +public class S3StorageService : IStorageService, IListableStorageService +{ + private const string Separator = "/"; - // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 - private const int DefaultCopyBufferSize = 81920; + /// + /// The value S3 expects in the If-None-Match header to mean "only if the key + /// is unused". See . + /// + private const string IfKeyIsUnused = "*"; - private readonly string _bucket; - private readonly string _prefix; - private readonly AmazonS3Client _client; + // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 + private const int DefaultCopyBufferSize = 81920; - public S3StorageService(IOptionsSnapshot options, AmazonS3Client client) - { - if (options == null) - throw new ArgumentNullException(nameof(options)); + private readonly string _bucket; + private readonly string _prefix; + private readonly AmazonS3Client _client; - _bucket = options.Value.Bucket; - _prefix = options.Value.Prefix; - _client = client ?? throw new ArgumentNullException(nameof(client)); + public S3StorageService(IOptionsSnapshot options, AmazonS3Client client) + { + if (options == null) + throw new ArgumentNullException(nameof(options)); - if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Separator)) - _prefix += Separator; - } + _bucket = options.Value.Bucket; + _prefix = options.Value.Prefix; + _client = client ?? throw new ArgumentNullException(nameof(client)); - private string PrepareKey(string path) - { - return _prefix + path.Replace("\\", Separator); - } + if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Separator)) + _prefix += Separator; + } - public async Task GetAsync(string path, CancellationToken cancellationToken = default) - { - var stream = new MemoryStream(); + private string PrepareKey(string path) + { + return _prefix + path.Replace("\\", Separator); + } - try - { - using (var request = await _client.GetObjectAsync(_bucket, PrepareKey(path), cancellationToken)) - { - await request.ResponseStream.CopyToAsync(stream); - } + public async Task GetAsync(string path, CancellationToken cancellationToken = default) + { + var stream = new MemoryStream(); - stream.Seek(0, SeekOrigin.Begin); - } - catch (Exception) + try + { + using (var request = await _client.GetObjectAsync(_bucket, PrepareKey(path), cancellationToken)) { - stream.Dispose(); - - // Unresolved: IStorageService.GetAsync is documented to return null when the - // content is missing, but no implementation does - FileStorageService throws - // FileNotFoundException and callers such as - // SymbolStorageService.GetPortablePdbContentStreamOrNullAsync catch instead of - // null-checking. Mapping S3's NoSuchKey to null here alone would hide missing - // content from PackageStorageService, so the mismatch belongs to the interface - // and is left for a change that fixes every implementation at once. - throw; + await request.ResponseStream.CopyToAsync(stream); } - return stream; + stream.Seek(0, SeekOrigin.Begin); } - - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + catch (Exception) { - var url = _client.GetPreSignedURL(new GetPreSignedUrlRequest - { - BucketName = _bucket, - Key = PrepareKey(path) - }); - - return Task.FromResult(new Uri(url)); + stream.Dispose(); + + // Unresolved: IStorageService.GetAsync is documented to return null when the + // content is missing, but no implementation does - FileStorageService throws + // FileNotFoundException and callers such as + // SymbolStorageService.GetPortablePdbContentStreamOrNullAsync catch instead of + // null-checking. Mapping S3's NoSuchKey to null here alone would hide missing + // content from PackageStorageService, so the mismatch belongs to the interface + // and is left for a change that fixes every implementation at once. + throw; } - public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + return stream; + } + + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + var url = _client.GetPreSignedURL(new GetPreSignedUrlRequest { - if (content == null) throw new ArgumentNullException(nameof(content)); + BucketName = _bucket, + Key = PrepareKey(path) + }); - using (var seekableContent = new MemoryStream()) - { - await content.CopyToAsync(seekableContent, DefaultCopyBufferSize, cancellationToken); + return Task.FromResult(new Uri(url)); + } + + public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + + using (var seekableContent = new MemoryStream()) + { + await content.CopyToAsync(seekableContent, DefaultCopyBufferSize, cancellationToken); - seekableContent.Seek(0, SeekOrigin.Begin); + seekableContent.Seek(0, SeekOrigin.Begin); - try + try + { + await _client.PutObjectAsync(new PutObjectRequest { - await _client.PutObjectAsync(new PutObjectRequest - { - BucketName = _bucket, - Key = PrepareKey(path), - InputStream = seekableContent, - ContentType = contentType, - // Make the upload idempotent: store the content only while the key is - // unused. S3 answers a taken key with "412 Precondition Failed". - IfNoneMatch = IfKeyIsUnused, - AutoResetStreamPosition = false, - AutoCloseStream = false - }, cancellationToken); - - return StoragePutResult.Success; - } - catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.PreconditionFailed) + BucketName = _bucket, + Key = PrepareKey(path), + InputStream = seekableContent, + ContentType = contentType, + // Make the upload idempotent: store the content only while the key is + // unused. S3 answers a taken key with "412 Precondition Failed". + IfNoneMatch = IfKeyIsUnused, + AutoResetStreamPosition = false, + AutoCloseStream = false + }, cancellationToken); + + return StoragePutResult.Success; + } + catch (AmazonS3Exception e) when (e.StatusCode == HttpStatusCode.PreconditionFailed) + { + // The key is taken. Storing the same content twice is not a failure, so + // this is only a conflict when the stored content differs. + using (var targetStream = await GetAsync(path, cancellationToken)) { - // The key is taken. Storing the same content twice is not a failure, so - // this is only a conflict when the stored content differs. - using (var targetStream = await GetAsync(path, cancellationToken)) - { - seekableContent.Seek(0, SeekOrigin.Begin); - - return seekableContent.Matches(targetStream) - ? StoragePutResult.AlreadyExists - : StoragePutResult.Conflict; - } + seekableContent.Seek(0, SeekOrigin.Begin); + + return seekableContent.Matches(targetStream) + ? StoragePutResult.AlreadyExists + : StoragePutResult.Conflict; } } } + } - /// - /// Every key under a prefix, paged until S3 says there is no more. The sweep of - /// abandoned staged uploads is the only caller, and without this a bucket would keep - /// them forever. - /// - public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) - { - // A prefix is a path segment, not a string prefix: "staging" must not also match - // "staging-archive/...". - var prefix = PrepareKey(pathPrefix.TrimEnd('/') + Separator); - var paths = new List(); - string continuation = null; + /// + /// Every key under a prefix, paged until S3 says there is no more. The sweep of + /// abandoned staged uploads is the only caller, and without this a bucket would keep + /// them forever. + /// + public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + // A prefix is a path segment, not a string prefix: "staging" must not also match + // "staging-archive/...". + var prefix = PrepareKey(pathPrefix.TrimEnd('/') + Separator); + var paths = new List(); + string continuation = null; - do - { - var response = await _client.ListObjectsV2Async( - new ListObjectsV2Request - { - BucketName = _bucket, - Prefix = prefix, - ContinuationToken = continuation, - }, - cancellationToken); - - foreach (var item in response.S3Objects) + do + { + var response = await _client.ListObjectsV2Async( + new ListObjectsV2Request { - // Reported as the paths IStorageService takes, so the configured bucket - // prefix is removed again. - paths.Add(string.IsNullOrEmpty(_prefix) ? item.Key : item.Key.Substring(_prefix.Length)); - } + BucketName = _bucket, + Prefix = prefix, + ContinuationToken = continuation, + }, + cancellationToken); - continuation = response.IsTruncated == true ? response.NextContinuationToken : null; + foreach (var item in response.S3Objects) + { + // Reported as the paths IStorageService takes, so the configured bucket + // prefix is removed again. + paths.Add(string.IsNullOrEmpty(_prefix) ? item.Key : item.Key.Substring(_prefix.Length)); } - while (continuation != null); - return paths; + continuation = response.IsTruncated == true ? response.NextContinuationToken : null; } + while (continuation != null); - public async Task DeleteAsync(string path, CancellationToken cancellationToken = default) - { - await _client.DeleteObjectAsync(_bucket, PrepareKey(path), cancellationToken); - } + return paths; + } + + public async Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + await _client.DeleteObjectAsync(_bucket, PrepareKey(path), cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/AzureApplicationExtensions.cs b/src/BaGet.Azure/AzureApplicationExtensions.cs index 150d4f1df..0eb93a100 100644 --- a/src/BaGet.Azure/AzureApplicationExtensions.cs +++ b/src/BaGet.Azure/AzureApplicationExtensions.cs @@ -8,177 +8,176 @@ using Microsoft.Extensions.Options; using Microsoft.Azure.Storage.Blob; -namespace BaGet -{ - using CloudStorageAccount = Microsoft.Azure.Storage.CloudStorageAccount; - using StorageCredentials = Microsoft.Azure.Storage.Auth.StorageCredentials; +namespace BaGet; + +using CloudStorageAccount = Microsoft.Azure.Storage.CloudStorageAccount; +using StorageCredentials = Microsoft.Azure.Storage.Auth.StorageCredentials; - using TableStorageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount; +using TableStorageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount; - public static class AzureApplicationExtensions +public static class AzureApplicationExtensions +{ + public static BaGetApplication AddAzureTableDatabase(this BaGetApplication app) { - public static BaGetApplication AddAzureTableDatabase(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Database)); + app.Services.AddBaGetOptions(nameof(BaGetOptions.Database)); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddSingleton(provider => - { - var options = provider.GetRequiredService>().Value; + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; - return TableStorageAccount.Parse(options.ConnectionString); - }); + return TableStorageAccount.Parse(options.ConnectionString); + }); - app.Services.AddTransient(provider => - { - var account = provider.GetRequiredService(); + app.Services.AddTransient(provider => + { + var account = provider.GetRequiredService(); - return account.CreateCloudTableClient(); - }); + return account.CreateCloudTableClient(); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasDatabaseType("AzureTable")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasDatabaseType("AzureTable")) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasSearchType("Database")) return null; - if (!config.HasDatabaseType("AzureTable")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasSearchType("Database")) return null; + if (!config.HasDatabaseType("AzureTable")) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasSearchType("Database")) return null; - if (!config.HasDatabaseType("AzureTable")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasSearchType("Database")) return null; + if (!config.HasDatabaseType("AzureTable")) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddAzureTableDatabase( - this BaGetApplication app, - Action configure) - { - app.AddAzureTableDatabase(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddAzureTableDatabase( + this BaGetApplication app, + Action configure) + { + app.AddAzureTableDatabase(); + app.Services.Configure(configure); + return app; + } - public static BaGetApplication AddAzureBlobStorage(this BaGetApplication app) + public static BaGetApplication AddAzureBlobStorage(this BaGetApplication app) + { + app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + + app.Services.AddSingleton(provider => { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + var options = provider.GetRequiredService>().Value; - app.Services.AddSingleton(provider => + if (!string.IsNullOrEmpty(options.ConnectionString)) { - var options = provider.GetRequiredService>().Value; - - if (!string.IsNullOrEmpty(options.ConnectionString)) - { - return CloudStorageAccount.Parse(options.ConnectionString); - } + return CloudStorageAccount.Parse(options.ConnectionString); + } - return new CloudStorageAccount( - new StorageCredentials( - options.AccountName, - options.AccessKey), - useHttps: true); - }); + return new CloudStorageAccount( + new StorageCredentials( + options.AccountName, + options.AccessKey), + useHttps: true); + }); - app.Services.AddTransient(provider => - { - var options = provider.GetRequiredService>().Value; - var account = provider.GetRequiredService(); + app.Services.AddTransient(provider => + { + var options = provider.GetRequiredService>().Value; + var account = provider.GetRequiredService(); - var client = account.CreateCloudBlobClient(); + var client = account.CreateCloudBlobClient(); - return client.GetContainerReference(options.Container); - }); + return client.GetContainerReference(options.Container); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasStorageType("AzureBlobStorage")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasStorageType("AzureBlobStorage")) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddAzureBlobStorage( - this BaGetApplication app, - Action configure) - { - app.AddAzureBlobStorage(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddAzureBlobStorage( + this BaGetApplication app, + Action configure) + { + app.AddAzureBlobStorage(); + app.Services.Configure(configure); + return app; + } - public static BaGetApplication AddAzureSearch(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Search)); + public static BaGetApplication AddAzureSearch(this BaGetApplication app) + { + app.Services.AddBaGetOptions(nameof(BaGetOptions.Search)); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.AddTransient(); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddSingleton(provider => - { - var options = provider.GetRequiredService>().Value; - var credentials = new SearchCredentials(options.ApiKey); + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; + var credentials = new SearchCredentials(options.ApiKey); - return new SearchServiceClient(options.AccountName, credentials); - }); + return new SearchServiceClient(options.AccountName, credentials); + }); - app.Services.AddSingleton(provider => - { - var options = provider.GetRequiredService>().Value; - var credentials = new SearchCredentials(options.ApiKey); + app.Services.AddSingleton(provider => + { + var options = provider.GetRequiredService>().Value; + var credentials = new SearchCredentials(options.ApiKey); - return new SearchIndexClient(options.AccountName, PackageDocument.IndexName, credentials); - }); + return new SearchIndexClient(options.AccountName, PackageDocument.IndexName, credentials); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasSearchType("AzureSearch")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasSearchType("AzureSearch")) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - app.Services.AddProvider((provider, config) => - { - if (!config.HasSearchType("AzureSearch")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasSearchType("AzureSearch")) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddAzureSearch( - this BaGetApplication app, - Action configure) - { - app.AddAzureSearch(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddAzureSearch( + this BaGetApplication app, + Action configure) + { + app.AddAzureSearch(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Configuration/AzureBlobStorageOptions.cs b/src/BaGet.Azure/Configuration/AzureBlobStorageOptions.cs index 4b4b9a422..b02f75b51 100644 --- a/src/BaGet.Azure/Configuration/AzureBlobStorageOptions.cs +++ b/src/BaGet.Azure/Configuration/AzureBlobStorageOptions.cs @@ -2,81 +2,80 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// BaGet's configurations to use Azure Blob Storage to store packages. +/// See: https://loic-sharma.github.io/BaGet/quickstart/azure/#azure-blob-storage +/// +public class AzureBlobStorageOptions : IValidatableObject { /// - /// BaGet's configurations to use Azure Blob Storage to store packages. - /// See: https://loic-sharma.github.io/BaGet/quickstart/azure/#azure-blob-storage + /// The Azure Blob Storage connection string. + /// If provided, ignores and . /// - public class AzureBlobStorageOptions : IValidatableObject - { - /// - /// The Azure Blob Storage connection string. - /// If provided, ignores and . - /// - public string ConnectionString { get; set; } + public string ConnectionString { get; set; } - /// - /// The Azure Blob Storage account name. Ignored if is provided. - /// - public string AccountName { get; set; } + /// + /// The Azure Blob Storage account name. Ignored if is provided. + /// + public string AccountName { get; set; } - /// - /// The Azure Blob Storage access key. Ignored if is provided. - /// - public string AccessKey { get; set; } + /// + /// The Azure Blob Storage access key. Ignored if is provided. + /// + public string AccessKey { get; set; } - /// - /// The Azure Blob Storage container name. - /// - public string Container { get; set; } + /// + /// The Azure Blob Storage container name. + /// + public string Container { get; set; } - /// - /// How long the shared access signatures handed out by - /// stay valid. - /// Must be greater than zero. - /// - public TimeSpan DownloadUriExpiry { get; set; } = DefaultDownloadUriExpiry; + /// + /// How long the shared access signatures handed out by + /// stay valid. + /// Must be greater than zero. + /// + public TimeSpan DownloadUriExpiry { get; set; } = DefaultDownloadUriExpiry; + + /// + /// The used when the configuration does not set one. + /// + public static readonly TimeSpan DefaultDownloadUriExpiry = TimeSpan.FromMinutes(10); - /// - /// The used when the configuration does not set one. - /// - public static readonly TimeSpan DefaultDownloadUriExpiry = TimeSpan.FromMinutes(10); + public IEnumerable Validate(ValidationContext validationContext) + { + const string helpUrl = "https://loic-sharma.github.io/BaGet/quickstart/azure/#azure-blob-storage"; - public IEnumerable Validate(ValidationContext validationContext) + if (DownloadUriExpiry <= TimeSpan.Zero) { - const string helpUrl = "https://loic-sharma.github.io/BaGet/quickstart/azure/#azure-blob-storage"; + yield return new ValidationResult( + $"The {nameof(DownloadUriExpiry)} configuration must be greater than zero. See {helpUrl}", + new[] { nameof(DownloadUriExpiry) }); + } - if (DownloadUriExpiry <= TimeSpan.Zero) + if (string.IsNullOrEmpty(ConnectionString)) + { + if (string.IsNullOrEmpty(AccountName)) { yield return new ValidationResult( - $"The {nameof(DownloadUriExpiry)} configuration must be greater than zero. See {helpUrl}", - new[] { nameof(DownloadUriExpiry) }); + $"The {nameof(AccountName)} configuration is required. See {helpUrl}", + new[] { nameof(AccountName) }); } - if (string.IsNullOrEmpty(ConnectionString)) - { - if (string.IsNullOrEmpty(AccountName)) - { - yield return new ValidationResult( - $"The {nameof(AccountName)} configuration is required. See {helpUrl}", - new[] { nameof(AccountName) }); - } - - if (string.IsNullOrEmpty(AccessKey)) - { - yield return new ValidationResult( - $"The {nameof(AccessKey)} configuration is required. See {helpUrl}", - new[] { nameof(AccessKey) }); - } - } - - if (string.IsNullOrEmpty(Container)) + if (string.IsNullOrEmpty(AccessKey)) { yield return new ValidationResult( - $"The {nameof(Container)} configuration is required. See {helpUrl}", - new[] { nameof(Container) }); + $"The {nameof(AccessKey)} configuration is required. See {helpUrl}", + new[] { nameof(AccessKey) }); } } + + if (string.IsNullOrEmpty(Container)) + { + yield return new ValidationResult( + $"The {nameof(Container)} configuration is required. See {helpUrl}", + new[] { nameof(Container) }); + } } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Configuration/AzureSearchOptions.cs b/src/BaGet.Azure/Configuration/AzureSearchOptions.cs index f92c06816..add7ee833 100644 --- a/src/BaGet.Azure/Configuration/AzureSearchOptions.cs +++ b/src/BaGet.Azure/Configuration/AzureSearchOptions.cs @@ -1,13 +1,12 @@ using System.ComponentModel.DataAnnotations; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class AzureSearchOptions { - public class AzureSearchOptions - { - [Required] - public string AccountName { get; set; } + [Required] + public string AccountName { get; set; } - [Required] - public string ApiKey { get; set; } - } -} + [Required] + public string ApiKey { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Azure/Configuration/AzureTableOptions.cs b/src/BaGet.Azure/Configuration/AzureTableOptions.cs index 373eb9b3e..5c96aaffb 100644 --- a/src/BaGet.Azure/Configuration/AzureTableOptions.cs +++ b/src/BaGet.Azure/Configuration/AzureTableOptions.cs @@ -1,10 +1,9 @@ using System.ComponentModel.DataAnnotations; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class AzureTableOptions { - public class AzureTableOptions - { - [Required] - public string ConnectionString { get; set; } - } -} + [Required] + public string ConnectionString { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs b/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs index 8f6a87bf5..1fae8b611 100644 --- a/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs +++ b/src/BaGet.Azure/Extensions/StorageExceptionExtensions.cs @@ -1,30 +1,29 @@ using System.Net; -namespace BaGet.Azure -{ - using StorageException = Microsoft.Azure.Storage.StorageException; - using TableStorageException = Microsoft.Azure.Cosmos.Table.StorageException; +namespace BaGet.Azure; + +using StorageException = Microsoft.Azure.Storage.StorageException; +using TableStorageException = Microsoft.Azure.Cosmos.Table.StorageException; - internal static class StorageExceptionExtensions +internal static class StorageExceptionExtensions +{ + public static bool IsAlreadyExistsException(this StorageException e) { - public static bool IsAlreadyExistsException(this StorageException e) - { - return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.Conflict; - } + return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.Conflict; + } - public static bool IsNotFoundException(this TableStorageException e) - { - return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.NotFound; - } + public static bool IsNotFoundException(this TableStorageException e) + { + return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.NotFound; + } - public static bool IsAlreadyExistsException(this TableStorageException e) - { - return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.Conflict; - } + public static bool IsAlreadyExistsException(this TableStorageException e) + { + return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.Conflict; + } - public static bool IsPreconditionFailedException(this TableStorageException e) - { - return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.PreconditionFailed; - } + public static bool IsPreconditionFailedException(this TableStorageException e) + { + return e?.RequestInformation?.HttpStatusCode == (int?)HttpStatusCode.PreconditionFailed; } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/AzureSearchBatchIndexer.cs b/src/BaGet.Azure/Search/AzureSearchBatchIndexer.cs index 062d67d84..68e4a80ca 100644 --- a/src/BaGet.Azure/Search/AzureSearchBatchIndexer.cs +++ b/src/BaGet.Azure/Search/AzureSearchBatchIndexer.cs @@ -9,80 +9,79 @@ using Microsoft.Extensions.Logging; using Microsoft.Rest.Azure; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class AzureSearchBatchIndexer { - public class AzureSearchBatchIndexer - { - /// - /// Azure Search accepts batches of up to 1000 documents. - /// - public const int MaxBatchSize = 1000; + /// + /// Azure Search accepts batches of up to 1000 documents. + /// + public const int MaxBatchSize = 1000; - private readonly ISearchIndexClient _indexClient; - private readonly ILogger _logger; + private readonly ISearchIndexClient _indexClient; + private readonly ILogger _logger; - public AzureSearchBatchIndexer( - SearchServiceClient searchClient, - ILogger logger) - { - if (searchClient == null) throw new ArgumentNullException(nameof(searchClient)); + public AzureSearchBatchIndexer( + SearchServiceClient searchClient, + ILogger logger) + { + if (searchClient == null) throw new ArgumentNullException(nameof(searchClient)); - _indexClient = searchClient.Indexes.GetClient(PackageDocument.IndexName); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + _indexClient = searchClient.Indexes.GetClient(PackageDocument.IndexName); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task IndexAsync( - IReadOnlyList> batch, - CancellationToken cancellationToken) + public async Task IndexAsync( + IReadOnlyList> batch, + CancellationToken cancellationToken) + { + if (batch.Count > MaxBatchSize) { - if (batch.Count > MaxBatchSize) - { - throw new ArgumentException( - $"Batch cannot have more than {MaxBatchSize} elements", - nameof(batch)); - } + throw new ArgumentException( + $"Batch cannot have more than {MaxBatchSize} elements", + nameof(batch)); + } - IList indexingResults = null; - Exception innerException = null; + IList indexingResults = null; + Exception innerException = null; - try - { - await _indexClient.Documents.IndexAsync( - IndexBatch.New(batch), - cancellationToken: cancellationToken); + try + { + await _indexClient.Documents.IndexAsync( + IndexBatch.New(batch), + cancellationToken: cancellationToken); - _logger.LogInformation("Pushed batch of {DocumentCount} documents", batch.Count); + _logger.LogInformation("Pushed batch of {DocumentCount} documents", batch.Count); - } - catch (IndexBatchException ex) - { - _logger.LogError(ex, "An exception was thrown when pushing batch of documents"); - indexingResults = ex.IndexingResults; - innerException = ex; - } - catch (CloudException ex) when (ex.Response.StatusCode == HttpStatusCode.RequestEntityTooLarge && batch.Count > 1) - { - var halfCount = batch.Count / 2; - var halfA = batch.Take(halfCount).ToList(); - var halfB = batch.Skip(halfCount).ToList(); + } + catch (IndexBatchException ex) + { + _logger.LogError(ex, "An exception was thrown when pushing batch of documents"); + indexingResults = ex.IndexingResults; + innerException = ex; + } + catch (CloudException ex) when (ex.Response.StatusCode == HttpStatusCode.RequestEntityTooLarge && batch.Count > 1) + { + var halfCount = batch.Count / 2; + var halfA = batch.Take(halfCount).ToList(); + var halfB = batch.Skip(halfCount).ToList(); - _logger.LogWarning( - 0, - ex, - "The request body for a batch of {BatchSize} was too large. Splitting into two batches of size " + - "{HalfA} and {HalfB}.", - batch.Count, - halfA.Count, - halfB.Count); + _logger.LogWarning( + 0, + ex, + "The request body for a batch of {BatchSize} was too large. Splitting into two batches of size " + + "{HalfA} and {HalfB}.", + batch.Count, + halfA.Count, + halfB.Count); - await IndexAsync(halfA, cancellationToken); - await IndexAsync(halfB, cancellationToken); - } + await IndexAsync(halfA, cancellationToken); + await IndexAsync(halfB, cancellationToken); + } - if (indexingResults != null && indexingResults.Any(result => !result.Succeeded)) - { - throw new InvalidOperationException("Failed to pushed batch of documents documents"); - } + if (indexingResults != null && indexingResults.Any(result => !result.Succeeded)) + { + throw new InvalidOperationException("Failed to pushed batch of documents documents"); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/AzureSearchIndexer.cs b/src/BaGet.Azure/Search/AzureSearchIndexer.cs index 46be8c95f..185f8782c 100644 --- a/src/BaGet.Azure/Search/AzureSearchIndexer.cs +++ b/src/BaGet.Azure/Search/AzureSearchIndexer.cs @@ -4,37 +4,36 @@ using BaGet.Core; using Microsoft.Extensions.Logging; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class AzureSearchIndexer : ISearchIndexer { - public class AzureSearchIndexer : ISearchIndexer - { - private readonly IPackageDatabase _packages; - private readonly IndexActionBuilder _actionBuilder; - private readonly AzureSearchBatchIndexer _batchIndexer; - private readonly ILogger _logger; + private readonly IPackageDatabase _packages; + private readonly IndexActionBuilder _actionBuilder; + private readonly AzureSearchBatchIndexer _batchIndexer; + private readonly ILogger _logger; - public AzureSearchIndexer( - IPackageDatabase packages, - IndexActionBuilder actionBuilder, - AzureSearchBatchIndexer batchIndexer, - ILogger logger) - { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _actionBuilder = actionBuilder ?? throw new ArgumentNullException(nameof(actionBuilder)); - _batchIndexer = batchIndexer ?? throw new ArgumentNullException(nameof(batchIndexer)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public AzureSearchIndexer( + IPackageDatabase packages, + IndexActionBuilder actionBuilder, + AzureSearchBatchIndexer batchIndexer, + ILogger logger) + { + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _actionBuilder = actionBuilder ?? throw new ArgumentNullException(nameof(actionBuilder)); + _batchIndexer = batchIndexer ?? throw new ArgumentNullException(nameof(batchIndexer)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task IndexAsync(Package package, CancellationToken cancellationToken) - { - var packages = await _packages.FindAsync(package.Id, includeUnlisted: false, cancellationToken); + public async Task IndexAsync(Package package, CancellationToken cancellationToken) + { + var packages = await _packages.FindAsync(package.Id, includeUnlisted: false, cancellationToken); - var actions = _actionBuilder.UpdatePackage( - new PackageRegistration( - package.Id, - packages)); + var actions = _actionBuilder.UpdatePackage( + new PackageRegistration( + package.Id, + packages)); - await _batchIndexer.IndexAsync(actions, cancellationToken); - } + await _batchIndexer.IndexAsync(actions, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/AzureSearchService.cs b/src/BaGet.Azure/Search/AzureSearchService.cs index 16a805e9d..d188445b2 100644 --- a/src/BaGet.Azure/Search/AzureSearchService.cs +++ b/src/BaGet.Azure/Search/AzureSearchService.cs @@ -9,413 +9,412 @@ using Microsoft.Azure.Search; using NuGet.Versioning; -namespace BaGet.Azure -{ - using QueryType = Microsoft.Azure.Search.Models.QueryType; - using SearchParameters = Microsoft.Azure.Search.Models.SearchParameters; +namespace BaGet.Azure; + +using QueryType = Microsoft.Azure.Search.Models.QueryType; +using SearchParameters = Microsoft.Azure.Search.Models.SearchParameters; - public class AzureSearchService : ISearchService +public class AzureSearchService : ISearchService +{ + private readonly SearchIndexClient _searchClient; + private readonly IUrlGenerator _url; + private readonly IFrameworkCompatibilityService _frameworks; + + public AzureSearchService( + SearchIndexClient searchClient, + IUrlGenerator url, + IFrameworkCompatibilityService frameworks) { - private readonly SearchIndexClient _searchClient; - private readonly IUrlGenerator _url; - private readonly IFrameworkCompatibilityService _frameworks; - - public AzureSearchService( - SearchIndexClient searchClient, - IUrlGenerator url, - IFrameworkCompatibilityService frameworks) - { - _searchClient = searchClient ?? throw new ArgumentNullException(nameof(searchClient)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - _frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); - } + _searchClient = searchClient ?? throw new ArgumentNullException(nameof(searchClient)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + _frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); + } - public async Task SearchAsync( - SearchRequest request, - CancellationToken cancellationToken) + public async Task SearchAsync( + SearchRequest request, + CancellationToken cancellationToken) + { + var searchText = BuildSeachQuery(request.Query, request.PackageType, request.Framework); + var filter = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2); + var parameters = new SearchParameters { - var searchText = BuildSeachQuery(request.Query, request.PackageType, request.Framework); - var filter = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2); - var parameters = new SearchParameters - { - IncludeTotalResultCount = true, - QueryType = QueryType.Full, - Skip = request.Skip, - Top = request.Take, - Filter = filter - }; - - var response = await _searchClient.Documents.SearchAsync( - searchText, - parameters, - cancellationToken: cancellationToken); + IncludeTotalResultCount = true, + QueryType = QueryType.Full, + Skip = request.Skip, + Top = request.Take, + Filter = filter + }; - var results = new List(); + var response = await _searchClient.Documents.SearchAsync( + searchText, + parameters, + cancellationToken: cancellationToken); - foreach (var result in response.Results) - { - var document = result.Document; - var versions = new List(); + var results = new List(); - if (document.Versions.Length != document.VersionDownloads.Length) - { - throw new InvalidOperationException($"Invalid document {document.Key} with mismatched versions"); - } - - for (var i = 0; i < document.Versions.Length; i++) - { - var version = NuGetVersion.Parse(document.Versions[i]); + foreach (var result in response.Results) + { + var document = result.Document; + var versions = new List(); - versions.Add(new SearchResultVersion - { - RegistrationLeafUrl = _url.GetRegistrationLeafUrl(document.Id, version), - Version = document.Versions[i], - Downloads = long.Parse(document.VersionDownloads[i]), - }); - } + if (document.Versions.Length != document.VersionDownloads.Length) + { + throw new InvalidOperationException($"Invalid document {document.Key} with mismatched versions"); + } - var iconUrl = document.HasEmbeddedIcon - ? _url.GetPackageIconDownloadUrl(document.Id, NuGetVersion.Parse(document.Version)) - : document.IconUrl; + for (var i = 0; i < document.Versions.Length; i++) + { + var version = NuGetVersion.Parse(document.Versions[i]); - results.Add(new SearchResult + versions.Add(new SearchResultVersion { - PackageId = document.Id, - Version = document.Version, - Description = document.Description, - Authors = document.Authors, - IconUrl = iconUrl, - LicenseUrl = document.LicenseUrl, - ProjectUrl = document.ProjectUrl, - RegistrationIndexUrl = _url.GetRegistrationIndexUrl(document.Id), - Summary = document.Summary, - Tags = document.Tags, - Title = document.Title, - TotalDownloads = document.TotalDownloads, - Versions = versions + RegistrationLeafUrl = _url.GetRegistrationLeafUrl(document.Id, version), + Version = document.Versions[i], + Downloads = long.Parse(document.VersionDownloads[i]), }); } - return new SearchResponse + var iconUrl = document.HasEmbeddedIcon + ? _url.GetPackageIconDownloadUrl(document.Id, NuGetVersion.Parse(document.Version)) + : document.IconUrl; + + results.Add(new SearchResult { - TotalHits = response.Count.Value, - Data = results, - Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl()) - }; + PackageId = document.Id, + Version = document.Version, + Description = document.Description, + Authors = document.Authors, + IconUrl = iconUrl, + LicenseUrl = document.LicenseUrl, + ProjectUrl = document.ProjectUrl, + RegistrationIndexUrl = _url.GetRegistrationIndexUrl(document.Id), + Summary = document.Summary, + Tags = document.Tags, + Title = document.Title, + TotalDownloads = document.TotalDownloads, + Versions = versions + }); } - public async Task AutocompleteAsync( - AutocompleteRequest request, - CancellationToken cancellationToken) + return new SearchResponse { - var parameters = new SearchParameters - { - IncludeTotalResultCount = true, - QueryType = QueryType.Full, - Skip = request.Skip, - Top = request.Take, - - // The index holds one document per package id per search filter, so without this - // the same id is returned up to four times and the total hit count is inflated. - Filter = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2), - }; - - var response = await _searchClient.Documents.SearchAsync( - BuildAutocompleteQuery(request.Query, request.PackageType), - parameters, - cancellationToken: cancellationToken); - - var results = response.Results - .Select(r => r.Document.Id) - .ToList() - .AsReadOnly(); - - return new AutocompleteResponse - { - TotalHits = response.Count.Value, - Data = results, - Context = AutocompleteContext.Default - }; - } + TotalHits = response.Count.Value, + Data = results, + Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl()) + }; + } - public async Task ListPackageVersionsAsync( - VersionsRequest request, - CancellationToken cancellationToken) + public async Task AutocompleteAsync( + AutocompleteRequest request, + CancellationToken cancellationToken) + { + var parameters = new SearchParameters + { + IncludeTotalResultCount = true, + QueryType = QueryType.Full, + Skip = request.Skip, + Top = request.Take, + + // The index holds one document per package id per search filter, so without this + // the same id is returned up to four times and the total hit count is inflated. + Filter = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2), + }; + + var response = await _searchClient.Documents.SearchAsync( + BuildAutocompleteQuery(request.Query, request.PackageType), + parameters, + cancellationToken: cancellationToken); + + var results = response.Results + .Select(r => r.Document.Id) + .ToList() + .AsReadOnly(); + + return new AutocompleteResponse { - var filters = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2); + TotalHits = response.Count.Value, + Data = results, + Context = AutocompleteContext.Default + }; + } - // The exact lookup, for documents that have "normalizedId". - var response = await _searchClient.Documents.SearchAsync( - "*", - new SearchParameters { Top = 1, Filter = BuildVersionsFilter(request.PackageId, filters) }, - cancellationToken: cancellationToken); + public async Task ListPackageVersionsAsync( + VersionsRequest request, + CancellationToken cancellationToken) + { + var filters = BuildSearchFilter(request.IncludePrerelease, request.IncludeSemVer2); - var document = response.Results.Select(r => r.Document).FirstOrDefault(); + // The exact lookup, for documents that have "normalizedId". + var response = await _searchClient.Documents.SearchAsync( + "*", + new SearchParameters { Top = 1, Filter = BuildVersionsFilter(request.PackageId, filters) }, + cancellationToken: cancellationToken); - // A document indexed before "normalizedId" existed: a phrase query on "id" finds - // it among the IDs containing the same words, and the exact match is picked here. - if (document == null) - { - response = await _searchClient.Documents.SearchAsync( - $"id:{EscapeQueryPhrase(request.PackageId)}", - new SearchParameters { QueryType = QueryType.Full, Top = 50, Filter = filters }, - cancellationToken: cancellationToken); - - document = response.Results - .Select(r => r.Document) - .FirstOrDefault(d => string.Equals(d.Id, request.PackageId, StringComparison.OrdinalIgnoreCase)); - } + var document = response.Results.Select(r => r.Document).FirstOrDefault(); - var versions = document?.Versions ?? Array.Empty(); + // A document indexed before "normalizedId" existed: a phrase query on "id" finds + // it among the IDs containing the same words, and the exact match is picked here. + if (document == null) + { + response = await _searchClient.Documents.SearchAsync( + $"id:{EscapeQueryPhrase(request.PackageId)}", + new SearchParameters { QueryType = QueryType.Full, Top = 50, Filter = filters }, + cancellationToken: cancellationToken); - return new AutocompleteResponse - { - TotalHits = versions.Length, - Data = versions, - Context = AutocompleteContext.Default, - }; + document = response.Results + .Select(r => r.Document) + .FirstOrDefault(d => string.Equals(d.Id, request.PackageId, StringComparison.OrdinalIgnoreCase)); } - /// - /// The OData filter for one package ID's document under these search filters. - /// - internal static string BuildVersionsFilter(string packageId, string searchFilter) + var versions = document?.Versions ?? Array.Empty(); + + return new AutocompleteResponse { - if (packageId == null) throw new ArgumentNullException(nameof(packageId)); + TotalHits = versions.Length, + Data = versions, + Context = AutocompleteContext.Default, + }; + } + + /// + /// The OData filter for one package ID's document under these search filters. + /// + internal static string BuildVersionsFilter(string packageId, string searchFilter) + { + if (packageId == null) throw new ArgumentNullException(nameof(packageId)); + + // An OData string literal escapes a quote by doubling it. + var literal = packageId.ToLowerInvariant().Replace("'", "''"); - // An OData string literal escapes a quote by doubling it. - var literal = packageId.ToLowerInvariant().Replace("'", "''"); + return $"normalizedId eq '{literal}' and {searchFilter}"; + } + + /// + /// The full Lucene query for autocomplete: a prefix match on the whole ID, or, for a + /// document indexed before "normalizedId" existed, the analyzed match autocomplete + /// always made; plus the package type, if one was asked for. + /// + internal static string BuildAutocompleteQuery(string query, string packageType) + { + var builder = new StringBuilder(); - return $"normalizedId eq '{literal}' and {searchFilter}"; + var term = EscapeQueryTerm((query ?? string.Empty).Trim().TrimEnd('*').ToLowerInvariant()); + if (term.Length > 0) + { + builder.Append("+(normalizedId:"); + builder.Append(term); + builder.Append("* OR "); + builder.Append(term); + builder.Append(')'); } - /// - /// The full Lucene query for autocomplete: a prefix match on the whole ID, or, for a - /// document indexed before "normalizedId" existed, the analyzed match autocomplete - /// always made; plus the package type, if one was asked for. - /// - internal static string BuildAutocompleteQuery(string query, string packageType) + if (!string.IsNullOrEmpty(packageType)) { - var builder = new StringBuilder(); + builder.Append(" +packageTypes:"); + builder.Append(EscapeQueryPhrase(packageType)); + } - var term = EscapeQueryTerm((query ?? string.Empty).Trim().TrimEnd('*').ToLowerInvariant()); - if (term.Length > 0) - { - builder.Append("+(normalizedId:"); - builder.Append(term); - builder.Append("* OR "); - builder.Append(term); - builder.Append(')'); - } + var result = builder.ToString().Trim(); - if (!string.IsNullOrEmpty(packageType)) - { - builder.Append(" +packageTypes:"); - builder.Append(EscapeQueryPhrase(packageType)); - } + return result.Length == 0 ? "*" : result; + } - var result = builder.ToString().Trim(); + public async Task FindDependentsAsync( + string packageId, + CancellationToken cancellationToken) + { + var query = BuildDependentsQuery(packageId); + var parameters = new SearchParameters + { + IncludeTotalResultCount = true, + QueryType = QueryType.Full, + Skip = 0, + Top = 20, + }; + + var response = await _searchClient.Documents.SearchAsync(query, parameters, cancellationToken: cancellationToken); + var results = response.Results + .Select(r => new PackageDependent + { + Id = r.Document.Id, + Description = r.Document.Description, + TotalDownloads = r.Document.TotalDownloads + }) + .ToList() + .AsReadOnly(); + + return new DependentsResponse + { + TotalHits = response.Count.Value, + Data = results + }; + } - return result.Length == 0 ? "*" : result; + /// + /// Builds the query that finds the packages which depend on . + /// It runs with , the full Lucene query syntax. + /// + internal static string BuildDependentsQuery(string packageId) + { + if (packageId == null) + { + throw new ArgumentNullException(nameof(packageId)); } - public async Task FindDependentsAsync( - string packageId, - CancellationToken cancellationToken) + // "dependencies" is indexed with ExactMatchCustomAnalyzer (a keyword tokenizer plus a + // lowercase filter) and holds lowercased ids, so the whole id must reach the analyzer + // as a single entity. + return $"dependencies:{EscapeQueryPhrase(packageId.ToLowerInvariant())}"; + } + + /// + /// Turns into a quoted phrase, which the full Lucene query parser + /// evaluates as a single literal entity, so that the value cannot change the meaning of the + /// query it is embedded in. + /// + /// + /// In an unquoted term the full Lucene syntax treats + /// + - & | ! ( ) { } [ ] ^ " ~ * ? : \ / as operators, and whitespace splits one + /// term into several - whitespace is not in that list and cannot be escaped, yet it is what + /// lets AND, OR and NOT become operators. Quoting solves both at once: + /// placement decides whether a symbol is an operator, and inside quotation marks every + /// character is content (wildcard, fuzzy, proximity and regex constructs are documented as + /// applying to a term, not to a phrase). That leaves exactly two significant characters, + /// each escaped here with a single backslash, the documented escape: + /// + /// ", which would end the phrase early; + /// \, the escape character itself, which would otherwise swallow + /// the character after it - a trailing one would escape the closing quotation mark. + /// + /// Neither is legal in a NuGet package id, so an ordinary id is emitted verbatim between + /// quotation marks and no backslash ever reaches the parser for a real id. + /// See https://learn.microsoft.com/azure/search/query-lucene-syntax. + /// + /// + /// Escapes the characters that are syntax in the full Lucene query the search runs + /// with, leaving the value usable as a term. Unlike + /// this does not quote, so a caller may still append a trailing "*" to make the term + /// a prefix query. + /// + /// + /// See the escaping rules for the full Lucene syntax: + /// https://learn.microsoft.com/en-us/azure/search/query-lucene-syntax + /// + internal static string EscapeQueryTerm(string value) + { + if (value == null) { - var query = BuildDependentsQuery(packageId); - var parameters = new SearchParameters - { - IncludeTotalResultCount = true, - QueryType = QueryType.Full, - Skip = 0, - Top = 20, - }; - - var response = await _searchClient.Documents.SearchAsync(query, parameters, cancellationToken: cancellationToken); - var results = response.Results - .Select(r => new PackageDependent - { - Id = r.Document.Id, - Description = r.Document.Description, - TotalDownloads = r.Document.TotalDownloads - }) - .ToList() - .AsReadOnly(); - - return new DependentsResponse - { - TotalHits = response.Count.Value, - Data = results - }; + throw new ArgumentNullException(nameof(value)); } - /// - /// Builds the query that finds the packages which depend on . - /// It runs with , the full Lucene query syntax. - /// - internal static string BuildDependentsQuery(string packageId) + const string special = @"+-&|!(){}[]^""~*?:\/"; + var builder = new StringBuilder(value.Length); + + foreach (var character in value) { - if (packageId == null) + if (special.IndexOf(character) >= 0) { - throw new ArgumentNullException(nameof(packageId)); + builder.Append('\\'); } - // "dependencies" is indexed with ExactMatchCustomAnalyzer (a keyword tokenizer plus a - // lowercase filter) and holds lowercased ids, so the whole id must reach the analyzer - // as a single entity. - return $"dependencies:{EscapeQueryPhrase(packageId.ToLowerInvariant())}"; + builder.Append(character); } - /// - /// Turns into a quoted phrase, which the full Lucene query parser - /// evaluates as a single literal entity, so that the value cannot change the meaning of the - /// query it is embedded in. - /// - /// - /// In an unquoted term the full Lucene syntax treats - /// + - & | ! ( ) { } [ ] ^ " ~ * ? : \ / as operators, and whitespace splits one - /// term into several - whitespace is not in that list and cannot be escaped, yet it is what - /// lets AND, OR and NOT become operators. Quoting solves both at once: - /// placement decides whether a symbol is an operator, and inside quotation marks every - /// character is content (wildcard, fuzzy, proximity and regex constructs are documented as - /// applying to a term, not to a phrase). That leaves exactly two significant characters, - /// each escaped here with a single backslash, the documented escape: - /// - /// ", which would end the phrase early; - /// \, the escape character itself, which would otherwise swallow - /// the character after it - a trailing one would escape the closing quotation mark. - /// - /// Neither is legal in a NuGet package id, so an ordinary id is emitted verbatim between - /// quotation marks and no backslash ever reaches the parser for a real id. - /// See https://learn.microsoft.com/azure/search/query-lucene-syntax. - /// - /// - /// Escapes the characters that are syntax in the full Lucene query the search runs - /// with, leaving the value usable as a term. Unlike - /// this does not quote, so a caller may still append a trailing "*" to make the term - /// a prefix query. - /// - /// - /// See the escaping rules for the full Lucene syntax: - /// https://learn.microsoft.com/en-us/azure/search/query-lucene-syntax - /// - internal static string EscapeQueryTerm(string value) - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + return builder.ToString(); + } - const string special = @"+-&|!(){}[]^""~*?:\/"; - var builder = new StringBuilder(value.Length); + internal static string EscapeQueryPhrase(string value) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } - foreach (var character in value) - { - if (special.IndexOf(character) >= 0) - { - builder.Append('\\'); - } + var builder = new StringBuilder(value.Length + 2); - builder.Append(character); - } + builder.Append('"'); - return builder.ToString(); - } - - internal static string EscapeQueryPhrase(string value) + foreach (var character in value) { - if (value == null) + if (character == '"' || character == '\\') { - throw new ArgumentNullException(nameof(value)); + builder.Append('\\'); } - var builder = new StringBuilder(value.Length + 2); + builder.Append(character); + } - builder.Append('"'); + builder.Append('"'); - foreach (var character in value) - { - if (character == '"' || character == '\\') - { - builder.Append('\\'); - } + return builder.ToString(); + } - builder.Append(character); - } + private string BuildSeachQuery(string query, string packageType, string framework) + { + var frameworks = string.IsNullOrEmpty(framework) + ? null + : _frameworks.FindAllCompatibleFrameworks(framework); - builder.Append('"'); + return BuildSearchQuery(query, packageType, frameworks); + } - return builder.ToString(); - } + /// + /// Builds the full Lucene query. Every caller supplied value is escaped: the search + /// runs with , so an unescaped value would change the + /// meaning of the query rather than being matched against. + /// + internal static string BuildSearchQuery( + string query, + string packageType, + IReadOnlyList frameworks) + { + var queryBuilder = new StringBuilder(); - private string BuildSeachQuery(string query, string packageType, string framework) + if (!string.IsNullOrEmpty(query)) { - var frameworks = string.IsNullOrEmpty(framework) - ? null - : _frameworks.FindAllCompatibleFrameworks(framework); - - return BuildSearchQuery(query, packageType, frameworks); + // Escaped as a term, not quoted as a phrase, so the "*" below still makes + // this a prefix query. + queryBuilder.Append(EscapeQueryTerm(query.TrimEnd().TrimEnd('*'))); + queryBuilder.Append('*'); } - /// - /// Builds the full Lucene query. Every caller supplied value is escaped: the search - /// runs with , so an unescaped value would change the - /// meaning of the query rather than being matched against. - /// - internal static string BuildSearchQuery( - string query, - string packageType, - IReadOnlyList frameworks) + if (!string.IsNullOrEmpty(packageType)) { - var queryBuilder = new StringBuilder(); + queryBuilder.Append(" +packageTypes:"); + queryBuilder.Append(EscapeQueryPhrase(packageType)); + } - if (!string.IsNullOrEmpty(query)) - { - // Escaped as a term, not quoted as a phrase, so the "*" below still makes - // this a prefix query. - queryBuilder.Append(EscapeQueryTerm(query.TrimEnd().TrimEnd('*'))); - queryBuilder.Append('*'); - } + if (frameworks != null && frameworks.Count > 0) + { + // An unrecognised moniker is returned as given by FindAllCompatibleFrameworks, + // so these values are caller controlled too. + queryBuilder.Append(" +frameworks:("); + queryBuilder.Append(string.Join(" ", frameworks.Select(EscapeQueryPhrase))); + queryBuilder.Append(')'); + } - if (!string.IsNullOrEmpty(packageType)) - { - queryBuilder.Append(" +packageTypes:"); - queryBuilder.Append(EscapeQueryPhrase(packageType)); - } + return queryBuilder.ToString(); + } - if (frameworks != null && frameworks.Count > 0) - { - // An unrecognised moniker is returned as given by FindAllCompatibleFrameworks, - // so these values are caller controlled too. - queryBuilder.Append(" +frameworks:("); - queryBuilder.Append(string.Join(" ", frameworks.Select(EscapeQueryPhrase))); - queryBuilder.Append(')'); - } + /// + /// Builds the OData filter that selects the single document matching these search filters. + /// writes one document per + /// value, using the same enum name as its "searchFilters" field. + /// + internal static string BuildSearchFilter(bool includePrerelease, bool includeSemVer2) + { + var searchFilters = SearchFilters.Default; - return queryBuilder.ToString(); + if (includePrerelease) + { + searchFilters |= SearchFilters.IncludePrerelease; } - /// - /// Builds the OData filter that selects the single document matching these search filters. - /// writes one document per - /// value, using the same enum name as its "searchFilters" field. - /// - internal static string BuildSearchFilter(bool includePrerelease, bool includeSemVer2) + if (includeSemVer2) { - var searchFilters = SearchFilters.Default; - - if (includePrerelease) - { - searchFilters |= SearchFilters.IncludePrerelease; - } - - if (includeSemVer2) - { - searchFilters |= SearchFilters.IncludeSemVer2; - } - - return $"searchFilters eq '{searchFilters}'"; + searchFilters |= SearchFilters.IncludeSemVer2; } + + return $"searchFilters eq '{searchFilters}'"; } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/ExactMatchCustomAnalyzer.cs b/src/BaGet.Azure/Search/ExactMatchCustomAnalyzer.cs index 962ef04c2..30475e3ee 100644 --- a/src/BaGet.Azure/Search/ExactMatchCustomAnalyzer.cs +++ b/src/BaGet.Azure/Search/ExactMatchCustomAnalyzer.cs @@ -1,21 +1,20 @@ using System.Collections.Generic; using Microsoft.Azure.Search.Models; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// A custom analyzer for case insensitive exact match. +/// +public static class ExactMatchCustomAnalyzer { - /// - /// A custom analyzer for case insensitive exact match. - /// - public static class ExactMatchCustomAnalyzer - { - public const string Name = "baget-exact-match-analyzer"; + public const string Name = "baget-exact-match-analyzer"; - public static CustomAnalyzer Instance = new CustomAnalyzer( - Name, - TokenizerName.Keyword, - new List - { - TokenFilterName.Lowercase - }); - } -} + public static CustomAnalyzer Instance = new CustomAnalyzer( + Name, + TokenizerName.Keyword, + new List + { + TokenFilterName.Lowercase + }); +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/IndexActionBuilder.cs b/src/BaGet.Azure/Search/IndexActionBuilder.cs index b9897f789..fd1505a03 100644 --- a/src/BaGet.Azure/Search/IndexActionBuilder.cs +++ b/src/BaGet.Azure/Search/IndexActionBuilder.cs @@ -5,115 +5,114 @@ using BaGet.Core; using Microsoft.Azure.Search.Models; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class IndexActionBuilder { - public class IndexActionBuilder + public virtual IReadOnlyList> AddPackage( + PackageRegistration registration) { - public virtual IReadOnlyList> AddPackage( - PackageRegistration registration) - { - return AddOrUpdatePackage(registration, isUpdate: false); - } + return AddOrUpdatePackage(registration, isUpdate: false); + } - public virtual IReadOnlyList> UpdatePackage( - PackageRegistration registration) - { - return AddOrUpdatePackage(registration, isUpdate: true); - } + public virtual IReadOnlyList> UpdatePackage( + PackageRegistration registration) + { + return AddOrUpdatePackage(registration, isUpdate: true); + } + + private IReadOnlyList> AddOrUpdatePackage( + PackageRegistration registration, + bool isUpdate) + { + var encodedId = EncodePackageId(registration.PackageId.ToLowerInvariant()); + var result = new List>(); - private IReadOnlyList> AddOrUpdatePackage( - PackageRegistration registration, - bool isUpdate) + for (var i = 0; i < 4; i++) { - var encodedId = EncodePackageId(registration.PackageId.ToLowerInvariant()); - var result = new List>(); + var includePrerelease = (i & 1) != 0; + var includeSemVer2 = (i & 2) != 0; + var searchFilters = (SearchFilters)i; - for (var i = 0; i < 4; i++) - { - var includePrerelease = (i & 1) != 0; - var includeSemVer2 = (i & 2) != 0; - var searchFilters = (SearchFilters)i; + var documentKey = $"{encodedId}-{searchFilters}"; + var filtered = registration.Packages.Where(p => p.Listed); - var documentKey = $"{encodedId}-{searchFilters}"; - var filtered = registration.Packages.Where(p => p.Listed); + if (!includePrerelease) + { + filtered = filtered.Where(p => !p.IsPrerelease); + } - if (!includePrerelease) - { - filtered = filtered.Where(p => !p.IsPrerelease); - } + if (!includeSemVer2) + { + filtered = filtered.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); + } - if (!includeSemVer2) + var versions = filtered.OrderBy(p => p.Version).ToList(); + if (versions.Count == 0) + { + if (isUpdate) { - filtered = filtered.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); - } + var action = IndexAction.Delete( + new KeyedDocument + { + Key = documentKey + }); - var versions = filtered.OrderBy(p => p.Version).ToList(); - if (versions.Count == 0) - { - if (isUpdate) - { - var action = IndexAction.Delete( - new KeyedDocument - { - Key = documentKey - }); - - result.Add(action); - } - - continue; + result.Add(action); } - var latest = versions.Last(); - var dependencies = latest - .Dependencies - .Select(d => d.Id?.ToLowerInvariant()) - .Where(d => d != null) - .Distinct() - .ToArray(); - - var document = new PackageDocument(); - - document.Key = $"{encodedId}-{searchFilters}"; - document.Id = latest.Id; - document.NormalizedId = latest.Id.ToLowerInvariant(); - document.Version = latest.Version.ToFullString(); - document.Description = latest.Description; - document.Authors = latest.Authors; - document.HasEmbeddedIcon = latest.HasEmbeddedIcon; - document.IconUrl = latest.IconUrlString; - document.LicenseUrl = latest.LicenseUrlString; - document.ProjectUrl = latest.ProjectUrlString; - document.Published = latest.Published; - document.Summary = latest.Summary; - document.Tags = latest.Tags; - document.Title = latest.Title; - document.TotalDownloads = versions.Sum(p => p.Downloads); - document.DownloadsMagnitude = document.TotalDownloads.ToString().Length; - document.Versions = versions.Select(p => p.Version.ToFullString()).ToArray(); - document.VersionDownloads = versions.Select(p => p.Downloads.ToString()).ToArray(); - document.Dependencies = dependencies; - document.PackageTypes = latest.PackageTypes.Select(t => t.Name).ToArray(); - document.Frameworks = latest.TargetFrameworks.Select(f => f.Moniker.ToLowerInvariant()).ToArray(); - document.SearchFilters = searchFilters.ToString(); - - result.Add( - isUpdate - ? IndexAction.MergeOrUpload(document) - : IndexAction.Upload(document)); + continue; } - return result; + var latest = versions.Last(); + var dependencies = latest + .Dependencies + .Select(d => d.Id?.ToLowerInvariant()) + .Where(d => d != null) + .Distinct() + .ToArray(); + + var document = new PackageDocument(); + + document.Key = $"{encodedId}-{searchFilters}"; + document.Id = latest.Id; + document.NormalizedId = latest.Id.ToLowerInvariant(); + document.Version = latest.Version.ToFullString(); + document.Description = latest.Description; + document.Authors = latest.Authors; + document.HasEmbeddedIcon = latest.HasEmbeddedIcon; + document.IconUrl = latest.IconUrlString; + document.LicenseUrl = latest.LicenseUrlString; + document.ProjectUrl = latest.ProjectUrlString; + document.Published = latest.Published; + document.Summary = latest.Summary; + document.Tags = latest.Tags; + document.Title = latest.Title; + document.TotalDownloads = versions.Sum(p => p.Downloads); + document.DownloadsMagnitude = document.TotalDownloads.ToString().Length; + document.Versions = versions.Select(p => p.Version.ToFullString()).ToArray(); + document.VersionDownloads = versions.Select(p => p.Downloads.ToString()).ToArray(); + document.Dependencies = dependencies; + document.PackageTypes = latest.PackageTypes.Select(t => t.Name).ToArray(); + document.Frameworks = latest.TargetFrameworks.Select(f => f.Moniker.ToLowerInvariant()).ToArray(); + document.SearchFilters = searchFilters.ToString(); + + result.Add( + isUpdate + ? IndexAction.MergeOrUpload(document) + : IndexAction.Upload(document)); } - private string EncodePackageId(string key) - { - // Keys can only contain letters, digits, underscore(_), dash(-), or equal sign(=). - // TODO: Align with NuGet.org's algorithm. - var bytes = Encoding.UTF8.GetBytes(key); - var base64 = Convert.ToBase64String(bytes); + return result; + } - return base64.Replace('+', '-').Replace('/', '_'); - } + private string EncodePackageId(string key) + { + // Keys can only contain letters, digits, underscore(_), dash(-), or equal sign(=). + // TODO: Align with NuGet.org's algorithm. + var bytes = Encoding.UTF8.GetBytes(key); + var base64 = Convert.ToBase64String(bytes); + + return base64.Replace('+', '-').Replace('/', '_'); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/PackageDocument.cs b/src/BaGet.Azure/Search/PackageDocument.cs index 2d6da69ad..e91e86f9f 100644 --- a/src/BaGet.Azure/Search/PackageDocument.cs +++ b/src/BaGet.Azure/Search/PackageDocument.cs @@ -3,88 +3,87 @@ using Microsoft.Azure.Search; using Microsoft.Azure.Search.Models; -namespace BaGet.Azure +namespace BaGet.Azure; + +// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages +[SerializePropertyNamesAsCamelCase] +public class PackageDocument : KeyedDocument +{ + public const string IndexName = "packages"; + + [IsSearchable, IsFilterable, IsSortable] + public string Id { get; set; } + + /// + /// The lowercased ID as a single token, for exact lookups and prefix matches; "id" + /// is split on "." and "-" by the default analyzer. An index created before this + /// field existed needs it added, and a document only has it once its package is + /// pushed again, so every query that uses it falls back for documents without it. + /// + [IsSearchable, IsFilterable] + [Analyzer(ExactMatchCustomAnalyzer.Name)] + public string NormalizedId { get; set; } + + /// + /// The package's full versions after normalization, including any SemVer 2.0.0 build metadata. + /// + [IsSearchable, IsFilterable, IsSortable] + public string Version { get; set; } + + [IsSearchable] + public string Description { get; set; } + public string[] Authors { get; set; } + public bool HasEmbeddedIcon { get; set; } + public string IconUrl { get; set; } + public string LicenseUrl { get; set; } + public string ProjectUrl { get; set; } + public DateTimeOffset Published { get; set; } + + [IsSearchable] + public string Summary { get; set; } + + [IsSearchable, IsFilterable, IsFacetable] + public string[] Tags { get; set; } + + [IsSearchable] + public string Title { get; set; } + + [IsFilterable, IsSortable] + public long TotalDownloads { get; set; } + + [IsFilterable, IsSortable] + public int DownloadsMagnitude { get; set; } + + /// + /// The package's full versions after normalization, including any SemVer 2.0.0 build metadata. + /// + public string[] Versions { get; set; } + public string[] VersionDownloads { get; set; } + + [IsSearchable] + [Analyzer(ExactMatchCustomAnalyzer.Name)] + public string[] Dependencies { get; set; } + + [IsSearchable] + [Analyzer(ExactMatchCustomAnalyzer.Name)] + public string[] PackageTypes { get; set; } + + [IsSearchable] + [Analyzer(ExactMatchCustomAnalyzer.Name)] + public string[] Frameworks { get; set; } + + [IsFilterable] + public string SearchFilters { get; set; } +} + +[SerializePropertyNamesAsCamelCase] +public class KeyedDocument : IKeyedDocument { - // See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages - [SerializePropertyNamesAsCamelCase] - public class PackageDocument : KeyedDocument - { - public const string IndexName = "packages"; - - [IsSearchable, IsFilterable, IsSortable] - public string Id { get; set; } - - /// - /// The lowercased ID as a single token, for exact lookups and prefix matches; "id" - /// is split on "." and "-" by the default analyzer. An index created before this - /// field existed needs it added, and a document only has it once its package is - /// pushed again, so every query that uses it falls back for documents without it. - /// - [IsSearchable, IsFilterable] - [Analyzer(ExactMatchCustomAnalyzer.Name)] - public string NormalizedId { get; set; } - - /// - /// The package's full versions after normalization, including any SemVer 2.0.0 build metadata. - /// - [IsSearchable, IsFilterable, IsSortable] - public string Version { get; set; } - - [IsSearchable] - public string Description { get; set; } - public string[] Authors { get; set; } - public bool HasEmbeddedIcon { get; set; } - public string IconUrl { get; set; } - public string LicenseUrl { get; set; } - public string ProjectUrl { get; set; } - public DateTimeOffset Published { get; set; } - - [IsSearchable] - public string Summary { get; set; } - - [IsSearchable, IsFilterable, IsFacetable] - public string[] Tags { get; set; } - - [IsSearchable] - public string Title { get; set; } - - [IsFilterable, IsSortable] - public long TotalDownloads { get; set; } - - [IsFilterable, IsSortable] - public int DownloadsMagnitude { get; set; } - - /// - /// The package's full versions after normalization, including any SemVer 2.0.0 build metadata. - /// - public string[] Versions { get; set; } - public string[] VersionDownloads { get; set; } - - [IsSearchable] - [Analyzer(ExactMatchCustomAnalyzer.Name)] - public string[] Dependencies { get; set; } - - [IsSearchable] - [Analyzer(ExactMatchCustomAnalyzer.Name)] - public string[] PackageTypes { get; set; } - - [IsSearchable] - [Analyzer(ExactMatchCustomAnalyzer.Name)] - public string[] Frameworks { get; set; } - - [IsFilterable] - public string SearchFilters { get; set; } - } - - [SerializePropertyNamesAsCamelCase] - public class KeyedDocument : IKeyedDocument - { - [Key] - public string Key { get; set; } - } - - public interface IKeyedDocument - { - string Key { get; set; } - } + [Key] + public string Key { get; set; } } + +public interface IKeyedDocument +{ + string Key { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Azure/Search/SearchFilters.cs b/src/BaGet.Azure/Search/SearchFilters.cs index 9e3e90b52..1a4a2d003 100644 --- a/src/BaGet.Azure/Search/SearchFilters.cs +++ b/src/BaGet.Azure/Search/SearchFilters.cs @@ -1,31 +1,30 @@ using System; -namespace BaGet.Azure +namespace BaGet.Azure; + +// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/d3e6b7a3aa8ec9cb8b32bf860f2d4f0d6766ed92/src/NuGet.Services.AzureSearch/VersionList/SearchFilters.cs#L9 +[Flags] +public enum SearchFilters { - // Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/d3e6b7a3aa8ec9cb8b32bf860f2d4f0d6766ed92/src/NuGet.Services.AzureSearch/VersionList/SearchFilters.cs#L9 - [Flags] - public enum SearchFilters - { - /// - /// Exclude SemVer 2.0.0 and prerelease packages. - /// - Default = 0, + /// + /// Exclude SemVer 2.0.0 and prerelease packages. + /// + Default = 0, - /// - /// Include packages that have prerelease versions. Note that a package's dependency version ranges do not - /// affect the prerelease status of the package. This is in contrast of . - /// - IncludePrerelease = 1 << 0, + /// + /// Include packages that have prerelease versions. Note that a package's dependency version ranges do not + /// affect the prerelease status of the package. This is in contrast of . + /// + IncludePrerelease = 1 << 0, - /// - /// Include SemVer 2.0.0 packages. Note that SemVer 2.0.0 dependency version ranges make a package into a SemVer - /// 2.0.0 even if the package's own version string is SemVer 1.0.0. - /// - IncludeSemVer2 = 1 << 1, + /// + /// Include SemVer 2.0.0 packages. Note that SemVer 2.0.0 dependency version ranges make a package into a SemVer + /// 2.0.0 even if the package's own version string is SemVer 1.0.0. + /// + IncludeSemVer2 = 1 << 1, - /// - /// Include package that have prerelease versions and include SemVer 2.0.0 packages. - /// - IncludePrereleaseAndSemVer2 = IncludePrerelease | IncludeSemVer2, - } -} + /// + /// Include package that have prerelease versions and include SemVer 2.0.0 packages. + /// + IncludePrereleaseAndSemVer2 = IncludePrerelease | IncludeSemVer2, +} \ No newline at end of file diff --git a/src/BaGet.Azure/Storage/BlobStorageService.cs b/src/BaGet.Azure/Storage/BlobStorageService.cs index 498537b25..119505654 100644 --- a/src/BaGet.Azure/Storage/BlobStorageService.cs +++ b/src/BaGet.Azure/Storage/BlobStorageService.cs @@ -8,129 +8,128 @@ using Microsoft.Azure.Storage.Blob; using Microsoft.Extensions.Options; -namespace BaGet.Azure -{ - // See: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Services/CloudBlobCoreFileStorageService.cs - public class BlobStorageService : IStorageService, IListableStorageService - { - private readonly CloudBlobContainer _container; - private readonly TimeSpan _downloadUriExpiry; +namespace BaGet.Azure; - public BlobStorageService(IOptionsSnapshot options, CloudBlobContainer container) - { - if (options == null) throw new ArgumentNullException(nameof(options)); +// See: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Services/CloudBlobCoreFileStorageService.cs +public class BlobStorageService : IStorageService, IListableStorageService +{ + private readonly CloudBlobContainer _container; + private readonly TimeSpan _downloadUriExpiry; - _container = container ?? throw new ArgumentNullException(nameof(container)); - _downloadUriExpiry = options.Value.DownloadUriExpiry; + public BlobStorageService(IOptionsSnapshot options, CloudBlobContainer container) + { + if (options == null) throw new ArgumentNullException(nameof(options)); - if (_downloadUriExpiry <= TimeSpan.Zero) - { - throw new ArgumentException( - $"The {nameof(AzureBlobStorageOptions.DownloadUriExpiry)} option must be greater than zero", - nameof(options)); - } - } + _container = container ?? throw new ArgumentNullException(nameof(container)); + _downloadUriExpiry = options.Value.DownloadUriExpiry; - public async Task GetAsync(string path, CancellationToken cancellationToken) + if (_downloadUriExpiry <= TimeSpan.Zero) { - return await _container - .GetBlockBlobReference(path) - .OpenReadAsync(cancellationToken); + throw new ArgumentException( + $"The {nameof(AzureBlobStorageOptions.DownloadUriExpiry)} option must be greater than zero", + nameof(options)); } + } + + public async Task GetAsync(string path, CancellationToken cancellationToken) + { + return await _container + .GetBlockBlobReference(path) + .OpenReadAsync(cancellationToken); + } - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken) + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken) + { + var blob = _container.GetBlockBlobReference(path); + var accessPolicy = new SharedAccessBlobPolicy { - var blob = _container.GetBlockBlobReference(path); - var accessPolicy = new SharedAccessBlobPolicy - { - SharedAccessExpiryTime = DateTimeOffset.UtcNow.Add(_downloadUriExpiry), - Permissions = SharedAccessBlobPermissions.Read - }; + SharedAccessExpiryTime = DateTimeOffset.UtcNow.Add(_downloadUriExpiry), + Permissions = SharedAccessBlobPermissions.Read + }; - var signature = blob.GetSharedAccessSignature(accessPolicy); - var result = new Uri(blob.Uri, signature); + var signature = blob.GetSharedAccessSignature(accessPolicy); + var result = new Uri(blob.Uri, signature); - return Task.FromResult(result); - } + return Task.FromResult(result); + } - public async Task PutAsync( - string path, - Stream content, - string contentType, - CancellationToken cancellationToken) - { - var blob = _container.GetBlockBlobReference(path); - var condition = AccessCondition.GenerateIfNotExistsCondition(); + public async Task PutAsync( + string path, + Stream content, + string contentType, + CancellationToken cancellationToken) + { + var blob = _container.GetBlockBlobReference(path); + var condition = AccessCondition.GenerateIfNotExistsCondition(); - blob.Properties.ContentType = contentType; + blob.Properties.ContentType = contentType; - try - { - await blob.UploadFromStreamAsync( - content, - condition, - options: null, - operationContext: null, - cancellationToken: cancellationToken); - - return StoragePutResult.Success; - } - catch (StorageException e) when (e.IsAlreadyExistsException()) + try + { + await blob.UploadFromStreamAsync( + content, + condition, + options: null, + operationContext: null, + cancellationToken: cancellationToken); + + return StoragePutResult.Success; + } + catch (StorageException e) when (e.IsAlreadyExistsException()) + { + using (var targetStream = await blob.OpenReadAsync(cancellationToken)) { - using (var targetStream = await blob.OpenReadAsync(cancellationToken)) - { - content.Position = 0; - return content.Matches(targetStream) - ? StoragePutResult.AlreadyExists - : StoragePutResult.Conflict; - } + content.Position = 0; + return content.Matches(targetStream) + ? StoragePutResult.AlreadyExists + : StoragePutResult.Conflict; } } + } - /// - /// Every blob under a prefix, paged until the container says there is no more. The - /// sweep of abandoned staged uploads is the only caller, and without this a container - /// would keep them forever. - /// - public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) - { - // A prefix is a path segment, not a string prefix: "staging" must not also match - // a "staging-archive" container entry. - var prefix = pathPrefix.TrimEnd('/') + "/"; - var paths = new List(); - BlobContinuationToken continuation = null; + /// + /// Every blob under a prefix, paged until the container says there is no more. The + /// sweep of abandoned staged uploads is the only caller, and without this a container + /// would keep them forever. + /// + public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + // A prefix is a path segment, not a string prefix: "staging" must not also match + // a "staging-archive" container entry. + var prefix = pathPrefix.TrimEnd('/') + "/"; + var paths = new List(); + BlobContinuationToken continuation = null; - do + do + { + var segment = await _container.ListBlobsSegmentedAsync( + prefix, + useFlatBlobListing: true, + blobListingDetails: BlobListingDetails.None, + maxResults: null, + currentToken: continuation, + options: null, + operationContext: null, + cancellationToken: cancellationToken); + + foreach (var item in segment.Results) { - var segment = await _container.ListBlobsSegmentedAsync( - prefix, - useFlatBlobListing: true, - blobListingDetails: BlobListingDetails.None, - maxResults: null, - currentToken: continuation, - options: null, - operationContext: null, - cancellationToken: cancellationToken); - - foreach (var item in segment.Results) - { - // The blob's name is already the path IStorageService takes, relative to - // the container. - if (item is CloudBlob blob) paths.Add(blob.Name); - } - - continuation = segment.ContinuationToken; + // The blob's name is already the path IStorageService takes, relative to + // the container. + if (item is CloudBlob blob) paths.Add(blob.Name); } - while (continuation != null); - return paths; + continuation = segment.ContinuationToken; } + while (continuation != null); - public async Task DeleteAsync(string path, CancellationToken cancellationToken) - { - await _container - .GetBlockBlobReference(path) - .DeleteIfExistsAsync(cancellationToken); - } + return paths; + } + + public async Task DeleteAsync(string path, CancellationToken cancellationToken) + { + await _container + .GetBlockBlobReference(path) + .DeleteIfExistsAsync(cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/PackageEntity.cs b/src/BaGet.Azure/Table/PackageEntity.cs index 46e9a053d..c94d395f1 100644 --- a/src/BaGet.Azure/Table/PackageEntity.cs +++ b/src/BaGet.Azure/Table/PackageEntity.cs @@ -2,105 +2,104 @@ using BaGet.Core; using Microsoft.Azure.Cosmos.Table; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// The Azure Table Storage entity that maps to a . +/// The is the and +/// the is the . +/// +public class PackageEntity : TableEntity, IDownloadCount, IListed { - /// - /// The Azure Table Storage entity that maps to a . - /// The is the and - /// the is the . - /// - public class PackageEntity : TableEntity, IDownloadCount, IListed + public PackageEntity() { - public PackageEntity() - { - } + } - public string Id { get; set; } - public string NormalizedVersion { get; set; } - public string OriginalVersion { get; set; } - public string Authors { get; set; } - public string Description { get; set; } - public long Downloads { get; set; } - public bool HasReadme { get; set; } - public bool HasEmbeddedIcon { get; set; } - public bool IsPrerelease { get; set; } - public string Language { get; set; } - public bool Listed { get; set; } - public string MinClientVersion { get; set; } - public DateTime Published { get; set; } - public bool RequireLicenseAcceptance { get; set; } - public int SemVerLevel { get; set; } - public string ReleaseNotes { get; set; } - public string Summary { get; set; } - public string Title { get; set; } + public string Id { get; set; } + public string NormalizedVersion { get; set; } + public string OriginalVersion { get; set; } + public string Authors { get; set; } + public string Description { get; set; } + public long Downloads { get; set; } + public bool HasReadme { get; set; } + public bool HasEmbeddedIcon { get; set; } + public bool IsPrerelease { get; set; } + public string Language { get; set; } + public bool Listed { get; set; } + public string MinClientVersion { get; set; } + public DateTime Published { get; set; } + public bool RequireLicenseAcceptance { get; set; } + public int SemVerLevel { get; set; } + public string ReleaseNotes { get; set; } + public string Summary { get; set; } + public string Title { get; set; } - public string IconUrl { get; set; } - public string LicenseUrl { get; set; } - public string ProjectUrl { get; set; } + public string IconUrl { get; set; } + public string LicenseUrl { get; set; } + public string ProjectUrl { get; set; } - public string RepositoryUrl { get; set; } - public string RepositoryType { get; set; } + public string RepositoryUrl { get; set; } + public string RepositoryType { get; set; } - public string Tags { get; set; } - public string Dependencies { get; set; } - public string PackageTypes { get; set; } - public string TargetFrameworks { get; set; } - } + public string Tags { get; set; } + public string Dependencies { get; set; } + public string PackageTypes { get; set; } + public string TargetFrameworks { get; set; } +} - /// - /// A single item in . - /// - public class DependencyModel - { - public string Id { get; set; } - public string VersionRange { get; set; } - public string TargetFramework { get; set; } - } +/// +/// A single item in . +/// +public class DependencyModel +{ + public string Id { get; set; } + public string VersionRange { get; set; } + public string TargetFramework { get; set; } +} - /// - /// A single item in . - /// - public class PackageTypeModel - { - public string Name { get; set; } - public string Version { get; set; } - } +/// +/// A single item in . +/// +public class PackageTypeModel +{ + public string Name { get; set; } + public string Version { get; set; } +} - /// - /// The Azure Table Storage entity to update the column. - /// The is the and - /// the is the . - /// - public class PackageListingEntity : TableEntity, IListed +/// +/// The Azure Table Storage entity to update the column. +/// The is the and +/// the is the . +/// +public class PackageListingEntity : TableEntity, IListed +{ + public PackageListingEntity() { - public PackageListingEntity() - { - } - - public bool Listed { get; set; } } - /// - /// The Azure Table Storage entity to update the column. - /// The is the and - /// the is the . - /// - public class PackageDownloadsEntity : TableEntity, IDownloadCount - { - public PackageDownloadsEntity() - { - } - - public long Downloads { get; set; } - } + public bool Listed { get; set; } +} - internal interface IListed +/// +/// The Azure Table Storage entity to update the column. +/// The is the and +/// the is the . +/// +public class PackageDownloadsEntity : TableEntity, IDownloadCount +{ + public PackageDownloadsEntity() { - bool Listed { get; set; } } - public interface IDownloadCount - { - long Downloads { get; set; } - } + public long Downloads { get; set; } +} + +internal interface IListed +{ + bool Listed { get; set; } } + +public interface IDownloadCount +{ + long Downloads { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/PackageEntityExtensions.cs b/src/BaGet.Azure/Table/PackageEntityExtensions.cs index fb2da07d0..f26d665d6 100644 --- a/src/BaGet.Azure/Table/PackageEntityExtensions.cs +++ b/src/BaGet.Azure/Table/PackageEntityExtensions.cs @@ -3,78 +3,77 @@ using System.Linq; using BaGet.Core; -namespace BaGet.Azure +namespace BaGet.Azure; + +public static class PackageEntityExtensions { - public static class PackageEntityExtensions + public static Package AsPackage(this PackageEntity entity) { - public static Package AsPackage(this PackageEntity entity) + return new Package { - return new Package - { - Id = entity.Id, - NormalizedVersionString = entity.NormalizedVersion, - OriginalVersionString = entity.OriginalVersion, + Id = entity.Id, + NormalizedVersionString = entity.NormalizedVersion, + OriginalVersionString = entity.OriginalVersion, - Authors = TableJson.Deserialize(entity.Authors), - Description = entity.Description, - Downloads = entity.Downloads, - HasReadme = entity.HasReadme, - HasEmbeddedIcon = entity.HasEmbeddedIcon, - IsPrerelease = entity.IsPrerelease, - Language = entity.Language, - Listed = entity.Listed, - MinClientVersion = entity.MinClientVersion, - Published = entity.Published, - RequireLicenseAcceptance = entity.RequireLicenseAcceptance, - SemVerLevel = (SemVerLevel)entity.SemVerLevel, - Summary = entity.Summary, - Title = entity.Title, - ReleaseNotes = entity.ReleaseNotes, - IconUrl = ParseUri(entity.IconUrl), - LicenseUrl = ParseUri(entity.LicenseUrl), - ProjectUrl = ParseUri(entity.ProjectUrl), - RepositoryUrl = ParseUri(entity.RepositoryUrl), - RepositoryType = entity.RepositoryType, - Tags = TableJson.Deserialize(entity.Tags), - Dependencies = ParseDependencies(entity.Dependencies), - PackageTypes = ParsePackageTypes(entity.PackageTypes), - TargetFrameworks = ParseTargetFrameworks(entity.TargetFrameworks), - }; - } + Authors = TableJson.Deserialize(entity.Authors), + Description = entity.Description, + Downloads = entity.Downloads, + HasReadme = entity.HasReadme, + HasEmbeddedIcon = entity.HasEmbeddedIcon, + IsPrerelease = entity.IsPrerelease, + Language = entity.Language, + Listed = entity.Listed, + MinClientVersion = entity.MinClientVersion, + Published = entity.Published, + RequireLicenseAcceptance = entity.RequireLicenseAcceptance, + SemVerLevel = (SemVerLevel)entity.SemVerLevel, + Summary = entity.Summary, + Title = entity.Title, + ReleaseNotes = entity.ReleaseNotes, + IconUrl = ParseUri(entity.IconUrl), + LicenseUrl = ParseUri(entity.LicenseUrl), + ProjectUrl = ParseUri(entity.ProjectUrl), + RepositoryUrl = ParseUri(entity.RepositoryUrl), + RepositoryType = entity.RepositoryType, + Tags = TableJson.Deserialize(entity.Tags), + Dependencies = ParseDependencies(entity.Dependencies), + PackageTypes = ParsePackageTypes(entity.PackageTypes), + TargetFrameworks = ParseTargetFrameworks(entity.TargetFrameworks), + }; + } - private static Uri ParseUri(string input) - { - return string.IsNullOrEmpty(input) ? null : new Uri(input); - } + private static Uri ParseUri(string input) + { + return string.IsNullOrEmpty(input) ? null : new Uri(input); + } - private static List ParseDependencies(string input) - { - return TableJson.Deserialize>(input) - .Select(e => new PackageDependency - { - Id = e.Id, - VersionRange = e.VersionRange, - TargetFramework = e.TargetFramework, - }) - .ToList(); - } + private static List ParseDependencies(string input) + { + return TableJson.Deserialize>(input) + .Select(e => new PackageDependency + { + Id = e.Id, + VersionRange = e.VersionRange, + TargetFramework = e.TargetFramework, + }) + .ToList(); + } - private static List ParsePackageTypes(string input) - { - return TableJson.Deserialize>(input) - .Select(e => new PackageType - { - Name = e.Name, - Version = e.Version - }) - .ToList(); - } + private static List ParsePackageTypes(string input) + { + return TableJson.Deserialize>(input) + .Select(e => new PackageType + { + Name = e.Name, + Version = e.Version + }) + .ToList(); + } - private static List ParseTargetFrameworks(string targetFrameworks) - { - return TableJson.Deserialize>(targetFrameworks) - .Select(f => new TargetFramework { Moniker = f }) - .ToList(); - } + private static List ParseTargetFrameworks(string targetFrameworks) + { + return TableJson.Deserialize>(targetFrameworks) + .Select(f => new TargetFramework { Moniker = f }) + .ToList(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/TableJson.cs b/src/BaGet.Azure/Table/TableJson.cs index 657ce874d..6ff0a4c00 100644 --- a/src/BaGet.Azure/Table/TableJson.cs +++ b/src/BaGet.Azure/Table/TableJson.cs @@ -1,24 +1,23 @@ using System.Text.Encodings.Web; using System.Text.Json; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// The JSON held in the table's string columns (authors, tags, dependencies, package +/// types, frameworks). Rows written by earlier versions used Newtonsoft.Json, so this +/// keeps that format: property names as declared, and non-ASCII text unescaped. +/// +internal static class TableJson { - /// - /// The JSON held in the table's string columns (authors, tags, dependencies, package - /// types, frameworks). Rows written by earlier versions used Newtonsoft.Json, so this - /// keeps that format: property names as declared, and non-ASCII text unescaped. - /// - internal static class TableJson + internal static readonly JsonSerializerOptions Options = new JsonSerializerOptions { - internal static readonly JsonSerializerOptions Options = new JsonSerializerOptions - { - // Newtonsoft matched property names case-insensitively, so older rows may differ in case. - PropertyNameCaseInsensitive = true, - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - }; + // Newtonsoft matched property names case-insensitively, so older rows may differ in case. + PropertyNameCaseInsensitive = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; - public static string Serialize(T value) => JsonSerializer.Serialize(value, Options); + public static string Serialize(T value) => JsonSerializer.Serialize(value, Options); - public static T Deserialize(string json) => JsonSerializer.Deserialize(json, Options); - } -} + public static T Deserialize(string json) => JsonSerializer.Deserialize(json, Options); +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/TableOperationBuilder.cs b/src/BaGet.Azure/Table/TableOperationBuilder.cs index 65623c815..4258e06ad 100644 --- a/src/BaGet.Azure/Table/TableOperationBuilder.cs +++ b/src/BaGet.Azure/Table/TableOperationBuilder.cs @@ -5,125 +5,124 @@ using Microsoft.Azure.Cosmos.Table; using NuGet.Versioning; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class TableOperationBuilder { - public class TableOperationBuilder + public TableOperation AddPackage(Package package) { - public TableOperation AddPackage(Package package) - { - if (package == null) throw new ArgumentNullException(nameof(package)); - - var version = package.Version; - var normalizedVersion = version.ToNormalizedString(); - - var entity = new PackageEntity - { - PartitionKey = package.Id.ToLowerInvariant(), - RowKey = normalizedVersion.ToLowerInvariant(), - - Id = package.Id, - NormalizedVersion = normalizedVersion, - OriginalVersion = version.ToFullString(), - Authors = TableJson.Serialize(package.Authors), - Description = package.Description, - Downloads = package.Downloads, - HasReadme = package.HasReadme, - HasEmbeddedIcon = package.HasEmbeddedIcon, - IsPrerelease = package.IsPrerelease, - Language = package.Language, - Listed = package.Listed, - MinClientVersion = package.MinClientVersion, - Published = package.Published, - RequireLicenseAcceptance = package.RequireLicenseAcceptance, - SemVerLevel = (int)package.SemVerLevel, - Summary = package.Summary, - Title = package.Title, - IconUrl = package.IconUrlString, - LicenseUrl = package.LicenseUrlString, - ReleaseNotes = package.ReleaseNotes, - ProjectUrl = package.ProjectUrlString, - RepositoryUrl = package.RepositoryUrlString, - RepositoryType = package.RepositoryType, - Tags = TableJson.Serialize(package.Tags), - Dependencies = SerializeList(package.Dependencies, AsDependencyModel), - PackageTypes = SerializeList(package.PackageTypes, AsPackageTypeModel), - TargetFrameworks = SerializeList(package.TargetFrameworks, f => f.Moniker) - }; - - return TableOperation.Insert(entity); - } - - public TableOperation UpdateDownloads(string packageId, NuGetVersion packageVersion, long downloads) + if (package == null) throw new ArgumentNullException(nameof(package)); + + var version = package.Version; + var normalizedVersion = version.ToNormalizedString(); + + var entity = new PackageEntity { - var entity = new PackageDownloadsEntity(); + PartitionKey = package.Id.ToLowerInvariant(), + RowKey = normalizedVersion.ToLowerInvariant(), + + Id = package.Id, + NormalizedVersion = normalizedVersion, + OriginalVersion = version.ToFullString(), + Authors = TableJson.Serialize(package.Authors), + Description = package.Description, + Downloads = package.Downloads, + HasReadme = package.HasReadme, + HasEmbeddedIcon = package.HasEmbeddedIcon, + IsPrerelease = package.IsPrerelease, + Language = package.Language, + Listed = package.Listed, + MinClientVersion = package.MinClientVersion, + Published = package.Published, + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + SemVerLevel = (int)package.SemVerLevel, + Summary = package.Summary, + Title = package.Title, + IconUrl = package.IconUrlString, + LicenseUrl = package.LicenseUrlString, + ReleaseNotes = package.ReleaseNotes, + ProjectUrl = package.ProjectUrlString, + RepositoryUrl = package.RepositoryUrlString, + RepositoryType = package.RepositoryType, + Tags = TableJson.Serialize(package.Tags), + Dependencies = SerializeList(package.Dependencies, AsDependencyModel), + PackageTypes = SerializeList(package.PackageTypes, AsPackageTypeModel), + TargetFrameworks = SerializeList(package.TargetFrameworks, f => f.Moniker) + }; + + return TableOperation.Insert(entity); + } + + public TableOperation UpdateDownloads(string packageId, NuGetVersion packageVersion, long downloads) + { + var entity = new PackageDownloadsEntity(); - entity.PartitionKey = packageId.ToLowerInvariant(); - entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); - entity.Downloads = downloads; - entity.ETag = "*"; + entity.PartitionKey = packageId.ToLowerInvariant(); + entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); + entity.Downloads = downloads; + entity.ETag = "*"; - return TableOperation.Merge(entity); - } + return TableOperation.Merge(entity); + } - public TableOperation HardDeletePackage(string packageId, NuGetVersion packageVersion) - { - var entity = new PackageEntity(); + public TableOperation HardDeletePackage(string packageId, NuGetVersion packageVersion) + { + var entity = new PackageEntity(); - entity.PartitionKey = packageId.ToLowerInvariant(); - entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); - entity.ETag = "*"; + entity.PartitionKey = packageId.ToLowerInvariant(); + entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); + entity.ETag = "*"; - return TableOperation.Delete(entity); - } + return TableOperation.Delete(entity); + } - public TableOperation UnlistPackage(string packageId, NuGetVersion packageVersion) - { - var entity = new PackageListingEntity(); + public TableOperation UnlistPackage(string packageId, NuGetVersion packageVersion) + { + var entity = new PackageListingEntity(); - entity.PartitionKey = packageId.ToLowerInvariant(); - entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); - entity.Listed = false; - entity.ETag = "*"; + entity.PartitionKey = packageId.ToLowerInvariant(); + entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); + entity.Listed = false; + entity.ETag = "*"; - return TableOperation.Merge(entity); - } + return TableOperation.Merge(entity); + } - public TableOperation RelistPackage(string packageId, NuGetVersion packageVersion) - { - var entity = new PackageListingEntity(); + public TableOperation RelistPackage(string packageId, NuGetVersion packageVersion) + { + var entity = new PackageListingEntity(); - entity.PartitionKey = packageId.ToLowerInvariant(); - entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); - entity.Listed = true; - entity.ETag = "*"; + entity.PartitionKey = packageId.ToLowerInvariant(); + entity.RowKey = packageVersion.ToNormalizedString().ToLowerInvariant(); + entity.Listed = true; + entity.ETag = "*"; - return TableOperation.Merge(entity); - } + return TableOperation.Merge(entity); + } - private static string SerializeList(IReadOnlyList objects, Func map) - { - var data = objects.Select(map).ToList(); + private static string SerializeList(IReadOnlyList objects, Func map) + { + var data = objects.Select(map).ToList(); - return TableJson.Serialize(data); - } + return TableJson.Serialize(data); + } - public static DependencyModel AsDependencyModel(PackageDependency dependency) + public static DependencyModel AsDependencyModel(PackageDependency dependency) + { + return new DependencyModel { - return new DependencyModel - { - Id = dependency.Id, - VersionRange = dependency.VersionRange, - TargetFramework = dependency.TargetFramework - }; - } - - public static PackageTypeModel AsPackageTypeModel(PackageType packageType) + Id = dependency.Id, + VersionRange = dependency.VersionRange, + TargetFramework = dependency.TargetFramework + }; + } + + public static PackageTypeModel AsPackageTypeModel(PackageType packageType) + { + return new PackageTypeModel { - return new PackageTypeModel - { - Name = packageType.Name, - Version = packageType.Version - }; - } + Name = packageType.Name, + Version = packageType.Version + }; } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/TablePackageDatabase.cs b/src/BaGet.Azure/Table/TablePackageDatabase.cs index a9367d48d..0e7c0b4cc 100644 --- a/src/BaGet.Azure/Table/TablePackageDatabase.cs +++ b/src/BaGet.Azure/Table/TablePackageDatabase.cs @@ -8,243 +8,242 @@ using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Azure +namespace BaGet.Azure; + +/// +/// Stores the metadata of packages using Azure Table Storage. +/// +public class TablePackageDatabase : IPackageDatabase { - /// - /// Stores the metadata of packages using Azure Table Storage. - /// - public class TablePackageDatabase : IPackageDatabase + private const string TableName = "Packages"; + private const int MaxPreconditionFailures = 5; + + private readonly TableOperationBuilder _operationBuilder; + private readonly CloudTable _table; + private readonly ILogger _logger; + + public TablePackageDatabase( + TableOperationBuilder operationBuilder, + CloudTableClient client, + ILogger logger) { - private const string TableName = "Packages"; - private const int MaxPreconditionFailures = 5; + _operationBuilder = operationBuilder ?? throw new ArgumentNullException(nameof(operationBuilder)); + _table = client?.GetTableReference(TableName) ?? throw new ArgumentNullException(nameof(client)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - private readonly TableOperationBuilder _operationBuilder; - private readonly CloudTable _table; - private readonly ILogger _logger; + public async Task AddAsync(Package package, CancellationToken cancellationToken) + { + try + { + var operation = _operationBuilder.AddPackage(package); - public TablePackageDatabase( - TableOperationBuilder operationBuilder, - CloudTableClient client, - ILogger logger) + await _table.ExecuteAsync(operation, cancellationToken); + } + catch (StorageException e) when (e.IsAlreadyExistsException()) { - _operationBuilder = operationBuilder ?? throw new ArgumentNullException(nameof(operationBuilder)); - _table = client?.GetTableReference(TableName) ?? throw new ArgumentNullException(nameof(client)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + return PackageAddResult.PackageAlreadyExists; } - public async Task AddAsync(Package package, CancellationToken cancellationToken) + return PackageAddResult.Success; + } + + public async Task AddDownloadAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + var attempt = 0; + + while (true) { try { - var operation = _operationBuilder.AddPackage(package); + var operation = TableOperation.Retrieve( + id.ToLowerInvariant(), + version.ToNormalizedString().ToLowerInvariant()); - await _table.ExecuteAsync(operation, cancellationToken); + var result = await _table.ExecuteAsync(operation, cancellationToken); + var entity = result.Result as PackageDownloadsEntity; + + if (entity == null) + { + return; + } + + entity.Downloads += 1; + + await _table.ExecuteAsync(TableOperation.Merge(entity), cancellationToken); + return; } - catch (StorageException e) when (e.IsAlreadyExistsException()) + catch (StorageException e) + when (attempt < MaxPreconditionFailures && e.IsPreconditionFailedException()) { - return PackageAddResult.PackageAlreadyExists; + attempt++; + _logger.LogWarning( + e, + $"Retrying due to precondition failure, attempt {{Attempt}} of {MaxPreconditionFailures}..", + attempt); } - - return PackageAddResult.Success; } + } - public async Task AddDownloadAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) - { - var attempt = 0; + public async Task ExistsAsync(string id, CancellationToken cancellationToken) + { + var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, id.ToLowerInvariant()); + var query = new TableQuery() + .Select(MinimalColumnSet) + .Where(filter) + .Take(1); - while (true) - { - try - { - var operation = TableOperation.Retrieve( - id.ToLowerInvariant(), - version.ToNormalizedString().ToLowerInvariant()); + var result = await _table.ExecuteQuerySegmentedAsync(query, token: null, cancellationToken); - var result = await _table.ExecuteAsync(operation, cancellationToken); - var entity = result.Result as PackageDownloadsEntity; + return result.Results.Any(); + } - if (entity == null) - { - return; - } + public async Task ExistsAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + var operation = TableOperation.Retrieve( + id.ToLowerInvariant(), + version.ToNormalizedString().ToLowerInvariant(), + MinimalColumnSet); - entity.Downloads += 1; + var execution = await _table.ExecuteAsync(operation, cancellationToken); - await _table.ExecuteAsync(TableOperation.Merge(entity), cancellationToken); - return; - } - catch (StorageException e) - when (attempt < MaxPreconditionFailures && e.IsPreconditionFailedException()) - { - attempt++; - _logger.LogWarning( - e, - $"Retrying due to precondition failure, attempt {{Attempt}} of {MaxPreconditionFailures}..", - attempt); - } - } - } + return execution.Result is PackageEntity; + } - public async Task ExistsAsync(string id, CancellationToken cancellationToken) + public async Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken) + { + var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, id.ToLowerInvariant()); + if (!includeUnlisted) { - var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, id.ToLowerInvariant()); - var query = new TableQuery() - .Select(MinimalColumnSet) - .Where(filter) - .Take(1); - - var result = await _table.ExecuteQuerySegmentedAsync(query, token: null, cancellationToken); - - return result.Results.Any(); + filter = TableQuery.CombineFilters( + filter, + TableOperators.And, + TableQuery.GenerateFilterConditionForBool(nameof(PackageEntity.Listed), QueryComparisons.Equal, true)); } - public async Task ExistsAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) - { - var operation = TableOperation.Retrieve( - id.ToLowerInvariant(), - version.ToNormalizedString().ToLowerInvariant(), - MinimalColumnSet); - - var execution = await _table.ExecuteAsync(operation, cancellationToken); + var query = new TableQuery().Where(filter); + var results = new List(); - return execution.Result is PackageEntity; - } + // Request 500 results at a time from the server. + TableContinuationToken token = null; + query.TakeCount = 500; - public async Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken) + do { - var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, id.ToLowerInvariant()); - if (!includeUnlisted) - { - filter = TableQuery.CombineFilters( - filter, - TableOperators.And, - TableQuery.GenerateFilterConditionForBool(nameof(PackageEntity.Listed), QueryComparisons.Equal, true)); - } + var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); - var query = new TableQuery().Where(filter); - var results = new List(); + token = segment.ContinuationToken; - // Request 500 results at a time from the server. - TableContinuationToken token = null; - query.TakeCount = 500; + // Write out the properties for each entity returned. + results.AddRange(segment.Results.Select(r => r.AsPackage())); + } + while (token != null); - do - { - var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); + return results.OrderBy(p => p.Version).ToList(); + } - token = segment.ContinuationToken; + public async Task FindOrNullAsync( + string id, + NuGetVersion version, + bool includeUnlisted, + CancellationToken cancellationToken) + { + var operation = TableOperation.Retrieve( + id.ToLowerInvariant(), + version.ToNormalizedString().ToLowerInvariant()); - // Write out the properties for each entity returned. - results.AddRange(segment.Results.Select(r => r.AsPackage())); - } - while (token != null); + var result = await _table.ExecuteAsync(operation, cancellationToken); + var entity = result.Result as PackageEntity; - return results.OrderBy(p => p.Version).ToList(); + if (entity == null) + { + return null; } - public async Task FindOrNullAsync( - string id, - NuGetVersion version, - bool includeUnlisted, - CancellationToken cancellationToken) + // Filter out the package if it's unlisted. + if (!includeUnlisted && !entity.Listed) { - var operation = TableOperation.Retrieve( - id.ToLowerInvariant(), - version.ToNormalizedString().ToLowerInvariant()); + return null; + } - var result = await _table.ExecuteAsync(operation, cancellationToken); - var entity = result.Result as PackageEntity; + return entity.AsPackage(); + } - if (entity == null) - { - return null; - } + public async Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await TryUpdatePackageAsync( + _operationBuilder.HardDeletePackage(id, version), + cancellationToken); + } - // Filter out the package if it's unlisted. - if (!includeUnlisted && !entity.Listed) - { - return null; - } + public async Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await TryUpdatePackageAsync( + _operationBuilder.RelistPackage(id, version), + cancellationToken); + } - return entity.AsPackage(); - } + public async Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await TryUpdatePackageAsync( + _operationBuilder.UnlistPackage(id, version), + cancellationToken); + } - public async Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await TryUpdatePackageAsync( - _operationBuilder.HardDeletePackage(id, version), - cancellationToken); - } + private List MinimalColumnSet => new List { "PartitionKey" }; - public async Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + private async Task TryUpdatePackageAsync(TableOperation operation, CancellationToken cancellationToken) + { + try { - return await TryUpdatePackageAsync( - _operationBuilder.RelistPackage(id, version), - cancellationToken); + await _table.ExecuteAsync(operation, cancellationToken); } - - public async Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + catch (StorageException e) when (e.IsNotFoundException()) { - return await TryUpdatePackageAsync( - _operationBuilder.UnlistPackage(id, version), - cancellationToken); + return false; } - private List MinimalColumnSet => new List { "PartitionKey" }; - - private async Task TryUpdatePackageAsync(TableOperation operation, CancellationToken cancellationToken) - { - try - { - await _table.ExecuteAsync(operation, cancellationToken); - } - catch (StorageException e) when (e.IsNotFoundException()) - { - return false; - } - - return true; - } + return true; + } - // Deprecation and vulnerability metadata are stored in relational tables. The Azure - // Table backend has no schema for them, and one cannot be verified without an Azure - // account, so it says so rather than silently discarding what it is given. - private const string MetadataNotSupported = - "Package deprecation and vulnerability metadata are not supported when the database is Azure Table storage."; - - public Task SetDeprecationAsync( - string id, - NuGetVersion version, - PackageDeprecation deprecation, - CancellationToken cancellationToken) - { - throw new NotSupportedException(MetadataNotSupported); - } + // Deprecation and vulnerability metadata are stored in relational tables. The Azure + // Table backend has no schema for them, and one cannot be verified without an Azure + // account, so it says so rather than silently discarding what it is given. + private const string MetadataNotSupported = + "Package deprecation and vulnerability metadata are not supported when the database is Azure Table storage."; + + public Task SetDeprecationAsync( + string id, + NuGetVersion version, + PackageDeprecation deprecation, + CancellationToken cancellationToken) + { + throw new NotSupportedException(MetadataNotSupported); + } - public Task RemoveDeprecationAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - throw new NotSupportedException(MetadataNotSupported); - } + public Task RemoveDeprecationAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + throw new NotSupportedException(MetadataNotSupported); + } - public Task SetVulnerabilitiesAsync( - string id, - NuGetVersion version, - IReadOnlyList vulnerabilities, - CancellationToken cancellationToken) - { - throw new NotSupportedException(MetadataNotSupported); - } + public Task SetVulnerabilitiesAsync( + string id, + NuGetVersion version, + IReadOnlyList vulnerabilities, + CancellationToken cancellationToken) + { + throw new NotSupportedException(MetadataNotSupported); + } - public Task> GetAllVulnerabilitiesAsync(CancellationToken cancellationToken) - { - // Nothing can have been stored, so there is nothing to report. - return Task.FromResult>(Array.Empty()); - } + public Task> GetAllVulnerabilitiesAsync(CancellationToken cancellationToken) + { + // Nothing can have been stored, so there is nothing to report. + return Task.FromResult>(Array.Empty()); } -} +} \ No newline at end of file diff --git a/src/BaGet.Azure/Table/TableSearchService.cs b/src/BaGet.Azure/Table/TableSearchService.cs index 0d81ec1b8..1ebcc7274 100644 --- a/src/BaGet.Azure/Table/TableSearchService.cs +++ b/src/BaGet.Azure/Table/TableSearchService.cs @@ -7,305 +7,304 @@ using BaGet.Protocol.Models; using Microsoft.Azure.Cosmos.Table; -namespace BaGet.Azure +namespace BaGet.Azure; + +public class TableSearchService : ISearchService { - public class TableSearchService : ISearchService - { - private const string TableName = "Packages"; + private const string TableName = "Packages"; - private readonly CloudTable _table; - private readonly ISearchResponseBuilder _responseBuilder; + private readonly CloudTable _table; + private readonly ISearchResponseBuilder _responseBuilder; - public TableSearchService( - CloudTableClient client, - ISearchResponseBuilder responseBuilder) - { - _table = client?.GetTableReference(TableName) ?? throw new ArgumentNullException(nameof(client)); - _responseBuilder = responseBuilder ?? throw new ArgumentNullException(nameof(responseBuilder)); - } + public TableSearchService( + CloudTableClient client, + ISearchResponseBuilder responseBuilder) + { + _table = client?.GetTableReference(TableName) ?? throw new ArgumentNullException(nameof(client)); + _responseBuilder = responseBuilder ?? throw new ArgumentNullException(nameof(responseBuilder)); + } - public async Task SearchAsync( - SearchRequest request, - CancellationToken cancellationToken) - { - var results = await SearchAsync( - request.Query, - request.Skip, - request.Take, - request.IncludePrerelease, - request.IncludeSemVer2, - cancellationToken); - - return _responseBuilder.BuildSearch(results.Page, results.TotalHits); - } + public async Task SearchAsync( + SearchRequest request, + CancellationToken cancellationToken) + { + var results = await SearchAsync( + request.Query, + request.Skip, + request.Take, + request.IncludePrerelease, + request.IncludeSemVer2, + cancellationToken); + + return _responseBuilder.BuildSearch(results.Page, results.TotalHits); + } - public async Task AutocompleteAsync( - AutocompleteRequest request, - CancellationToken cancellationToken) - { - var results = await SearchAsync( - request.Query, - request.Skip, - request.Take, - request.IncludePrerelease, - request.IncludeSemVer2, - cancellationToken); + public async Task AutocompleteAsync( + AutocompleteRequest request, + CancellationToken cancellationToken) + { + var results = await SearchAsync( + request.Query, + request.Skip, + request.Take, + request.IncludePrerelease, + request.IncludeSemVer2, + cancellationToken); - var packageIds = results.Page.Select(p => p.PackageId).ToList(); + var packageIds = results.Page.Select(p => p.PackageId).ToList(); - return _responseBuilder.BuildAutocomplete(packageIds, results.TotalHits); - } + return _responseBuilder.BuildAutocomplete(packageIds, results.TotalHits); + } - public async Task ListPackageVersionsAsync( - VersionsRequest request, - CancellationToken cancellationToken) - { - // A package ID is one partition, so its versions are a single partition query. - var query = new TableQuery(); - query = query.Where(GenerateVersionsFilter(request.PackageId, request.IncludePrerelease, request.IncludeSemVer2)); + public async Task ListPackageVersionsAsync( + VersionsRequest request, + CancellationToken cancellationToken) + { + // A package ID is one partition, so its versions are a single partition query. + var query = new TableQuery(); + query = query.Where(GenerateVersionsFilter(request.PackageId, request.IncludePrerelease, request.IncludeSemVer2)); - var packages = await LoadPackagesAsync(query, maxPartitions: 1, cancellationToken); - var versions = packages - .OrderBy(p => p.Version) - .Select(p => p.Version.ToNormalizedString()) - .ToList(); + var packages = await LoadPackagesAsync(query, maxPartitions: 1, cancellationToken); + var versions = packages + .OrderBy(p => p.Version) + .Select(p => p.Version.ToNormalizedString()) + .ToList(); - return _responseBuilder.BuildAutocomplete(versions, versions.Count); - } + return _responseBuilder.BuildAutocomplete(versions, versions.Count); + } - public Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) - { - var response = _responseBuilder.BuildDependents(new List()); + public Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) + { + var response = _responseBuilder.BuildDependents(new List()); - return Task.FromResult(response); - } + return Task.FromResult(response); + } - /// - /// A page of package registrations and the number of registrations that matched, - /// disregarding skip and take. - /// - private readonly struct SearchPage + /// + /// A page of package registrations and the number of registrations that matched, + /// disregarding skip and take. + /// + private readonly struct SearchPage + { + public SearchPage(List page, long totalHits) { - public SearchPage(List page, long totalHits) - { - Page = page; - TotalHits = totalHits; - } + Page = page; + TotalHits = totalHits; + } - public List Page { get; } + public List Page { get; } - public long TotalHits { get; } - } + public long TotalHits { get; } + } - private async Task SearchAsync( - string searchText, - int skip, - int take, - bool includePrerelease, - bool includeSemVer2, - CancellationToken cancellationToken) - { - var filter = GenerateSearchFilter(searchText, includePrerelease, includeSemVer2); + private async Task SearchAsync( + string searchText, + int skip, + int take, + bool includePrerelease, + bool includeSemVer2, + CancellationToken cancellationToken) + { + var filter = GenerateSearchFilter(searchText, includePrerelease, includeSemVer2); - var query = new TableQuery(); - query = query.Where(filter); - query.TakeCount = 500; + var query = new TableQuery(); + query = query.Where(filter); + query.TakeCount = 500; - var results = await LoadPackagesAsync(query, maxPartitions: skip + take, cancellationToken); + var results = await LoadPackagesAsync(query, maxPartitions: skip + take, cancellationToken); - var registrations = results - .GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase) - .Select(group => new PackageRegistration(group.Key, group.ToList())) - .ToList(); + var registrations = results + .GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase) + .Select(group => new PackageRegistration(group.Key, group.ToList())) + .ToList(); - // Table storage cannot count. The scan above stops after "skip + take" partitions, - // so when it reached that limit there may be more: count them with a scan that - // reads only the partition keys of the matching rows. - var totalHits = registrations.Count < skip + take - ? registrations.Count - : await CountPartitionsAsync(filter, cancellationToken); + // Table storage cannot count. The scan above stops after "skip + take" partitions, + // so when it reached that limit there may be more: count them with a scan that + // reads only the partition keys of the matching rows. + var totalHits = registrations.Count < skip + take + ? registrations.Count + : await CountPartitionsAsync(filter, cancellationToken); - var page = registrations - .Skip(skip) - .Take(take) - .ToList(); + var page = registrations + .Skip(skip) + .Take(take) + .ToList(); - return new SearchPage(page, totalHits); - } + return new SearchPage(page, totalHits); + } - private async Task CountPartitionsAsync(string filter, CancellationToken cancellationToken) + private async Task CountPartitionsAsync(string filter, CancellationToken cancellationToken) + { + var query = new TableQuery() + .Where(filter) + .Select(new[] { "PartitionKey" }); + query.TakeCount = 1000; + + var partitionKeys = new List(); + TableContinuationToken token = null; + do { - var query = new TableQuery() - .Where(filter) - .Select(new[] { "PartitionKey" }); - query.TakeCount = 1000; - - var partitionKeys = new List(); - TableContinuationToken token = null; - do - { - var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); - - token = segment.ContinuationToken; - partitionKeys.AddRange(segment.Results.Select(r => r.PartitionKey)); - } - while (token != null); + var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); - return CountPartitions(partitionKeys); + token = segment.ContinuationToken; + partitionKeys.AddRange(segment.Results.Select(r => r.PartitionKey)); } + while (token != null); - /// - /// The number of package IDs among rows in partition key order: each ID is one - /// partition, and a partition's rows are contiguous. - /// - internal static long CountPartitions(IEnumerable partitionKeys) - { - long count = 0; - string last = null; + return CountPartitions(partitionKeys); + } - foreach (var key in partitionKeys) + /// + /// The number of package IDs among rows in partition key order: each ID is one + /// partition, and a partition's rows are contiguous. + /// + internal static long CountPartitions(IEnumerable partitionKeys) + { + long count = 0; + string last = null; + + foreach (var key in partitionKeys) + { + if (!string.Equals(key, last, StringComparison.Ordinal)) { - if (!string.Equals(key, last, StringComparison.Ordinal)) - { - count++; - last = key; - } + count++; + last = key; } - - return count; } - private async Task> LoadPackagesAsync( - TableQuery query, - int maxPartitions, - CancellationToken cancellationToken) - { - var results = new List(); + return count; + } - var partitions = 0; - string lastPartitionKey = null; - TableContinuationToken token = null; - do - { - var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); + private async Task> LoadPackagesAsync( + TableQuery query, + int maxPartitions, + CancellationToken cancellationToken) + { + var results = new List(); + + var partitions = 0; + string lastPartitionKey = null; + TableContinuationToken token = null; + do + { + var segment = await _table.ExecuteQuerySegmentedAsync(query, token, cancellationToken); - token = segment.ContinuationToken; + token = segment.ContinuationToken; - foreach (var result in segment.Results) + foreach (var result in segment.Results) + { + if (lastPartitionKey != result.PartitionKey) { - if (lastPartitionKey != result.PartitionKey) + lastPartitionKey = result.PartitionKey; + partitions++; + + // Enough partitions: stop rather than fetch segments only to skip them. + if (partitions > maxPartitions) { - lastPartitionKey = result.PartitionKey; - partitions++; - - // Enough partitions: stop rather than fetch segments only to skip them. - if (partitions > maxPartitions) - { - return results; - } + return results; } - - results.Add(result.AsPackage()); } - } - while (token != null); - return results; + results.Add(result.AsPackage()); + } } + while (token != null); - /// - /// The rows of one package ID that these filters allow. - /// - internal static string GenerateVersionsFilter(string packageId, bool includePrerelease, bool includeSemVer2) - { - if (packageId == null) throw new ArgumentNullException(nameof(packageId)); + return results; + } - var partition = TableQuery.GenerateFilterCondition( - "PartitionKey", - QueryComparisons.Equal, - packageId.ToLowerInvariant()); + /// + /// The rows of one package ID that these filters allow. + /// + internal static string GenerateVersionsFilter(string packageId, bool includePrerelease, bool includeSemVer2) + { + if (packageId == null) throw new ArgumentNullException(nameof(packageId)); - return GenerateFilters(partition, includePrerelease, includeSemVer2); - } + var partition = TableQuery.GenerateFilterCondition( + "PartitionKey", + QueryComparisons.Equal, + packageId.ToLowerInvariant()); - internal static string GenerateSearchFilter(string searchText, bool includePrerelease, bool includeSemVer2) - { - var result = ""; + return GenerateFilters(partition, includePrerelease, includeSemVer2); + } - if (!string.IsNullOrWhiteSpace(searchText)) - { - // Filter to rows where the "searchText" prefix matches on the partition key. - // Partition keys are lowercased IDs, and the comparison is ordinal, so the - // prefix must be lowercased too or a capitalised query matches nothing. - var prefix = searchText.TrimEnd().Split(separator: null).Last().ToLowerInvariant(); + internal static string GenerateSearchFilter(string searchText, bool includePrerelease, bool includeSemVer2) + { + var result = ""; - var prefixLower = prefix; - var prefixUpper = prefix + "~"; + if (!string.IsNullOrWhiteSpace(searchText)) + { + // Filter to rows where the "searchText" prefix matches on the partition key. + // Partition keys are lowercased IDs, and the comparison is ordinal, so the + // prefix must be lowercased too or a capitalised query matches nothing. + var prefix = searchText.TrimEnd().Split(separator: null).Last().ToLowerInvariant(); - var partitionLowerFilter = TableQuery.GenerateFilterCondition( - "PartitionKey", - QueryComparisons.GreaterThanOrEqual, - prefixLower); + var prefixLower = prefix; + var prefixUpper = prefix + "~"; - var partitionUpperFilter = TableQuery.GenerateFilterCondition( - "PartitionKey", - QueryComparisons.LessThanOrEqual, - prefixUpper); + var partitionLowerFilter = TableQuery.GenerateFilterCondition( + "PartitionKey", + QueryComparisons.GreaterThanOrEqual, + prefixLower); - result = TableQuery.CombineFilters(partitionLowerFilter, TableOperators.And, partitionUpperFilter); - } + var partitionUpperFilter = TableQuery.GenerateFilterCondition( + "PartitionKey", + QueryComparisons.LessThanOrEqual, + prefixUpper); - return GenerateFilters(result, includePrerelease, includeSemVer2); + result = TableQuery.CombineFilters(partitionLowerFilter, TableOperators.And, partitionUpperFilter); } - private static string GenerateFilters(string result, bool includePrerelease, bool includeSemVer2) + return GenerateFilters(result, includePrerelease, includeSemVer2); + } + + private static string GenerateFilters(string result, bool includePrerelease, bool includeSemVer2) + { + // Filter to rows that are listed. + result = GenerateAnd( + result, + GenerateIsTrue(nameof(PackageEntity.Listed))); + + if (!includePrerelease) { - // Filter to rows that are listed. result = GenerateAnd( result, - GenerateIsTrue(nameof(PackageEntity.Listed))); - - if (!includePrerelease) - { - result = GenerateAnd( - result, - GenerateIsFalse(nameof(PackageEntity.IsPrerelease))); - } + GenerateIsFalse(nameof(PackageEntity.IsPrerelease))); + } - if (!includeSemVer2) - { - result = GenerateAnd( - result, - TableQuery.GenerateFilterConditionForInt( - nameof(PackageEntity.SemVerLevel), - QueryComparisons.Equal, - 0)); - } + if (!includeSemVer2) + { + result = GenerateAnd( + result, + TableQuery.GenerateFilterConditionForInt( + nameof(PackageEntity.SemVerLevel), + QueryComparisons.Equal, + 0)); + } - return result; + return result; - string GenerateAnd(string left, string right) - { - if (string.IsNullOrEmpty(left)) return right; + string GenerateAnd(string left, string right) + { + if (string.IsNullOrEmpty(left)) return right; - return TableQuery.CombineFilters(left, TableOperators.And, right); - } + return TableQuery.CombineFilters(left, TableOperators.And, right); + } - string GenerateIsTrue(string propertyName) - { - return TableQuery.GenerateFilterConditionForBool( - propertyName, - QueryComparisons.Equal, - givenValue: true); - } + string GenerateIsTrue(string propertyName) + { + return TableQuery.GenerateFilterConditionForBool( + propertyName, + QueryComparisons.Equal, + givenValue: true); + } - string GenerateIsFalse(string propertyName) - { - return TableQuery.GenerateFilterConditionForBool( - propertyName, - QueryComparisons.Equal, - givenValue: false); - } + string GenerateIsFalse(string propertyName) + { + return TableQuery.GenerateFilterConditionForBool( + propertyName, + QueryComparisons.Equal, + givenValue: false); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Catalog/CatalogController.cs b/src/BaGet.Catalog/CatalogController.cs index 48d5344c6..4157c397e 100644 --- a/src/BaGet.Catalog/CatalogController.cs +++ b/src/BaGet.Catalog/CatalogController.cs @@ -5,74 +5,73 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -namespace BaGet.Catalog +namespace BaGet.Catalog; + +/// +/// The Catalog/3.0.0 resource. +/// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource +/// +public class CatalogController : Controller { + private readonly CatalogReader _reader; + + public CatalogController(CatalogReader reader) + { + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + } + /// - /// The Catalog/3.0.0 resource. - /// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource + /// A database that cannot hold the catalog has none, so the whole surface is absent. /// - public class CatalogController : Controller + public override void OnActionExecuting(ActionExecutingContext context) { - private readonly CatalogReader _reader; - - public CatalogController(CatalogReader reader) + if (!_reader.IsSupported) { - _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + context.Result = NotFound(); + return; } - /// - /// A database that cannot hold the catalog has none, so the whole surface is absent. - /// - public override void OnActionExecuting(ActionExecutingContext context) - { - if (!_reader.IsSupported) - { - context.Result = NotFound(); - return; - } + base.OnActionExecuting(context); + } - base.OnActionExecuting(context); - } + [HttpGet] + public async Task Index(CancellationToken cancellationToken) + { + return Json(await _reader.GetIndexAsync(cancellationToken)); + } - [HttpGet] - public async Task Index(CancellationToken cancellationToken) + [HttpGet] + public async Task Page(int pageIndex, CancellationToken cancellationToken) + { + var page = await _reader.GetPageOrNullAsync(pageIndex, cancellationToken); + if (page == null) { - return Json(await _reader.GetIndexAsync(cancellationToken)); + return NotFound(); } - [HttpGet] - public async Task Page(int pageIndex, CancellationToken cancellationToken) - { - var page = await _reader.GetPageOrNullAsync(pageIndex, cancellationToken); - if (page == null) - { - return NotFound(); - } + return Json(page); + } - return Json(page); + [HttpGet] + public async Task Leaf(string commitId, CancellationToken cancellationToken) + { + string leaf; + try + { + leaf = await _reader.GetLeafOrNullAsync(commitId, cancellationToken); } - - [HttpGet] - public async Task Leaf(string commitId, CancellationToken cancellationToken) + catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) { - string leaf; - try - { - leaf = await _reader.GetLeafOrNullAsync(commitId, cancellationToken); - } - catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) - { - // The entry exists but its document does not, which "catalog rebuild" cannot - // repair: the leaf is a snapshot that was never written. - leaf = null; - } - - if (leaf == null) - { - return NotFound(); - } + // The entry exists but its document does not, which "catalog rebuild" cannot + // repair: the leaf is a snapshot that was never written. + leaf = null; + } - return Content(leaf, "application/json"); + if (leaf == null) + { + return NotFound(); } + + return Content(leaf, "application/json"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Catalog/CatalogDatabase.cs b/src/BaGet.Catalog/CatalogDatabase.cs index 853a64b2a..c0206cffd 100644 --- a/src/BaGet.Catalog/CatalogDatabase.cs +++ b/src/BaGet.Catalog/CatalogDatabase.cs @@ -6,106 +6,105 @@ using BaGet.Core; using Microsoft.EntityFrameworkCore; -namespace BaGet.Catalog +namespace BaGet.Catalog; + +/// +/// The catalog log in the relational database, beside the packages. +/// +public class CatalogDatabase : ICatalogDatabase { - /// - /// The catalog log in the relational database, beside the packages. - /// - public class CatalogDatabase : ICatalogDatabase - { - private readonly IContext _context; + private readonly IContext _context; - public CatalogDatabase(IContext context) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - } + public CatalogDatabase(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } - public bool IsSupported => true; + public bool IsSupported => true; - public async Task GetLastCommitTimestampAsync(CancellationToken cancellationToken) - { - // Entries are added in commit order, so the highest key is the newest. - var last = await _context.CatalogLeafs - .OrderByDescending(e => e.Key) - .Select(e => (DateTime?)e.CommitTimestamp) - .FirstOrDefaultAsync(cancellationToken); + public async Task GetLastCommitTimestampAsync(CancellationToken cancellationToken) + { + // Entries are added in commit order, so the highest key is the newest. + var last = await _context.CatalogLeafs + .OrderByDescending(e => e.Key) + .Select(e => (DateTime?)e.CommitTimestamp) + .FirstOrDefaultAsync(cancellationToken); - return last.HasValue ? AsUtc(last.Value) : (DateTime?)null; - } + return last.HasValue ? AsUtc(last.Value) : (DateTime?)null; + } - public async Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken) - { - _context.CatalogLeafs.Add(entry); + public async Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken) + { + _context.CatalogLeafs.Add(entry); - await _context.SaveChangesAsync(cancellationToken); - } + await _context.SaveChangesAsync(cancellationToken); + } - public async Task> GetCommitTimestampsAsync(CancellationToken cancellationToken) - { - var timestamps = await _context.CatalogLeafs - .OrderBy(e => e.Key) - .Select(e => e.CommitTimestamp) - .ToListAsync(cancellationToken); + public async Task> GetCommitTimestampsAsync(CancellationToken cancellationToken) + { + var timestamps = await _context.CatalogLeafs + .OrderBy(e => e.Key) + .Select(e => e.CommitTimestamp) + .ToListAsync(cancellationToken); - return timestamps.Select(AsUtc).ToList(); - } + return timestamps.Select(AsUtc).ToList(); + } - public async Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken) + public async Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken) + { + var entries = await _context.CatalogLeafs + .AsNoTracking() + .OrderBy(e => e.Key) + .Skip(skip) + .Take(take) + .ToListAsync(cancellationToken); + + foreach (var entry in entries) { - var entries = await _context.CatalogLeafs - .AsNoTracking() - .OrderBy(e => e.Key) - .Skip(skip) - .Take(take) - .ToListAsync(cancellationToken); - - foreach (var entry in entries) - { - entry.CommitTimestamp = AsUtc(entry.CommitTimestamp); - } - - return entries; + entry.CommitTimestamp = AsUtc(entry.CommitTimestamp); } - public async Task FindOrNullAsync(string commitId, CancellationToken cancellationToken) - { - var entry = await _context.CatalogLeafs - .AsNoTracking() - .FirstOrDefaultAsync(e => e.CommitId == commitId, cancellationToken); + return entries; + } - if (entry != null) - { - entry.CommitTimestamp = AsUtc(entry.CommitTimestamp); - } + public async Task FindOrNullAsync(string commitId, CancellationToken cancellationToken) + { + var entry = await _context.CatalogLeafs + .AsNoTracking() + .FirstOrDefaultAsync(e => e.CommitId == commitId, cancellationToken); - return entry; + if (entry != null) + { + entry.CommitTimestamp = AsUtc(entry.CommitTimestamp); } - // Every timestamp is written as UTC, but some providers, such as SQLite, read it - // back without a kind. - private static DateTime AsUtc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc); + return entry; } - /// - /// Used when the configured database cannot hold the catalog. - /// - public class NullCatalogDatabase : ICatalogDatabase - { - public bool IsSupported => false; + // Every timestamp is written as UTC, but some providers, such as SQLite, read it + // back without a kind. + private static DateTime AsUtc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc); +} - public Task GetLastCommitTimestampAsync(CancellationToken cancellationToken) - => Task.FromResult(null); +/// +/// Used when the configured database cannot hold the catalog. +/// +public class NullCatalogDatabase : ICatalogDatabase +{ + public bool IsSupported => false; - public Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken) - => throw new NotSupportedException("The configured database does not support the catalog."); + public Task GetLastCommitTimestampAsync(CancellationToken cancellationToken) + => Task.FromResult(null); - public Task> GetCommitTimestampsAsync(CancellationToken cancellationToken) - => Task.FromResult>(Array.Empty()); + public Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken) + => throw new NotSupportedException("The configured database does not support the catalog."); - public Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken) - => Task.FromResult>(Array.Empty()); + public Task> GetCommitTimestampsAsync(CancellationToken cancellationToken) + => Task.FromResult>(Array.Empty()); - public Task FindOrNullAsync(string commitId, CancellationToken cancellationToken) - => Task.FromResult(null); - } -} + public Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken) + => Task.FromResult>(Array.Empty()); + + public Task FindOrNullAsync(string commitId, CancellationToken cancellationToken) + => Task.FromResult(null); +} \ No newline at end of file diff --git a/src/BaGet.Catalog/CatalogReader.cs b/src/BaGet.Catalog/CatalogReader.cs index 547c2f6e4..2e169f362 100644 --- a/src/BaGet.Catalog/CatalogReader.cs +++ b/src/BaGet.Catalog/CatalogReader.cs @@ -8,110 +8,109 @@ using BaGet.Core; using BaGet.Protocol.Models; -namespace BaGet.Catalog +namespace BaGet.Catalog; + +/// +/// Builds the catalog documents. The index and pages are built from the database on +/// read, so their URLs always match the host the client used; the leaves are read from +/// storage, since a deleted package's details exist nowhere else. +/// +public class CatalogReader { /// - /// Builds the catalog documents. The index and pages are built from the database on - /// read, so their URLs always match the host the client used; the leaves are read from - /// storage, since a deleted package's details exist nowhere else. + /// nuget.org uses 550. Any size is valid; a client follows the index. /// - public class CatalogReader - { - /// - /// nuget.org uses 550. Any size is valid; a client follows the index. - /// - internal const int PageSize = 500; + internal const int PageSize = 500; - private readonly ICatalogDatabase _catalog; - private readonly IStorageService _storage; - private readonly IUrlGenerator _url; + private readonly ICatalogDatabase _catalog; + private readonly IStorageService _storage; + private readonly IUrlGenerator _url; - public CatalogReader(ICatalogDatabase catalog, IStorageService storage, IUrlGenerator url) - { - _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public CatalogReader(ICatalogDatabase catalog, IStorageService storage, IUrlGenerator url) + { + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - public bool IsSupported => _catalog.IsSupported; + public bool IsSupported => _catalog.IsSupported; - public async Task GetIndexAsync(CancellationToken cancellationToken) - { - var timestamps = await _catalog.GetCommitTimestampsAsync(cancellationToken); - - return new CatalogIndex - { - CommitTimestamp = timestamps.Count == 0 ? DateTimeOffset.UnixEpoch : Utc(timestamps[^1]), - Count = PageCount(timestamps.Count), - Items = Enumerable.Range(0, PageCount(timestamps.Count)) - .Select(page => - { - var count = Math.Min(PageSize, timestamps.Count - page * PageSize); - - return new CatalogPageItem - { - CatalogPageUrl = _url.GetCatalogPageUrl(page), - CommitTimestamp = Utc(timestamps[page * PageSize + count - 1]), - Count = count, - }; - }) - .ToList(), - }; - } + public async Task GetIndexAsync(CancellationToken cancellationToken) + { + var timestamps = await _catalog.GetCommitTimestampsAsync(cancellationToken); - /// - /// One page, or null if the page does not exist. - /// - public async Task GetPageOrNullAsync(int pageIndex, CancellationToken cancellationToken) + return new CatalogIndex { - if (pageIndex < 0) return null; - - var entries = await _catalog.GetEntriesAsync(pageIndex * PageSize, PageSize, cancellationToken); - if (entries.Count == 0) return null; - - return new CatalogPage - { - CommitTimestamp = Utc(entries[^1].CommitTimestamp), - Count = entries.Count, - CatalogIndexUrl = _url.GetCatalogIndexUrl(), - Items = entries - .Select(e => new CatalogLeafItem + CommitTimestamp = timestamps.Count == 0 ? DateTimeOffset.UnixEpoch : Utc(timestamps[^1]), + Count = PageCount(timestamps.Count), + Items = Enumerable.Range(0, PageCount(timestamps.Count)) + .Select(page => + { + var count = Math.Min(PageSize, timestamps.Count - page * PageSize); + + return new CatalogPageItem { - CatalogLeafUrl = _url.GetCatalogLeafUrl(e.CommitId), - Type = "nuget:" + e.Type, - CommitTimestamp = Utc(e.CommitTimestamp), - PackageId = e.PackageId, - PackageVersion = e.PackageVersion, - }) - .ToList(), - }; - } + CatalogPageUrl = _url.GetCatalogPageUrl(page), + CommitTimestamp = Utc(timestamps[page * PageSize + count - 1]), + Count = count, + }; + }) + .ToList(), + }; + } - /// - /// One leaf document as JSON, or null if no such leaf exists. - /// - public async Task GetLeafOrNullAsync(string commitId, CancellationToken cancellationToken) - { - if (!Guid.TryParseExact(commitId, "D", out _)) return null; + /// + /// One page, or null if the page does not exist. + /// + public async Task GetPageOrNullAsync(int pageIndex, CancellationToken cancellationToken) + { + if (pageIndex < 0) return null; - var entry = await _catalog.FindOrNullAsync(commitId, cancellationToken); - if (entry == null) return null; + var entries = await _catalog.GetEntriesAsync(pageIndex * PageSize, PageSize, cancellationToken); + if (entries.Count == 0) return null; + + return new CatalogPage + { + CommitTimestamp = Utc(entries[^1].CommitTimestamp), + Count = entries.Count, + CatalogIndexUrl = _url.GetCatalogIndexUrl(), + Items = entries + .Select(e => new CatalogLeafItem + { + CatalogLeafUrl = _url.GetCatalogLeafUrl(e.CommitId), + Type = "nuget:" + e.Type, + CommitTimestamp = Utc(e.CommitTimestamp), + PackageId = e.PackageId, + PackageVersion = e.PackageVersion, + }) + .ToList(), + }; + } - JsonNode leaf; - using (var stream = await _storage.GetAsync(CatalogWriter.LeafPath(entry.CommitId), cancellationToken)) - { - leaf = await JsonNode.ParseAsync(stream, cancellationToken: cancellationToken); - } + /// + /// One leaf document as JSON, or null if no such leaf exists. + /// + public async Task GetLeafOrNullAsync(string commitId, CancellationToken cancellationToken) + { + if (!Guid.TryParseExact(commitId, "D", out _)) return null; - // The leaf's own URL is not stored, so it follows the host like every other URL. - leaf["@id"] = _url.GetCatalogLeafUrl(entry.CommitId); + var entry = await _catalog.FindOrNullAsync(commitId, cancellationToken); + if (entry == null) return null; - return leaf.ToJsonString(); + JsonNode leaf; + using (var stream = await _storage.GetAsync(CatalogWriter.LeafPath(entry.CommitId), cancellationToken)) + { + leaf = await JsonNode.ParseAsync(stream, cancellationToken: cancellationToken); } - internal static int PageCount(int entries) => (entries + PageSize - 1) / PageSize; + // The leaf's own URL is not stored, so it follows the host like every other URL. + leaf["@id"] = _url.GetCatalogLeafUrl(entry.CommitId); - private static DateTimeOffset Utc(DateTime value) - => new DateTimeOffset(DateTime.SpecifyKind(value, DateTimeKind.Utc)); + return leaf.ToJsonString(); } -} + + internal static int PageCount(int entries) => (entries + PageSize - 1) / PageSize; + + private static DateTimeOffset Utc(DateTime value) + => new DateTimeOffset(DateTime.SpecifyKind(value, DateTimeKind.Utc)); +} \ No newline at end of file diff --git a/src/BaGet.Catalog/CatalogRebuilder.cs b/src/BaGet.Catalog/CatalogRebuilder.cs index 25436d06b..3bb6dfb3e 100644 --- a/src/BaGet.Catalog/CatalogRebuilder.cs +++ b/src/BaGet.Catalog/CatalogRebuilder.cs @@ -8,101 +8,100 @@ using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Catalog +namespace BaGet.Catalog; + +/// +/// Reconciles the catalog with the packages: appends a details entry for every package +/// version whose latest entry is missing or a delete, and a delete entry for every +/// version whose latest entry is details but which no longer exists. This backfills +/// packages pushed before the catalog existed, and repairs a commit that failed. +/// +/// +/// The log is append-only, so nothing is rewritten. A change whose commit failed while +/// the version kept existing, such as an unlist, cannot be detected and is not repaired. +/// +public class CatalogRebuilder { - /// - /// Reconciles the catalog with the packages: appends a details entry for every package - /// version whose latest entry is missing or a delete, and a delete entry for every - /// version whose latest entry is details but which no longer exists. This backfills - /// packages pushed before the catalog existed, and repairs a commit that failed. - /// - /// - /// The log is append-only, so nothing is rewritten. A change whose commit failed while - /// the version kept existing, such as an unlist, cannot be detected and is not repaired. - /// - public class CatalogRebuilder + private readonly ICatalogDatabase _catalog; + private readonly IContext _context; + private readonly CatalogWriter _writer; + private readonly ILogger _logger; + + public CatalogRebuilder( + ICatalogDatabase catalog, + IContext context, + CatalogWriter writer, + ILogger logger) { - private readonly ICatalogDatabase _catalog; - private readonly IContext _context; - private readonly CatalogWriter _writer; - private readonly ILogger _logger; + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _writer = writer ?? throw new ArgumentNullException(nameof(writer)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public CatalogRebuilder( - ICatalogDatabase catalog, - IContext context, - CatalogWriter writer, - ILogger logger) + public async Task<(int Added, int Deleted)> RebuildAsync(CancellationToken cancellationToken) + { + if (!_catalog.IsSupported) { - _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); - _context = context ?? throw new ArgumentNullException(nameof(context)); - _writer = writer ?? throw new ArgumentNullException(nameof(writer)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _logger.LogWarning("The configured database does not support the catalog"); + return (0, 0); } - public async Task<(int Added, int Deleted)> RebuildAsync(CancellationToken cancellationToken) + var latest = new Dictionary<(string, string), CatalogEntry>(); + for (var skip = 0; ; skip += CatalogReader.PageSize) { - if (!_catalog.IsSupported) + var entries = await _catalog.GetEntriesAsync(skip, CatalogReader.PageSize, cancellationToken); + foreach (var entry in entries) { - _logger.LogWarning("The configured database does not support the catalog"); - return (0, 0); + latest[Identity(entry.PackageId, entry.PackageVersion)] = entry; } - var latest = new Dictionary<(string, string), CatalogEntry>(); - for (var skip = 0; ; skip += CatalogReader.PageSize) - { - var entries = await _catalog.GetEntriesAsync(skip, CatalogReader.PageSize, cancellationToken); - foreach (var entry in entries) - { - latest[Identity(entry.PackageId, entry.PackageVersion)] = entry; - } - - if (entries.Count < CatalogReader.PageSize) break; - } - - var packages = await _context.Packages - .AsNoTracking() - .Select(p => new { p.Id, p.NormalizedVersionString }) - .ToListAsync(cancellationToken); - - var existing = new HashSet<(string, string)>(); - var added = 0; - foreach (var package in packages.OrderBy(p => p.Id, StringComparer.OrdinalIgnoreCase)) - { - var identity = Identity(package.Id, package.NormalizedVersionString); - existing.Add(identity); + if (entries.Count < CatalogReader.PageSize) break; + } - if (latest.TryGetValue(identity, out var entry) && entry.Type == CatalogEntry.PackageDetailsType) - { - continue; - } + var packages = await _context.Packages + .AsNoTracking() + .Select(p => new { p.Id, p.NormalizedVersionString }) + .ToListAsync(cancellationToken); - await _writer.OnPackageChangedAsync( - package.Id, - NuGetVersion.Parse(package.NormalizedVersionString), - cancellationToken); - added++; - } + var existing = new HashSet<(string, string)>(); + var added = 0; + foreach (var package in packages.OrderBy(p => p.Id, StringComparer.OrdinalIgnoreCase)) + { + var identity = Identity(package.Id, package.NormalizedVersionString); + existing.Add(identity); - var deleted = 0; - foreach (var pair in latest.Where(l => l.Value.Type == CatalogEntry.PackageDetailsType && !existing.Contains(l.Key))) + if (latest.TryGetValue(identity, out var entry) && entry.Type == CatalogEntry.PackageDetailsType) { - await _writer.OnPackageDeletedAsync( - pair.Value.PackageId, - NuGetVersion.Parse(pair.Value.PackageVersion), - cancellationToken); - deleted++; + continue; } - _logger.LogInformation( - "Catalog rebuilt: {Added} details entries and {Deleted} delete entries appended", - added, - deleted); + await _writer.OnPackageChangedAsync( + package.Id, + NuGetVersion.Parse(package.NormalizedVersionString), + cancellationToken); + added++; + } - return (added, deleted); + var deleted = 0; + foreach (var pair in latest.Where(l => l.Value.Type == CatalogEntry.PackageDetailsType && !existing.Contains(l.Key))) + { + await _writer.OnPackageDeletedAsync( + pair.Value.PackageId, + NuGetVersion.Parse(pair.Value.PackageVersion), + cancellationToken); + deleted++; } - // Package IDs are case insensitive. - private static (string, string) Identity(string id, string version) - => (id.ToLowerInvariant(), NuGetVersion.Parse(version).ToNormalizedString().ToLowerInvariant()); + _logger.LogInformation( + "Catalog rebuilt: {Added} details entries and {Deleted} delete entries appended", + added, + deleted); + + return (added, deleted); } -} + + // Package IDs are case insensitive. + private static (string, string) Identity(string id, string version) + => (id.ToLowerInvariant(), NuGetVersion.Parse(version).ToNormalizedString().ToLowerInvariant()); +} \ No newline at end of file diff --git a/src/BaGet.Catalog/CatalogServiceCollectionExtensions.cs b/src/BaGet.Catalog/CatalogServiceCollectionExtensions.cs index bd4d4423e..a8119da46 100644 --- a/src/BaGet.Catalog/CatalogServiceCollectionExtensions.cs +++ b/src/BaGet.Catalog/CatalogServiceCollectionExtensions.cs @@ -2,27 +2,26 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet.Catalog +namespace BaGet.Catalog; + +public static class CatalogServiceCollectionExtensions { - public static class CatalogServiceCollectionExtensions + public static IServiceCollection AddBaGetCatalog(this IServiceCollection services) { - public static IServiceCollection AddBaGetCatalog(this IServiceCollection services) - { - // A database without the catalog table, such as Azure Table storage, is - // registered as the null context; the catalog is then switched off. - services.TryAddScoped(provider => - provider.GetRequiredService() is NullContext - ? (ICatalogDatabase)new NullCatalogDatabase() - : new CatalogDatabase(provider.GetRequiredService())); + // A database without the catalog table, such as Azure Table storage, is + // registered as the null context; the catalog is then switched off. + services.TryAddScoped(provider => + provider.GetRequiredService() is NullContext + ? (ICatalogDatabase)new NullCatalogDatabase() + : new CatalogDatabase(provider.GetRequiredService())); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); - services.TryAddEnumerable(ServiceDescriptor.Transient()); - services.TryAddEnumerable(ServiceDescriptor.Transient()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); - return services; - } + return services; } -} +} \ No newline at end of file diff --git a/src/BaGet.Catalog/CatalogServiceIndexProvider.cs b/src/BaGet.Catalog/CatalogServiceIndexProvider.cs index 65a2cd9e3..9f0ff034a 100644 --- a/src/BaGet.Catalog/CatalogServiceIndexProvider.cs +++ b/src/BaGet.Catalog/CatalogServiceIndexProvider.cs @@ -3,31 +3,30 @@ using BaGet.Core; using BaGet.Protocol.Models; -namespace BaGet.Catalog +namespace BaGet.Catalog; + +/// +/// Advertises Catalog/3.0.0, unless the database cannot hold the catalog. +/// +public class CatalogServiceIndexProvider : IServiceIndexResourceProvider { - /// - /// Advertises Catalog/3.0.0, unless the database cannot hold the catalog. - /// - public class CatalogServiceIndexProvider : IServiceIndexResourceProvider + private readonly ICatalogDatabase _catalog; + private readonly IUrlGenerator _url; + + public CatalogServiceIndexProvider(ICatalogDatabase catalog, IUrlGenerator url) { - private readonly ICatalogDatabase _catalog; - private readonly IUrlGenerator _url; + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - public CatalogServiceIndexProvider(ICatalogDatabase catalog, IUrlGenerator url) - { - _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public IEnumerable GetResources() + { + if (!_catalog.IsSupported) yield break; - public IEnumerable GetResources() + yield return new ServiceIndexItem { - if (!_catalog.IsSupported) yield break; - - yield return new ServiceIndexItem - { - ResourceUrl = _url.GetCatalogIndexUrl(), - Type = "Catalog/3.0.0", - }; - } + ResourceUrl = _url.GetCatalogIndexUrl(), + Type = "Catalog/3.0.0", + }; } -} +} \ No newline at end of file diff --git a/src/BaGet.Catalog/CatalogWriter.cs b/src/BaGet.Catalog/CatalogWriter.cs index 2e8737b70..111b52ca4 100644 --- a/src/BaGet.Catalog/CatalogWriter.cs +++ b/src/BaGet.Catalog/CatalogWriter.cs @@ -11,254 +11,253 @@ using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Catalog +namespace BaGet.Catalog; + +/// +/// Appends a catalog entry for every package change. Each entry's leaf document is +/// written to storage first, so a leaf can always be served once its entry exists. +/// +public class CatalogWriter : IPackageChangeHandler { - /// - /// Appends a catalog entry for every package change. Each entry's leaf document is - /// written to storage first, so a leaf can always be served once its entry exists. - /// - public class CatalogWriter : IPackageChangeHandler + internal static readonly JsonSerializerOptions LeafSerializerOptions = new JsonSerializerOptions { - internal static readonly JsonSerializerOptions LeafSerializerOptions = new JsonSerializerOptions - { - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - }; + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + // Commit timestamps must strictly increase, or a mirror reading the catalog + // "after" its cursor could miss an entry. Commits in this process are serialized. + // Several BaGet instances writing to one database are not coordinated. + private static readonly SemaphoreSlim CommitLock = new SemaphoreSlim(1, 1); + + private readonly ICatalogDatabase _catalog; + private readonly IPackageDatabase _packages; + private readonly IPackageStorageService _packageStorage; + private readonly IStorageService _storage; + private readonly SystemTime _time; + private readonly ILogger _logger; + + public CatalogWriter( + ICatalogDatabase catalog, + IPackageDatabase packages, + IPackageStorageService packageStorage, + IStorageService storage, + SystemTime time, + ILogger logger) + { + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _packageStorage = packageStorage ?? throw new ArgumentNullException(nameof(packageStorage)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - // Commit timestamps must strictly increase, or a mirror reading the catalog - // "after" its cursor could miss an entry. Commits in this process are serialized. - // Several BaGet instances writing to one database are not coordinated. - private static readonly SemaphoreSlim CommitLock = new SemaphoreSlim(1, 1); - - private readonly ICatalogDatabase _catalog; - private readonly IPackageDatabase _packages; - private readonly IPackageStorageService _packageStorage; - private readonly IStorageService _storage; - private readonly SystemTime _time; - private readonly ILogger _logger; - - public CatalogWriter( - ICatalogDatabase catalog, - IPackageDatabase packages, - IPackageStorageService packageStorage, - IStorageService storage, - SystemTime time, - ILogger logger) - { - _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _packageStorage = packageStorage ?? throw new ArgumentNullException(nameof(packageStorage)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _time = time ?? throw new ArgumentNullException(nameof(time)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + internal static string LeafPath(string commitId) => $"catalog/{commitId}.json"; - internal static string LeafPath(string commitId) => $"catalog/{commitId}.json"; + public async Task OnPackageChangedAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + if (!_catalog.IsSupported) return; - public async Task OnPackageChangedAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + var package = await _packages.FindOrNullAsync(id, version, includeUnlisted: true, cancellationToken); + if (package == null) { - if (!_catalog.IsSupported) return; - - var package = await _packages.FindOrNullAsync(id, version, includeUnlisted: true, cancellationToken); - if (package == null) - { - _logger.LogWarning( - "Package {PackageId} {PackageVersion} changed but no longer exists; no catalog entry written", - id, - version); - return; - } - - var (hash, size) = await HashPackageAsync(package, cancellationToken); - - await CommitAsync( - CatalogEntry.PackageDetailsType, - package.Id, - package.Version, - (commitId, timestamp) => BuildDetailsLeaf(package, hash, size, commitId, timestamp), - cancellationToken); + _logger.LogWarning( + "Package {PackageId} {PackageVersion} changed but no longer exists; no catalog entry written", + id, + version); + return; } - public async Task OnPackageDeletedAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - if (!_catalog.IsSupported) return; + var (hash, size) = await HashPackageAsync(package, cancellationToken); - await CommitAsync( - CatalogEntry.PackageDeleteType, - id, - version, - (commitId, timestamp) => new PackageDeleteCatalogLeaf - { - Type = new[] { CatalogEntry.PackageDeleteType, "catalog:Permalink" }, - CommitId = commitId, - CommitTimestamp = timestamp, - PackageId = id, - PackageVersion = version.ToNormalizedString(), - Published = timestamp, - }, - cancellationToken); - } + await CommitAsync( + CatalogEntry.PackageDetailsType, + package.Id, + package.Version, + (commitId, timestamp) => BuildDetailsLeaf(package, hash, size, commitId, timestamp), + cancellationToken); + } - internal static PackageDetailsCatalogLeaf BuildDetailsLeaf( - Package package, - string hash, - long size, - string commitId, - DateTimeOffset timestamp) - { - var published = new DateTimeOffset(DateTime.SpecifyKind(package.Published, DateTimeKind.Utc)); + public async Task OnPackageDeletedAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + if (!_catalog.IsSupported) return; - return new PackageDetailsCatalogLeaf + await CommitAsync( + CatalogEntry.PackageDeleteType, + id, + version, + (commitId, timestamp) => new PackageDeleteCatalogLeaf { - Type = new[] { CatalogEntry.PackageDetailsType, "catalog:Permalink" }, + Type = new[] { CatalogEntry.PackageDeleteType, "catalog:Permalink" }, CommitId = commitId, CommitTimestamp = timestamp, - PackageId = package.Id, - PackageVersion = package.NormalizedVersionString, - VerbatimVersion = package.OriginalVersionString ?? package.NormalizedVersionString, - Published = published, - Created = published, - LastEdited = timestamp, - Authors = string.Join(", ", package.Authors ?? Array.Empty()), - Description = package.Description, - DependencyGroups = RegistrationBuilder.ToDependencyGroups(package).ToList(), - IconUrl = NullIfEmpty(package.IconUrlString), - IsPrerelease = package.IsPrerelease, - Language = NullIfEmpty(package.Language), - LicenseUrl = NullIfEmpty(package.LicenseUrlString), - Listed = package.Listed, - MinClientVersion = NullIfEmpty(package.MinClientVersion), - PackageHash = hash, - PackageHashAlgorithm = "SHA512", - PackageSize = size, - ProjectUrl = NullIfEmpty(package.ProjectUrlString), - ReleaseNotes = NullIfEmpty(package.ReleaseNotes), - RequireLicenseAcceptance = package.RequireLicenseAcceptance, - Summary = NullIfEmpty(package.Summary), - Tags = package.Tags?.ToList(), - Title = NullIfEmpty(package.Title), - }; - } + PackageId = id, + PackageVersion = version.ToNormalizedString(), + Published = timestamp, + }, + cancellationToken); + } + + internal static PackageDetailsCatalogLeaf BuildDetailsLeaf( + Package package, + string hash, + long size, + string commitId, + DateTimeOffset timestamp) + { + var published = new DateTimeOffset(DateTime.SpecifyKind(package.Published, DateTimeKind.Utc)); - /// - /// The next commit timestamp: now, truncated to milliseconds so that every database - /// provider stores it exactly, and always later than the previous commit. - /// - internal static DateTime NextTimestamp(DateTime now, DateTime? last) + return new PackageDetailsCatalogLeaf { - now = now.ToUniversalTime(); - var truncated = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerMillisecond, DateTimeKind.Utc); + Type = new[] { CatalogEntry.PackageDetailsType, "catalog:Permalink" }, + CommitId = commitId, + CommitTimestamp = timestamp, + PackageId = package.Id, + PackageVersion = package.NormalizedVersionString, + VerbatimVersion = package.OriginalVersionString ?? package.NormalizedVersionString, + Published = published, + Created = published, + LastEdited = timestamp, + Authors = string.Join(", ", package.Authors ?? Array.Empty()), + Description = package.Description, + DependencyGroups = RegistrationBuilder.ToDependencyGroups(package).ToList(), + IconUrl = NullIfEmpty(package.IconUrlString), + IsPrerelease = package.IsPrerelease, + Language = NullIfEmpty(package.Language), + LicenseUrl = NullIfEmpty(package.LicenseUrlString), + Listed = package.Listed, + MinClientVersion = NullIfEmpty(package.MinClientVersion), + PackageHash = hash, + PackageHashAlgorithm = "SHA512", + PackageSize = size, + ProjectUrl = NullIfEmpty(package.ProjectUrlString), + ReleaseNotes = NullIfEmpty(package.ReleaseNotes), + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + Summary = NullIfEmpty(package.Summary), + Tags = package.Tags?.ToList(), + Title = NullIfEmpty(package.Title), + }; + } - if (last.HasValue && truncated <= last.Value) - { - return last.Value.AddMilliseconds(1); - } + /// + /// The next commit timestamp: now, truncated to milliseconds so that every database + /// provider stores it exactly, and always later than the previous commit. + /// + internal static DateTime NextTimestamp(DateTime now, DateTime? last) + { + now = now.ToUniversalTime(); + var truncated = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerMillisecond, DateTimeKind.Utc); - return truncated; + if (last.HasValue && truncated <= last.Value) + { + return last.Value.AddMilliseconds(1); } - private async Task CommitAsync( - string type, - string id, - NuGetVersion version, - Func buildLeaf, - CancellationToken cancellationToken) + return truncated; + } + + private async Task CommitAsync( + string type, + string id, + NuGetVersion version, + Func buildLeaf, + CancellationToken cancellationToken) + { + await CommitLock.WaitAsync(cancellationToken); + try { - await CommitLock.WaitAsync(cancellationToken); - try - { - var last = await _catalog.GetLastCommitTimestampAsync(cancellationToken); - var timestamp = NextTimestamp(_time.UtcNow, last); - var commitId = Guid.NewGuid().ToString("D"); + var last = await _catalog.GetLastCommitTimestampAsync(cancellationToken); + var timestamp = NextTimestamp(_time.UtcNow, last); + var commitId = Guid.NewGuid().ToString("D"); - var leaf = buildLeaf(commitId, new DateTimeOffset(timestamp)); + var leaf = buildLeaf(commitId, new DateTimeOffset(timestamp)); - using (var content = new MemoryStream()) + using (var content = new MemoryStream()) + { + await JsonSerializer.SerializeAsync(content, leaf, leaf.GetType(), LeafSerializerOptions, cancellationToken); + content.Position = 0; + + var result = await _storage.PutAsync(LeafPath(commitId), content, "application/json", cancellationToken); + if (result == StoragePutResult.Conflict) { - await JsonSerializer.SerializeAsync(content, leaf, leaf.GetType(), LeafSerializerOptions, cancellationToken); - content.Position = 0; - - var result = await _storage.PutAsync(LeafPath(commitId), content, "application/json", cancellationToken); - if (result == StoragePutResult.Conflict) - { - throw new InvalidOperationException($"Catalog leaf {commitId} already exists with different content"); - } + throw new InvalidOperationException($"Catalog leaf {commitId} already exists with different content"); } - - await _catalog.AddAsync( - new CatalogEntry - { - CommitId = commitId, - CommitTimestamp = timestamp, - Type = type, - PackageId = id, - PackageVersion = version.ToNormalizedString(), - }, - cancellationToken); - - _logger.LogInformation( - "Committed catalog {Type} entry {CommitId} for {PackageId} {PackageVersion}", - type, - commitId, - id, - version); - } - finally - { - CommitLock.Release(); } - } - - private async Task<(string Hash, long Size)> HashPackageAsync(Package package, CancellationToken cancellationToken) - { - using var stream = await _packageStorage.GetPackageStreamAsync(package.Id, package.Version, cancellationToken); - using var counting = new CountingStream(stream); - using var sha512 = SHA512.Create(); - var hash = await sha512.ComputeHashAsync(counting, cancellationToken); + await _catalog.AddAsync( + new CatalogEntry + { + CommitId = commitId, + CommitTimestamp = timestamp, + Type = type, + PackageId = id, + PackageVersion = version.ToNormalizedString(), + }, + cancellationToken); - return (Convert.ToBase64String(hash), counting.BytesRead); + _logger.LogInformation( + "Committed catalog {Type} entry {CommitId} for {PackageId} {PackageVersion}", + type, + commitId, + id, + version); + } + finally + { + CommitLock.Release(); } + } + + private async Task<(string Hash, long Size)> HashPackageAsync(Package package, CancellationToken cancellationToken) + { + using var stream = await _packageStorage.GetPackageStreamAsync(package.Id, package.Version, cancellationToken); + using var counting = new CountingStream(stream); + using var sha512 = SHA512.Create(); - private static string NullIfEmpty(string value) => string.IsNullOrEmpty(value) ? null : value; + var hash = await sha512.ComputeHashAsync(counting, cancellationToken); - /// - /// Counts the bytes read through it, since a storage stream may not know its length. - /// - private sealed class CountingStream : Stream - { - private readonly Stream _source; + return (Convert.ToBase64String(hash), counting.BytesRead); + } - public CountingStream(Stream source) => _source = source; + private static string NullIfEmpty(string value) => string.IsNullOrEmpty(value) ? null : value; - public long BytesRead { get; private set; } + /// + /// Counts the bytes read through it, since a storage stream may not know its length. + /// + private sealed class CountingStream : Stream + { + private readonly Stream _source; - public override bool CanRead => true; - public override bool CanSeek => false; - public override bool CanWrite => false; - public override long Length => throw new NotSupportedException(); - public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public CountingStream(Stream source) => _source = source; - public override int Read(byte[] buffer, int offset, int count) - { - var read = _source.Read(buffer, offset, count); - BytesRead += read; - return read; - } + public long BytesRead { get; private set; } - public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) - { - var read = await _source.ReadAsync(buffer, cancellationToken); - BytesRead += read; - return read; - } + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + public override int Read(byte[] buffer, int offset, int count) + { + var read = _source.Read(buffer, offset, count); + BytesRead += read; + return read; + } - public override void Flush() { } - public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); - public override void SetLength(long value) => throw new NotSupportedException(); - public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var read = await _source.ReadAsync(buffer, cancellationToken); + BytesRead += read; + return read; } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Catalog/ICatalogDatabase.cs b/src/BaGet.Catalog/ICatalogDatabase.cs index dd6229119..38a5d44c8 100644 --- a/src/BaGet.Catalog/ICatalogDatabase.cs +++ b/src/BaGet.Catalog/ICatalogDatabase.cs @@ -4,36 +4,35 @@ using System.Threading.Tasks; using BaGet.Core; -namespace BaGet.Catalog +namespace BaGet.Catalog; + +/// +/// Where the catalog log is kept. +/// +public interface ICatalogDatabase { /// - /// Where the catalog log is kept. + /// False when the configured database cannot hold the catalog, such as Azure Table + /// storage. The catalog is then neither written nor advertised. /// - public interface ICatalogDatabase - { - /// - /// False when the configured database cannot hold the catalog, such as Azure Table - /// storage. The catalog is then neither written nor advertised. - /// - bool IsSupported { get; } + bool IsSupported { get; } - /// - /// The newest entry's commit timestamp, or null if the log is empty. - /// - Task GetLastCommitTimestampAsync(CancellationToken cancellationToken); + /// + /// The newest entry's commit timestamp, or null if the log is empty. + /// + Task GetLastCommitTimestampAsync(CancellationToken cancellationToken); - Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken); + Task AddAsync(CatalogEntry entry, CancellationToken cancellationToken); - /// - /// Every entry's commit timestamp, in commit order. Used to lay out the pages. - /// - Task> GetCommitTimestampsAsync(CancellationToken cancellationToken); + /// + /// Every entry's commit timestamp, in commit order. Used to lay out the pages. + /// + Task> GetCommitTimestampsAsync(CancellationToken cancellationToken); - /// - /// The entries in commit order, skipping . - /// - Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken); + /// + /// The entries in commit order, skipping . + /// + Task> GetEntriesAsync(int skip, int take, CancellationToken cancellationToken); - Task FindOrNullAsync(string commitId, CancellationToken cancellationToken); - } -} + Task FindOrNullAsync(string commitId, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Authentication/ApiKeyAuthenticationService.cs b/src/BaGet.Core/Authentication/ApiKeyAuthenticationService.cs index 99249d17c..47fddbf47 100644 --- a/src/BaGet.Core/Authentication/ApiKeyAuthenticationService.cs +++ b/src/BaGet.Core/Authentication/ApiKeyAuthenticationService.cs @@ -5,35 +5,34 @@ using System.Threading.Tasks; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +public class ApiKeyAuthenticationService : IAuthenticationService { - public class ApiKeyAuthenticationService : IAuthenticationService - { - private readonly byte[] _apiKey; + private readonly byte[] _apiKey; - public ApiKeyAuthenticationService(IOptionsSnapshot options) - { - if (options == null) throw new ArgumentNullException(nameof(options)); + public ApiKeyAuthenticationService(IOptionsSnapshot options) + { + if (options == null) throw new ArgumentNullException(nameof(options)); - _apiKey = string.IsNullOrEmpty(options.Value.ApiKey) - ? null - : Encoding.UTF8.GetBytes(options.Value.ApiKey); - } + _apiKey = string.IsNullOrEmpty(options.Value.ApiKey) + ? null + : Encoding.UTF8.GetBytes(options.Value.ApiKey); + } - public Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken) - => Task.FromResult(Authenticate(apiKey)); + public Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken) + => Task.FromResult(Authenticate(apiKey)); - private bool Authenticate(string apiKey) - { - // No authentication is necessary if there is no required API key. - if (_apiKey == null) return true; - if (string.IsNullOrEmpty(apiKey)) return false; + private bool Authenticate(string apiKey) + { + // No authentication is necessary if there is no required API key. + if (_apiKey == null) return true; + if (string.IsNullOrEmpty(apiKey)) return false; - // Compared in fixed time. An ordinary string comparison returns at the first - // differing character, so the time it takes says how much of the key was right, - // and a caller who can measure that can learn the key one character at a time. - // Only the length still leaks, which is what every fixed-time comparison does. - return CryptographicOperations.FixedTimeEquals(_apiKey, Encoding.UTF8.GetBytes(apiKey)); - } + // Compared in fixed time. An ordinary string comparison returns at the first + // differing character, so the time it takes says how much of the key was right, + // and a caller who can measure that can learn the key one character at a time. + // Only the length still leaks, which is what every fixed-time comparison does. + return CryptographicOperations.FixedTimeEquals(_apiKey, Encoding.UTF8.GetBytes(apiKey)); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Authentication/BaGetPrincipal.cs b/src/BaGet.Core/Authentication/BaGetPrincipal.cs index c27898ce3..638533da6 100644 --- a/src/BaGet.Core/Authentication/BaGetPrincipal.cs +++ b/src/BaGet.Core/Authentication/BaGetPrincipal.cs @@ -3,63 +3,62 @@ using System.Linq; using System.Text.RegularExpressions; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Who an API key authenticated, and what it may do. +/// +public sealed class BaGetPrincipal { /// - /// Who an API key authenticated, and what it may do. + /// The server's global API key, or any caller when no key is configured: it may do + /// anything to any package. /// - public sealed class BaGetPrincipal - { - /// - /// The server's global API key, or any caller when no key is configured: it may do - /// anything to any package. - /// - public static readonly BaGetPrincipal Superuser = new BaGetPrincipal( - userId: null, - userName: null, - isSuperuser: true, - scopes: ApiKeyScopes.All, - packageGlobPattern: "*"); + public static readonly BaGetPrincipal Superuser = new BaGetPrincipal( + userId: null, + userName: null, + isSuperuser: true, + scopes: ApiKeyScopes.All, + packageGlobPattern: "*"); - public BaGetPrincipal( - string userId, - string userName, - bool isSuperuser, - IReadOnlyList scopes, - string packageGlobPattern) - { - UserId = userId; - UserName = userName; - IsSuperuser = isSuperuser; - Scopes = scopes ?? Array.Empty(); - PackageGlobPattern = string.IsNullOrEmpty(packageGlobPattern) ? "*" : packageGlobPattern; - } + public BaGetPrincipal( + string userId, + string userName, + bool isSuperuser, + IReadOnlyList scopes, + string packageGlobPattern) + { + UserId = userId; + UserName = userName; + IsSuperuser = isSuperuser; + Scopes = scopes ?? Array.Empty(); + PackageGlobPattern = string.IsNullOrEmpty(packageGlobPattern) ? "*" : packageGlobPattern; + } - public string UserId { get; } + public string UserId { get; } - public string UserName { get; } + public string UserName { get; } - public bool IsSuperuser { get; } + public bool IsSuperuser { get; } - public IReadOnlyList Scopes { get; } + public IReadOnlyList Scopes { get; } - public string PackageGlobPattern { get; } + public string PackageGlobPattern { get; } - public bool HasScope(string scope) => IsSuperuser || Scopes.Contains(scope, StringComparer.Ordinal); + public bool HasScope(string scope) => IsSuperuser || Scopes.Contains(scope, StringComparer.Ordinal); - public bool MatchesPackage(string packageId) => IsSuperuser || GlobMatches(PackageGlobPattern, packageId); + public bool MatchesPackage(string packageId) => IsSuperuser || GlobMatches(PackageGlobPattern, packageId); - /// - /// Match a package ID against a glob in which "*" stands for any run of characters. - /// Package IDs are case insensitive, so the match is too. - /// - internal static bool GlobMatches(string pattern, string packageId) - { - if (packageId == null) return false; + /// + /// Match a package ID against a glob in which "*" stands for any run of characters. + /// Package IDs are case insensitive, so the match is too. + /// + internal static bool GlobMatches(string pattern, string packageId) + { + if (packageId == null) return false; - var regex = "^" + Regex.Escape(pattern).Replace("\\*", ".*") + "$"; + var regex = "^" + Regex.Escape(pattern).Replace("\\*", ".*") + "$"; - return Regex.IsMatch(packageId, regex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } + return Regex.IsMatch(packageId, regex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Authentication/IAuthenticationService.cs b/src/BaGet.Core/Authentication/IAuthenticationService.cs index a8c84be40..2e2bc9d6f 100644 --- a/src/BaGet.Core/Authentication/IAuthenticationService.cs +++ b/src/BaGet.Core/Authentication/IAuthenticationService.cs @@ -1,17 +1,16 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public interface IAuthenticationService { - public interface IAuthenticationService - { - Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken); + Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken); - /// - /// Who the API key authenticated, or null if it did not. An implementation that only - /// knows the global key reports every success as . - /// - async Task AuthenticatePrincipalAsync(string apiKey, CancellationToken cancellationToken) - => await AuthenticateAsync(apiKey, cancellationToken) ? BaGetPrincipal.Superuser : null; - } -} + /// + /// Who the API key authenticated, or null if it did not. An implementation that only + /// knows the global key reports every success as . + /// + async Task AuthenticatePrincipalAsync(string apiKey, CancellationToken cancellationToken) + => await AuthenticateAsync(apiKey, cancellationToken) ? BaGetPrincipal.Superuser : null; +} \ No newline at end of file diff --git a/src/BaGet.Core/Authentication/IPackageAuthorizationService.cs b/src/BaGet.Core/Authentication/IPackageAuthorizationService.cs index e31aaf0e9..821e58380 100644 --- a/src/BaGet.Core/Authentication/IPackageAuthorizationService.cs +++ b/src/BaGet.Core/Authentication/IPackageAuthorizationService.cs @@ -1,52 +1,51 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core -{ - public enum PackageAction - { - /// - /// Push a package or a symbol package. - /// - Push, +namespace BaGet.Core; - /// - /// Unlist, relist or delete a version, or edit its deprecation or vulnerabilities. - /// - Manage, - } +public enum PackageAction +{ + /// + /// Push a package or a symbol package. + /// + Push, /// - /// Decides whether an authenticated principal may act on a package ID. + /// Unlist, relist or delete a version, or edit its deprecation or vulnerabilities. /// - public interface IPackageAuthorizationService - { - Task AuthorizeAsync( - BaGetPrincipal principal, - PackageAction action, - string packageId, - CancellationToken cancellationToken); + Manage, +} - /// - /// Called after a successful push, so that a user pushing a new package ID becomes - /// its owner. - /// - Task OnPushedAsync(BaGetPrincipal principal, string packageId, CancellationToken cancellationToken); - } +/// +/// Decides whether an authenticated principal may act on a package ID. +/// +public interface IPackageAuthorizationService +{ + Task AuthorizeAsync( + BaGetPrincipal principal, + PackageAction action, + string packageId, + CancellationToken cancellationToken); /// - /// Without accounts every authenticated caller is the superuser, as it always was. + /// Called after a successful push, so that a user pushing a new package ID becomes + /// its owner. /// - public class AllowAuthenticatedAuthorizationService : IPackageAuthorizationService - { - public Task AuthorizeAsync( - BaGetPrincipal principal, - PackageAction action, - string packageId, - CancellationToken cancellationToken) - => Task.FromResult(principal != null); - - public Task OnPushedAsync(BaGetPrincipal principal, string packageId, CancellationToken cancellationToken) - => Task.CompletedTask; - } + Task OnPushedAsync(BaGetPrincipal principal, string packageId, CancellationToken cancellationToken); } + +/// +/// Without accounts every authenticated caller is the superuser, as it always was. +/// +public class AllowAuthenticatedAuthorizationService : IPackageAuthorizationService +{ + public Task AuthorizeAsync( + BaGetPrincipal principal, + PackageAction action, + string packageId, + CancellationToken cancellationToken) + => Task.FromResult(principal != null); + + public Task OnPushedAsync(BaGetPrincipal principal, string packageId, CancellationToken cancellationToken) + => Task.CompletedTask; +} \ No newline at end of file diff --git a/src/BaGet.Core/BaGetApplication.cs b/src/BaGet.Core/BaGetApplication.cs index 9894b41ad..b03f13c2c 100644 --- a/src/BaGet.Core/BaGetApplication.cs +++ b/src/BaGet.Core/BaGetApplication.cs @@ -1,15 +1,14 @@ using System; using Microsoft.Extensions.DependencyInjection; -namespace BaGet.Core +namespace BaGet.Core; + +public class BaGetApplication { - public class BaGetApplication + public BaGetApplication(IServiceCollection services) { - public BaGetApplication(IServiceCollection services) - { - Services = services ?? throw new ArgumentNullException(nameof(services)); - } - - public IServiceCollection Services { get; } + Services = services ?? throw new ArgumentNullException(nameof(services)); } -} + + public IServiceCollection Services { get; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/AccountsOptions.cs b/src/BaGet.Core/Configuration/AccountsOptions.cs index f8339867e..82e25dcc5 100644 --- a/src/BaGet.Core/Configuration/AccountsOptions.cs +++ b/src/BaGet.Core/Configuration/AccountsOptions.cs @@ -1,48 +1,47 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// User accounts, package owners and per-user API keys. +/// +public class AccountsOptions { /// - /// User accounts, package owners and per-user API keys. + /// Off by default, so that an upgraded server behaves exactly as before: only the + /// global authenticates. + /// + /// + /// While this is on, a caller must prove who they are: the global + /// if one is configured, otherwise a user's own key. + /// An unset means there is no global key, not that + /// the server is open - otherwise ownership, which is the point of accounts, could be + /// bypassed by sending no key at all. + /// + public bool Enabled { get; set; } + + /// + /// Whether anyone may create a local account from the sign-in page. /// - public class AccountsOptions - { - /// - /// Off by default, so that an upgraded server behaves exactly as before: only the - /// global authenticates. - /// - /// - /// While this is on, a caller must prove who they are: the global - /// if one is configured, otherwise a user's own key. - /// An unset means there is no global key, not that - /// the server is open - otherwise ownership, which is the point of accounts, could be - /// bypassed by sending no key at all. - /// - public bool Enabled { get; set; } - - /// - /// Whether anyone may create a local account from the sign-in page. - /// - public bool AllowRegistration { get; set; } = true; - - /// - /// An external OpenID Connect provider, such as Microsoft Entra ID. Unused unless - /// is set. - /// - public AccountsOpenIdConnectOptions OpenIdConnect { get; set; } = new AccountsOpenIdConnectOptions(); - } - - public class AccountsOpenIdConnectOptions - { - public string Authority { get; set; } - - public string ClientId { get; set; } - - public string ClientSecret { get; set; } - - /// - /// The provider's name on the sign-in button. - /// - public string DisplayName { get; set; } = "OpenID Connect"; - - public bool IsConfigured => !string.IsNullOrEmpty(Authority) && !string.IsNullOrEmpty(ClientId); - } + public bool AllowRegistration { get; set; } = true; + + /// + /// An external OpenID Connect provider, such as Microsoft Entra ID. Unused unless + /// is set. + /// + public AccountsOpenIdConnectOptions OpenIdConnect { get; set; } = new AccountsOpenIdConnectOptions(); } + +public class AccountsOpenIdConnectOptions +{ + public string Authority { get; set; } + + public string ClientId { get; set; } + + public string ClientSecret { get; set; } + + /// + /// The provider's name on the sign-in button. + /// + public string DisplayName { get; set; } = "OpenID Connect"; + + public bool IsConfigured => !string.IsNullOrEmpty(Authority) && !string.IsNullOrEmpty(ClientId); +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/BaGetOptions.cs b/src/BaGet.Core/Configuration/BaGetOptions.cs index 9ed0edcc3..11209f79d 100644 --- a/src/BaGet.Core/Configuration/BaGetOptions.cs +++ b/src/BaGet.Core/Configuration/BaGetOptions.cs @@ -1,76 +1,75 @@ using System.ComponentModel.DataAnnotations; -namespace BaGet.Core +namespace BaGet.Core; + +public class BaGetOptions { - public class BaGetOptions - { - /// - /// The API Key required to authenticate package - /// operations. If empty, package operations do not require authentication. - /// - public string ApiKey { get; set; } - - /// - /// The application root URL for usage in reverse proxy scenarios. - /// - public string PathBase { get; set; } - - /// - /// The host names BaGet will serve, separated by semicolons. A request whose - /// "Host" header matches none of them is rejected with a 400 response, before it - /// reaches a handler. An entry may be a wildcard subdomain ("*.example.com") and - /// may carry a port, in which case the port must match too; an entry without a - /// port matches any port. - /// - /// If empty, or if any entry is "*", every host is allowed. That is the default: - /// BaGet is commonly run behind a reverse proxy on a host name it cannot know. - /// - /// This is ASP.NET Core's own "AllowedHosts" configuration key, so an existing - /// value keeps working unchanged. - /// See: https://learn.microsoft.com/aspnet/core/fundamentals/servers/kestrel/host-filtering - /// - public string AllowedHosts { get; set; } - - /// - /// If enabled, the database will be updated at app startup by running - /// Entity Framework migrations. This is not recommended in production. - /// - public bool RunMigrationsAtStartup { get; set; } = true; - - /// - /// How BaGet should interpret package deletion requests. - /// - public PackageDeletionBehavior PackageDeletionBehavior { get; set; } = PackageDeletionBehavior.Unlist; - - /// - /// If enabled, pushing a package that already exists will replace the - /// existing package. - /// - public bool AllowPackageOverwrites { get; set; } = false; - - /// - /// If true, disables package pushing, deleting, and re-listing. - /// - public bool IsReadOnlyMode { get; set; } = false; - - /// - /// The URLs the BaGet server will use. - /// As per documentation here (Server URLs). - /// - public string Urls { get; set; } - - public DatabaseOptions Database { get; set; } - - public StorageOptions Storage { get; set; } - - public SearchOptions Search { get; set; } - - public MirrorOptions Mirror { get; set; } - - public FeedsOptions Feeds { get; set; } - - public AccountsOptions Accounts { get; set; } - - public ValidationOptions Validation { get; set; } - } -} + /// + /// The API Key required to authenticate package + /// operations. If empty, package operations do not require authentication. + /// + public string ApiKey { get; set; } + + /// + /// The application root URL for usage in reverse proxy scenarios. + /// + public string PathBase { get; set; } + + /// + /// The host names BaGet will serve, separated by semicolons. A request whose + /// "Host" header matches none of them is rejected with a 400 response, before it + /// reaches a handler. An entry may be a wildcard subdomain ("*.example.com") and + /// may carry a port, in which case the port must match too; an entry without a + /// port matches any port. + /// + /// If empty, or if any entry is "*", every host is allowed. That is the default: + /// BaGet is commonly run behind a reverse proxy on a host name it cannot know. + /// + /// This is ASP.NET Core's own "AllowedHosts" configuration key, so an existing + /// value keeps working unchanged. + /// See: https://learn.microsoft.com/aspnet/core/fundamentals/servers/kestrel/host-filtering + /// + public string AllowedHosts { get; set; } + + /// + /// If enabled, the database will be updated at app startup by running + /// Entity Framework migrations. This is not recommended in production. + /// + public bool RunMigrationsAtStartup { get; set; } = true; + + /// + /// How BaGet should interpret package deletion requests. + /// + public PackageDeletionBehavior PackageDeletionBehavior { get; set; } = PackageDeletionBehavior.Unlist; + + /// + /// If enabled, pushing a package that already exists will replace the + /// existing package. + /// + public bool AllowPackageOverwrites { get; set; } = false; + + /// + /// If true, disables package pushing, deleting, and re-listing. + /// + public bool IsReadOnlyMode { get; set; } = false; + + /// + /// The URLs the BaGet server will use. + /// As per documentation here (Server URLs). + /// + public string Urls { get; set; } + + public DatabaseOptions Database { get; set; } + + public StorageOptions Storage { get; set; } + + public SearchOptions Search { get; set; } + + public MirrorOptions Mirror { get; set; } + + public FeedsOptions Feeds { get; set; } + + public AccountsOptions Accounts { get; set; } + + public ValidationOptions Validation { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/BindOptions.cs b/src/BaGet.Core/Configuration/BindOptions.cs index ca6fd47a1..9c8d6fbdc 100644 --- a/src/BaGet.Core/Configuration/BindOptions.cs +++ b/src/BaGet.Core/Configuration/BindOptions.cs @@ -2,25 +2,24 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Automatically binds configs to options. +/// +/// The options to bind to. +public class BindOptions : IConfigureOptions where TOptions : class { + private readonly IConfiguration _config; + /// - /// Automatically binds configs to options. + /// Automatically bind these configurations to the options. /// - /// The options to bind to. - public class BindOptions : IConfigureOptions where TOptions : class + /// The configs to automatically bind to options. + public BindOptions(IConfiguration config) { - private readonly IConfiguration _config; - - /// - /// Automatically bind these configurations to the options. - /// - /// The configs to automatically bind to options. - public BindOptions(IConfiguration config) - { - _config = config ?? throw new ArgumentNullException(nameof(config)); - } - - public void Configure(TOptions options) => _config.Bind(options); + _config = config ?? throw new ArgumentNullException(nameof(config)); } -} + + public void Configure(TOptions options) => _config.Bind(options); +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/DatabaseOptions.cs b/src/BaGet.Core/Configuration/DatabaseOptions.cs index 1127f57f2..80d06636a 100644 --- a/src/BaGet.Core/Configuration/DatabaseOptions.cs +++ b/src/BaGet.Core/Configuration/DatabaseOptions.cs @@ -1,24 +1,23 @@ using System.ComponentModel.DataAnnotations; -namespace BaGet.Core +namespace BaGet.Core; + +public class DatabaseOptions { - public class DatabaseOptions - { - public string Type { get; set; } + public string Type { get; set; } - [Required] - public string ConnectionString { get; set; } + [Required] + public string ConnectionString { get; set; } - /// - /// The MySQL server version, such as "8.0.0-mysql" or "10.11.0-mariadb". Optional. - /// - /// - /// When this is not set, the version is detected by connecting to the server. Detection - /// happens while the database options are being built, which also happens when the - /// Entity Framework design-time tools enumerate the contexts, so an unreachable server - /// makes commands such as "dotnet ef migrations add" fail even for another provider. - /// Set this to keep option building offline. - /// - public string MySqlServerVersion { get; set; } - } -} + /// + /// The MySQL server version, such as "8.0.0-mysql" or "10.11.0-mariadb". Optional. + /// + /// + /// When this is not set, the version is detected by connecting to the server. Detection + /// happens while the database options are being built, which also happens when the + /// Entity Framework design-time tools enumerate the contexts, so an unreachable server + /// makes commands such as "dotnet ef migrations add" fail even for another provider. + /// Set this to keep option building offline. + /// + public string MySqlServerVersion { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/FeedsOptions.cs b/src/BaGet.Core/Configuration/FeedsOptions.cs index 90dc83d3e..2f59fdd7b 100644 --- a/src/BaGet.Core/Configuration/FeedsOptions.cs +++ b/src/BaGet.Core/Configuration/FeedsOptions.cs @@ -1,17 +1,16 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Which protocol surfaces BaGet exposes. +/// +public class FeedsOptions { /// - /// Which protocol surfaces BaGet exposes. + /// Whether the NuGet V2 (OData) feed is served under "api/v2". /// - public class FeedsOptions - { - /// - /// Whether the NuGet V2 (OData) feed is served under "api/v2". - /// - /// - /// On by default: clients that cannot speak V3 - "nuget list", older - /// Install-Package, and PowerShellGet - have no other way in. - /// - public bool EnableV2 { get; set; } = true; - } -} + /// + /// On by default: clients that cannot speak V3 - "nuget list", older + /// Install-Package, and PowerShellGet - have no other way in. + /// + public bool EnableV2 { get; set; } = true; +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/FileSystemStorageOptions.cs b/src/BaGet.Core/Configuration/FileSystemStorageOptions.cs index a74dba3dd..2adc6cdf6 100644 --- a/src/BaGet.Core/Configuration/FileSystemStorageOptions.cs +++ b/src/BaGet.Core/Configuration/FileSystemStorageOptions.cs @@ -3,26 +3,25 @@ using System.IO; using System.Linq; -namespace BaGet.Core +namespace BaGet.Core; + +public class FileSystemStorageOptions : IValidatableObject { - public class FileSystemStorageOptions : IValidatableObject - { - /// - /// The path at which content will be stored. Defaults to the same path - /// as the main BaGet executable. This path will be created if it does not - /// exist at startup. Packages will be stored in a subfolder named "packages". - /// - public string Path { get; set; } + /// + /// The path at which content will be stored. Defaults to the same path + /// as the main BaGet executable. This path will be created if it does not + /// exist at startup. Packages will be stored in a subfolder named "packages". + /// + public string Path { get; set; } - public IEnumerable Validate(ValidationContext validationContext) + public IEnumerable Validate(ValidationContext validationContext) + { + // Convert an empty storage path to the current working directory. + if (string.IsNullOrEmpty(Path)) { - // Convert an empty storage path to the current working directory. - if (string.IsNullOrEmpty(Path)) - { - Path = Directory.GetCurrentDirectory(); - } - - return Enumerable.Empty(); + Path = Directory.GetCurrentDirectory(); } + + return Enumerable.Empty(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/MirrorOptions.cs b/src/BaGet.Core/Configuration/MirrorOptions.cs index 09db895d3..9c299207e 100644 --- a/src/BaGet.Core/Configuration/MirrorOptions.cs +++ b/src/BaGet.Core/Configuration/MirrorOptions.cs @@ -2,40 +2,39 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -namespace BaGet.Core +namespace BaGet.Core; + +public class MirrorOptions : IValidatableObject { - public class MirrorOptions : IValidatableObject - { - /// - /// If true, packages that aren't found locally will be indexed - /// using the upstream source. - /// - public bool Enabled { get; set; } + /// + /// If true, packages that aren't found locally will be indexed + /// using the upstream source. + /// + public bool Enabled { get; set; } - /// - /// The v3 index that will be mirrored. - /// - public Uri PackageSource { get; set; } + /// + /// The v3 index that will be mirrored. + /// + public Uri PackageSource { get; set; } - /// - /// Whether or not the package source is a v2 package source feed. - /// - public bool Legacy { get; set; } + /// + /// Whether or not the package source is a v2 package source feed. + /// + public bool Legacy { get; set; } - /// - /// The time before a download from the package source times out. - /// - [Range(0, int.MaxValue)] - public int PackageDownloadTimeoutSeconds { get; set; } = 600; + /// + /// The time before a download from the package source times out. + /// + [Range(0, int.MaxValue)] + public int PackageDownloadTimeoutSeconds { get; set; } = 600; - public IEnumerable Validate(ValidationContext validationContext) + public IEnumerable Validate(ValidationContext validationContext) + { + if (Enabled && PackageSource == null) { - if (Enabled && PackageSource == null) - { - yield return new ValidationResult( - $"The {nameof(PackageSource)} configuration is required if mirroring is enabled", - new[] { nameof(PackageSource) }); - } + yield return new ValidationResult( + $"The {nameof(PackageSource)} configuration is required if mirroring is enabled", + new[] { nameof(PackageSource) }); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/PackageDeletionBehavior.cs b/src/BaGet.Core/Configuration/PackageDeletionBehavior.cs index 01c68d7ff..0f6b45420 100644 --- a/src/BaGet.Core/Configuration/PackageDeletionBehavior.cs +++ b/src/BaGet.Core/Configuration/PackageDeletionBehavior.cs @@ -1,22 +1,21 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// How BaGet should interpret package deletion requests. +/// See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package +/// +public enum PackageDeletionBehavior { /// - /// How BaGet should interpret package deletion requests. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#delete-a-package + /// Package "deletions" make the package undiscoverable. The package is still restorable + /// by consumers that know its id and version. This is the recommended behavior as it prevents + /// the "left pad" problem. /// - public enum PackageDeletionBehavior - { - /// - /// Package "deletions" make the package undiscoverable. The package is still restorable - /// by consumers that know its id and version. This is the recommended behavior as it prevents - /// the "left pad" problem. - /// - Unlist, + Unlist, - /// - /// Removes the package from the database and storage. Existing consumers will no longer - /// be able to restore the package. - /// - HardDelete, - } -} + /// + /// Removes the package from the database and storage. Existing consumers will no longer + /// be able to restore the package. + /// + HardDelete, +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/SearchOptions.cs b/src/BaGet.Core/Configuration/SearchOptions.cs index 52f430cb8..6822f85d0 100644 --- a/src/BaGet.Core/Configuration/SearchOptions.cs +++ b/src/BaGet.Core/Configuration/SearchOptions.cs @@ -1,7 +1,6 @@ -namespace BaGet.Core +namespace BaGet.Core; + +public class SearchOptions { - public class SearchOptions - { - public string Type { get; set; } - } -} + public string Type { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/StorageOptions.cs b/src/BaGet.Core/Configuration/StorageOptions.cs index be8c8a5db..f3fe03c5c 100644 --- a/src/BaGet.Core/Configuration/StorageOptions.cs +++ b/src/BaGet.Core/Configuration/StorageOptions.cs @@ -1,7 +1,6 @@ -namespace BaGet.Core +namespace BaGet.Core; + +public class StorageOptions { - public class StorageOptions - { - public string Type { get; set; } - } -} + public string Type { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Configuration/ValidationOptions.cs b/src/BaGet.Core/Configuration/ValidationOptions.cs index 5f837e1af..0654a432c 100644 --- a/src/BaGet.Core/Configuration/ValidationOptions.cs +++ b/src/BaGet.Core/Configuration/ValidationOptions.cs @@ -1,37 +1,36 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Asynchronous validation of pushed packages. +/// +public class ValidationOptions { /// - /// Asynchronous validation of pushed packages. + /// Off by default. With it off a push is indexed at once, exactly as before. + /// With it on, a push answers 202 Accepted and the package appears once every + /// validator has passed; a package that fails is quarantined, never served. /// - public class ValidationOptions - { - /// - /// Off by default. With it off a push is indexed at once, exactly as before. - /// With it on, a push answers 202 Accepted and the package appears once every - /// validator has passed; a package that fails is quarantined, never served. - /// - public bool Enabled { get; set; } + public bool Enabled { get; set; } - /// - /// Reject packages without a valid author or repository signature. - /// - public bool RequireSignedPackages { get; set; } + /// + /// Reject packages without a valid author or repository signature. + /// + public bool RequireSignedPackages { get; set; } - /// - /// A PFX file whose certificate repository-signs every package that passes - /// validation. Unused unless set; the RepositorySignatures resource is only - /// advertised when it is. - /// - public string RepositorySigningCertificatePath { get; set; } + /// + /// A PFX file whose certificate repository-signs every package that passes + /// validation. Unused unless set; the RepositorySignatures resource is only + /// advertised when it is. + /// + public string RepositorySigningCertificatePath { get; set; } - public string RepositorySigningCertificatePassword { get; set; } + public string RepositorySigningCertificatePassword { get; set; } - /// - /// This server's public service index URL, recorded in every repository signature; - /// a client checks it against the source it restored from. Required for signing, - /// since signing runs in the background, outside any request to read it from, and - /// it must be https: NuGet rejects a repository signature for any other scheme. - /// - public string RepositorySigningServiceIndexUrl { get; set; } - } -} + /// + /// This server's public service index URL, recorded in every repository signature; + /// a client checks it against the source it restored from. Required for signing, + /// since signing runs in the background, outside any request to read it from, and + /// it must be https: NuGet rejects a repository signature for any other scheme. + /// + public string RepositorySigningServiceIndexUrl { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Content/DefaultPackageContentService.cs b/src/BaGet.Core/Content/DefaultPackageContentService.cs index 8d0a76d13..7093fa04f 100644 --- a/src/BaGet.Core/Content/DefaultPackageContentService.cs +++ b/src/BaGet.Core/Content/DefaultPackageContentService.cs @@ -6,87 +6,86 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Implements the NuGet Package Content resource in NuGet's V3 protocol. +/// +public class DefaultPackageContentService : IPackageContentService { - /// - /// Implements the NuGet Package Content resource in NuGet's V3 protocol. - /// - public class DefaultPackageContentService : IPackageContentService + private readonly IPackageService _packages; + private readonly IPackageStorageService _storage; + + public DefaultPackageContentService( + IPackageService packages, + IPackageStorageService storage) { - private readonly IPackageService _packages; - private readonly IPackageStorageService _storage; + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + } - public DefaultPackageContentService( - IPackageService packages, - IPackageStorageService storage) + public async Task GetPackageVersionsOrNullAsync( + string id, + CancellationToken cancellationToken = default) + { + var versions = await _packages.FindPackageVersionsAsync(id, cancellationToken); + if (!versions.Any()) { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + return null; } - public async Task GetPackageVersionsOrNullAsync( - string id, - CancellationToken cancellationToken = default) + return new PackageVersionsResponse { - var versions = await _packages.FindPackageVersionsAsync(id, cancellationToken); - if (!versions.Any()) - { - return null; - } - - return new PackageVersionsResponse - { - Versions = versions - .Select(v => v.ToNormalizedString()) - .Select(v => v.ToLowerInvariant()) - .ToList() - }; - } + Versions = versions + .Select(v => v.ToNormalizedString()) + .Select(v => v.ToLowerInvariant()) + .ToList() + }; + } - public async Task GetPackageContentStreamOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken = default) + public async Task GetPackageContentStreamOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken = default) + { + if (!await _packages.ExistsAsync(id, version, cancellationToken)) { - if (!await _packages.ExistsAsync(id, version, cancellationToken)) - { - return null; - } - - await _packages.AddDownloadAsync(id, version, cancellationToken); - return await _storage.GetPackageStreamAsync(id, version, cancellationToken); + return null; } - public async Task GetPackageManifestStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) - { - if (!await _packages.ExistsAsync(id, version, cancellationToken)) - { - return null; - } + await _packages.AddDownloadAsync(id, version, cancellationToken); + return await _storage.GetPackageStreamAsync(id, version, cancellationToken); + } - return await _storage.GetNuspecStreamAsync(id, version, cancellationToken); + public async Task GetPackageManifestStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) + { + if (!await _packages.ExistsAsync(id, version, cancellationToken)) + { + return null; } - public async Task GetPackageReadmeStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) - { - var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); - if (package == null || !package.HasReadme) - { - return null; - } + return await _storage.GetNuspecStreamAsync(id, version, cancellationToken); + } - return await _storage.GetReadmeStreamAsync(id, version, cancellationToken); + public async Task GetPackageReadmeStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) + { + var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); + if (package == null || !package.HasReadme) + { + return null; } - public async Task GetPackageIconStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) - { - var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); - if (package == null || !package.HasEmbeddedIcon) - { - return null; - } + return await _storage.GetReadmeStreamAsync(id, version, cancellationToken); + } - return await _storage.GetIconStreamAsync(id, version, cancellationToken); + public async Task GetPackageIconStreamOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken = default) + { + var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); + if (package == null || !package.HasEmbeddedIcon) + { + return null; } + + return await _storage.GetIconStreamAsync(id, version, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Content/IPackageContentService.cs b/src/BaGet.Core/Content/IPackageContentService.cs index 31abcafdd..4e7df239f 100644 --- a/src/BaGet.Core/Content/IPackageContentService.cs +++ b/src/BaGet.Core/Content/IPackageContentService.cs @@ -4,82 +4,81 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The Package Content resource, used to download NuGet packages and to fetch other metadata. +/// +/// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource +/// +public interface IPackageContentService { /// - /// The Package Content resource, used to download NuGet packages and to fetch other metadata. - /// - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource + /// Get a package's versions, or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions /// - public interface IPackageContentService - { - /// - /// Get a package's versions, or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions - /// - /// The package ID. - /// A token to cancel the task. - /// The package's versions, or null if the package does not exist. - Task GetPackageVersionsOrNullAsync( - string packageId, - CancellationToken cancellationToken); + /// The package ID. + /// A token to cancel the task. + /// The package's versions, or null if the package does not exist. + Task GetPackageVersionsOrNullAsync( + string packageId, + CancellationToken cancellationToken); - /// - /// Download a package, or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg - /// - /// The package ID. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's content stream, or null if the package does not exist. The stream may not be seekable. - /// - Task GetPackageContentStreamOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken); + /// + /// Download a package, or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg + /// + /// The package ID. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's content stream, or null if the package does not exist. The stream may not be seekable. + /// + Task GetPackageContentStreamOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken); - /// - /// Download a package's manifest (nuspec), or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec - /// - /// The package id. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's manifest stream, or null if the package does not exist. The stream may not be seekable. - /// - Task GetPackageManifestStreamOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken); + /// + /// Download a package's manifest (nuspec), or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec + /// + /// The package id. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's manifest stream, or null if the package does not exist. The stream may not be seekable. + /// + Task GetPackageManifestStreamOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken); - /// - /// Download a package's readme, or null if the package or readme does not exist. - /// - /// The package id. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's readme stream, or null if the package or readme does not exist. The stream may not be seekable. - /// - Task GetPackageReadmeStreamOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken); + /// + /// Download a package's readme, or null if the package or readme does not exist. + /// + /// The package id. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's readme stream, or null if the package or readme does not exist. The stream may not be seekable. + /// + Task GetPackageReadmeStreamOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken); - /// - /// Download a package's icon, or null if the package or icon does not exist. - /// - /// The package id. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's icon stream, or null if the package or icon does not exist. The stream may not be seekable. - /// - Task GetPackageIconStreamOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken); - } -} + /// + /// Download a package's icon, or null if the package or icon does not exist. + /// + /// The package id. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's icon stream, or null if the package or icon does not exist. The stream may not be seekable. + /// + Task GetPackageIconStreamOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/AbstractContext.cs b/src/BaGet.Core/Entities/AbstractContext.cs index b4804d4f0..1c328abf8 100644 --- a/src/BaGet.Core/Entities/AbstractContext.cs +++ b/src/BaGet.Core/Entities/AbstractContext.cs @@ -4,324 +4,323 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Identity's tables live in the same database as the packages, so a deployment keeps +/// one database. They are created by a migration whether or not accounts are enabled. +/// +public abstract class AbstractContext : IdentityDbContext, IContext where TContext : DbContext { - /// - /// Identity's tables live in the same database as the packages, so a deployment keeps - /// one database. They are created by a migration whether or not accounts are enabled. - /// - public abstract class AbstractContext : IdentityDbContext, IContext where TContext : DbContext + public const int DefaultMaxStringLength = 4000; + + public const int MaxPackageIdLength = 128; + public const int MaxPackageVersionLength = 64; + public const int MaxPackageMinClientVersionLength = 44; + public const int MaxPackageLanguageLength = 20; + public const int MaxPackageTitleLength = 256; + public const int MaxPackageTypeNameLength = 512; + public const int MaxPackageTypeVersionLength = 64; + public const int MaxRepositoryTypeLength = 100; + public const int MaxTargetFrameworkLength = 256; + + public const int MaxPackageDependencyVersionRangeLength = 256; + + public const int MaxCatalogCommitIdLength = 36; + public const int MaxCatalogTypeLength = 32; + + public const int MaxAccountNameLength = 256; + public const int MaxUserIdLength = 450; + public const int MaxApiKeyDescriptionLength = 256; + public const int MaxApiKeyHashLength = 64; + + public const int MaxValidationTypeLength = 64; + + public const int MaxAbuseReasonLength = 128; + public const int MaxEmailLength = 256; + + public AbstractContext(DbContextOptions options) + : base(options) + { } + + public DbSet Packages { get; set; } + public DbSet PackageDependencies { get; set; } + public DbSet PackageTypes { get; set; } + public DbSet TargetFrameworks { get; set; } + public DbSet PackageDeprecations { get; set; } + public DbSet PackageVulnerabilities { get; set; } + public DbSet CatalogLeafs { get; set; } + public DbSet Organizations { get; set; } + public DbSet OrganizationMembers { get; set; } + public DbSet PackageOwners { get; set; } + public DbSet ApiKeys { get; set; } + public DbSet PackageValidations { get; set; } + public DbSet AbuseReports { get; set; } + + public Task SaveChangesAsync() => SaveChangesAsync(default); + + public virtual async Task RunMigrationsAsync(CancellationToken cancellationToken) + => await Database.MigrateAsync(cancellationToken); + + public abstract bool IsUniqueConstraintViolationException(DbUpdateException exception); + + public virtual bool SupportsLimitInSubqueries => true; + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + builder.Entity(BuildPackageEntity); + builder.Entity(BuildPackageDependencyEntity); + builder.Entity(BuildPackageTypeEntity); + builder.Entity(BuildTargetFrameworkEntity); + builder.Entity(BuildPackageDeprecationEntity); + builder.Entity(BuildPackageVulnerabilityEntity); + builder.Entity(BuildCatalogEntryEntity); + builder.Entity(BuildOrganizationEntity); + builder.Entity(BuildOrganizationMemberEntity); + builder.Entity(BuildPackageOwnerEntity); + builder.Entity(BuildApiKeyEntity); + builder.Entity(BuildPackageValidationEntity); + builder.Entity(BuildAbuseReportEntity); + } + + private void BuildPackageEntity(EntityTypeBuilder package) + { + package.HasKey(p => p.Key); + package.HasIndex(p => p.Id); + package.HasIndex(p => new { p.Id, p.NormalizedVersionString }) + .IsUnique(); + + package.Property(p => p.Id) + .HasMaxLength(MaxPackageIdLength) + .IsRequired(); + + package.Property(p => p.NormalizedVersionString) + .HasColumnName("Version") + .HasMaxLength(MaxPackageVersionLength) + .IsRequired(); + + package.Property(p => p.OriginalVersionString) + .HasColumnName("OriginalVersion") + .HasMaxLength(MaxPackageVersionLength); + + package.Property(p => p.ReleaseNotes) + .HasColumnName("ReleaseNotes"); + + package.Property(p => p.Authors) + .HasMaxLength(DefaultMaxStringLength) + .HasConversion(StringArrayToJsonConverter.Instance) + .Metadata.SetValueComparer(StringArrayComparer.Instance); + + package.Property(p => p.IconUrl) + .HasConversion(UriToStringConverter.Instance) + .HasMaxLength(DefaultMaxStringLength); + + package.Property(p => p.LicenseUrl) + .HasConversion(UriToStringConverter.Instance) + .HasMaxLength(DefaultMaxStringLength); + + package.Property(p => p.ProjectUrl) + .HasConversion(UriToStringConverter.Instance) + .HasMaxLength(DefaultMaxStringLength); + + package.Property(p => p.RepositoryUrl) + .HasConversion(UriToStringConverter.Instance) + .HasMaxLength(DefaultMaxStringLength); + + package.Property(p => p.Tags) + .HasMaxLength(DefaultMaxStringLength) + .HasConversion(StringArrayToJsonConverter.Instance) + .Metadata.SetValueComparer(StringArrayComparer.Instance); + + package.Property(p => p.Description).HasMaxLength(DefaultMaxStringLength); + package.Property(p => p.Language).HasMaxLength(MaxPackageLanguageLength); + package.Property(p => p.MinClientVersion).HasMaxLength(MaxPackageMinClientVersionLength); + package.Property(p => p.Summary).HasMaxLength(DefaultMaxStringLength); + package.Property(p => p.Title).HasMaxLength(MaxPackageTitleLength); + package.Property(p => p.RepositoryType).HasMaxLength(MaxRepositoryTypeLength); + + package.Ignore(p => p.Version); + package.Ignore(p => p.IconUrlString); + package.Ignore(p => p.LicenseUrlString); + package.Ignore(p => p.ProjectUrlString); + package.Ignore(p => p.RepositoryUrlString); + + // The dependency to package relationship is deliberately left optional. Making it + // required, or giving it a cascade delete, changes the foreign key and so needs a + // migration; SQLite cannot alter a foreign key, so consumers would have to + // recreate their database and reindex every package. PackageDatabase therefore + // deletes a package's dependency rows itself, so that none are left orphaned. + // See: https://github.com/loic-sharma/BaGet/pull/174 + + package.HasMany(p => p.PackageTypes) + .WithOne(d => d.Package) + .IsRequired(); + + package.HasMany(p => p.TargetFrameworks) + .WithOne(d => d.Package) + .IsRequired(); + + package.Property(p => p.RowVersion).IsRowVersion(); + } + + private void BuildPackageDeprecationEntity(EntityTypeBuilder deprecation) + { + deprecation.HasKey(d => d.Key); + + deprecation + .Property(d => d.Reasons) + .HasMaxLength(DefaultMaxStringLength) + .HasConversion(StringArrayToJsonConverter.Instance) + .Metadata.SetValueComparer(StringArrayComparer.Instance); + + deprecation.Property(d => d.Message).HasMaxLength(DefaultMaxStringLength); + deprecation.Property(d => d.AlternatePackageId).HasMaxLength(MaxPackageIdLength); + deprecation.Property(d => d.AlternateVersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); + + // A version has at most one deprecation. The relationship is optional in the + // database for the same reason as the dependency one: a required relationship + // would need a foreign key change, which SQLite cannot make in place. + // The foreign key is declared explicitly: for a one to one relationship EF + // cannot otherwise tell which side is the dependent. + deprecation + .HasOne(d => d.Package) + .WithOne(p => p.Deprecation) + .HasForeignKey(d => d.PackageKey) + .IsRequired(false); + } + + private void BuildPackageVulnerabilityEntity(EntityTypeBuilder vulnerability) + { + vulnerability.HasKey(v => v.Key); + + vulnerability.Property(v => v.AdvisoryUrl).HasMaxLength(DefaultMaxStringLength); + vulnerability.Property(v => v.VersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); + + vulnerability + .HasOne(v => v.Package) + .WithMany(p => p.Vulnerabilities) + .HasForeignKey(v => v.PackageKey) + .IsRequired(false); + } + + private void BuildCatalogEntryEntity(EntityTypeBuilder entry) + { + entry.HasKey(e => e.Key); + entry.HasIndex(e => e.CommitId).IsUnique(); + + entry.Property(e => e.CommitId).HasMaxLength(MaxCatalogCommitIdLength).IsRequired(); + entry.Property(e => e.Type).HasMaxLength(MaxCatalogTypeLength).IsRequired(); + entry.Property(e => e.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + entry.Property(e => e.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + } + + private void BuildOrganizationEntity(EntityTypeBuilder organization) { - public const int DefaultMaxStringLength = 4000; - - public const int MaxPackageIdLength = 128; - public const int MaxPackageVersionLength = 64; - public const int MaxPackageMinClientVersionLength = 44; - public const int MaxPackageLanguageLength = 20; - public const int MaxPackageTitleLength = 256; - public const int MaxPackageTypeNameLength = 512; - public const int MaxPackageTypeVersionLength = 64; - public const int MaxRepositoryTypeLength = 100; - public const int MaxTargetFrameworkLength = 256; - - public const int MaxPackageDependencyVersionRangeLength = 256; - - public const int MaxCatalogCommitIdLength = 36; - public const int MaxCatalogTypeLength = 32; - - public const int MaxAccountNameLength = 256; - public const int MaxUserIdLength = 450; - public const int MaxApiKeyDescriptionLength = 256; - public const int MaxApiKeyHashLength = 64; - - public const int MaxValidationTypeLength = 64; - - public const int MaxAbuseReasonLength = 128; - public const int MaxEmailLength = 256; - - public AbstractContext(DbContextOptions options) - : base(options) - { } - - public DbSet Packages { get; set; } - public DbSet PackageDependencies { get; set; } - public DbSet PackageTypes { get; set; } - public DbSet TargetFrameworks { get; set; } - public DbSet PackageDeprecations { get; set; } - public DbSet PackageVulnerabilities { get; set; } - public DbSet CatalogLeafs { get; set; } - public DbSet Organizations { get; set; } - public DbSet OrganizationMembers { get; set; } - public DbSet PackageOwners { get; set; } - public DbSet ApiKeys { get; set; } - public DbSet PackageValidations { get; set; } - public DbSet AbuseReports { get; set; } - - public Task SaveChangesAsync() => SaveChangesAsync(default); - - public virtual async Task RunMigrationsAsync(CancellationToken cancellationToken) - => await Database.MigrateAsync(cancellationToken); - - public abstract bool IsUniqueConstraintViolationException(DbUpdateException exception); - - public virtual bool SupportsLimitInSubqueries => true; - - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - builder.Entity(BuildPackageEntity); - builder.Entity(BuildPackageDependencyEntity); - builder.Entity(BuildPackageTypeEntity); - builder.Entity(BuildTargetFrameworkEntity); - builder.Entity(BuildPackageDeprecationEntity); - builder.Entity(BuildPackageVulnerabilityEntity); - builder.Entity(BuildCatalogEntryEntity); - builder.Entity(BuildOrganizationEntity); - builder.Entity(BuildOrganizationMemberEntity); - builder.Entity(BuildPackageOwnerEntity); - builder.Entity(BuildApiKeyEntity); - builder.Entity(BuildPackageValidationEntity); - builder.Entity(BuildAbuseReportEntity); - } - - private void BuildPackageEntity(EntityTypeBuilder package) - { - package.HasKey(p => p.Key); - package.HasIndex(p => p.Id); - package.HasIndex(p => new { p.Id, p.NormalizedVersionString }) - .IsUnique(); - - package.Property(p => p.Id) - .HasMaxLength(MaxPackageIdLength) - .IsRequired(); - - package.Property(p => p.NormalizedVersionString) - .HasColumnName("Version") - .HasMaxLength(MaxPackageVersionLength) - .IsRequired(); - - package.Property(p => p.OriginalVersionString) - .HasColumnName("OriginalVersion") - .HasMaxLength(MaxPackageVersionLength); - - package.Property(p => p.ReleaseNotes) - .HasColumnName("ReleaseNotes"); - - package.Property(p => p.Authors) - .HasMaxLength(DefaultMaxStringLength) - .HasConversion(StringArrayToJsonConverter.Instance) - .Metadata.SetValueComparer(StringArrayComparer.Instance); - - package.Property(p => p.IconUrl) - .HasConversion(UriToStringConverter.Instance) - .HasMaxLength(DefaultMaxStringLength); - - package.Property(p => p.LicenseUrl) - .HasConversion(UriToStringConverter.Instance) - .HasMaxLength(DefaultMaxStringLength); - - package.Property(p => p.ProjectUrl) - .HasConversion(UriToStringConverter.Instance) - .HasMaxLength(DefaultMaxStringLength); - - package.Property(p => p.RepositoryUrl) - .HasConversion(UriToStringConverter.Instance) - .HasMaxLength(DefaultMaxStringLength); - - package.Property(p => p.Tags) - .HasMaxLength(DefaultMaxStringLength) - .HasConversion(StringArrayToJsonConverter.Instance) - .Metadata.SetValueComparer(StringArrayComparer.Instance); - - package.Property(p => p.Description).HasMaxLength(DefaultMaxStringLength); - package.Property(p => p.Language).HasMaxLength(MaxPackageLanguageLength); - package.Property(p => p.MinClientVersion).HasMaxLength(MaxPackageMinClientVersionLength); - package.Property(p => p.Summary).HasMaxLength(DefaultMaxStringLength); - package.Property(p => p.Title).HasMaxLength(MaxPackageTitleLength); - package.Property(p => p.RepositoryType).HasMaxLength(MaxRepositoryTypeLength); - - package.Ignore(p => p.Version); - package.Ignore(p => p.IconUrlString); - package.Ignore(p => p.LicenseUrlString); - package.Ignore(p => p.ProjectUrlString); - package.Ignore(p => p.RepositoryUrlString); - - // The dependency to package relationship is deliberately left optional. Making it - // required, or giving it a cascade delete, changes the foreign key and so needs a - // migration; SQLite cannot alter a foreign key, so consumers would have to - // recreate their database and reindex every package. PackageDatabase therefore - // deletes a package's dependency rows itself, so that none are left orphaned. - // See: https://github.com/loic-sharma/BaGet/pull/174 - - package.HasMany(p => p.PackageTypes) - .WithOne(d => d.Package) - .IsRequired(); - - package.HasMany(p => p.TargetFrameworks) - .WithOne(d => d.Package) - .IsRequired(); - - package.Property(p => p.RowVersion).IsRowVersion(); - } - - private void BuildPackageDeprecationEntity(EntityTypeBuilder deprecation) - { - deprecation.HasKey(d => d.Key); - - deprecation - .Property(d => d.Reasons) - .HasMaxLength(DefaultMaxStringLength) - .HasConversion(StringArrayToJsonConverter.Instance) - .Metadata.SetValueComparer(StringArrayComparer.Instance); - - deprecation.Property(d => d.Message).HasMaxLength(DefaultMaxStringLength); - deprecation.Property(d => d.AlternatePackageId).HasMaxLength(MaxPackageIdLength); - deprecation.Property(d => d.AlternateVersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); - - // A version has at most one deprecation. The relationship is optional in the - // database for the same reason as the dependency one: a required relationship - // would need a foreign key change, which SQLite cannot make in place. - // The foreign key is declared explicitly: for a one to one relationship EF - // cannot otherwise tell which side is the dependent. - deprecation - .HasOne(d => d.Package) - .WithOne(p => p.Deprecation) - .HasForeignKey(d => d.PackageKey) - .IsRequired(false); - } - - private void BuildPackageVulnerabilityEntity(EntityTypeBuilder vulnerability) - { - vulnerability.HasKey(v => v.Key); - - vulnerability.Property(v => v.AdvisoryUrl).HasMaxLength(DefaultMaxStringLength); - vulnerability.Property(v => v.VersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); - - vulnerability - .HasOne(v => v.Package) - .WithMany(p => p.Vulnerabilities) - .HasForeignKey(v => v.PackageKey) - .IsRequired(false); - } - - private void BuildCatalogEntryEntity(EntityTypeBuilder entry) - { - entry.HasKey(e => e.Key); - entry.HasIndex(e => e.CommitId).IsUnique(); - - entry.Property(e => e.CommitId).HasMaxLength(MaxCatalogCommitIdLength).IsRequired(); - entry.Property(e => e.Type).HasMaxLength(MaxCatalogTypeLength).IsRequired(); - entry.Property(e => e.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); - entry.Property(e => e.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); - } - - private void BuildOrganizationEntity(EntityTypeBuilder organization) - { - organization.HasKey(o => o.Key); - organization.HasIndex(o => o.Name).IsUnique(); - - organization.Property(o => o.Name).HasMaxLength(MaxAccountNameLength).IsRequired(); - } - - private void BuildOrganizationMemberEntity(EntityTypeBuilder member) - { - member.HasKey(m => m.Key); - member.HasIndex(m => m.UserId); - - member.Property(m => m.UserId).HasMaxLength(MaxUserIdLength).IsRequired(); - - member - .HasOne(m => m.Organization) - .WithMany() - .HasForeignKey(m => m.OrganizationKey) - .IsRequired(false); - } - - private void BuildPackageOwnerEntity(EntityTypeBuilder owner) - { - owner.HasKey(o => o.Key); - owner.HasIndex(o => o.PackageId); - owner.HasIndex(o => o.OwnerName); - - owner.Property(o => o.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); - owner.Property(o => o.OwnerName).HasMaxLength(MaxAccountNameLength).IsRequired(); - } - - private void BuildApiKeyEntity(EntityTypeBuilder apiKey) - { - apiKey.HasKey(k => k.Key); - apiKey.HasIndex(k => k.HashedKey).IsUnique(); - apiKey.HasIndex(k => k.UserId); - - apiKey.Property(k => k.UserId).HasMaxLength(MaxUserIdLength).IsRequired(); - apiKey.Property(k => k.Description).HasMaxLength(MaxApiKeyDescriptionLength); - apiKey.Property(k => k.HashedKey).HasMaxLength(MaxApiKeyHashLength).IsRequired(); - apiKey.Property(k => k.PackageGlobPattern).HasMaxLength(MaxPackageIdLength); - - apiKey - .Property(k => k.Scopes) - .HasMaxLength(DefaultMaxStringLength) - .HasConversion(StringArrayToJsonConverter.Instance) - .Metadata.SetValueComparer(StringArrayComparer.Instance); - } - - private void BuildPackageValidationEntity(EntityTypeBuilder validation) - { - validation.HasKey(v => v.Key); - validation.HasIndex(v => v.SubmissionId); - validation.HasIndex(v => v.PackageId); - - validation.Property(v => v.SubmissionId).HasMaxLength(MaxCatalogCommitIdLength).IsRequired(); - validation.Property(v => v.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); - validation.Property(v => v.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); - validation.Property(v => v.Type).HasMaxLength(MaxValidationTypeLength).IsRequired(); - validation.Property(v => v.Message).HasMaxLength(DefaultMaxStringLength); - - validation - .HasOne(v => v.Package) - .WithMany() - .HasForeignKey(v => v.PackageKey) - .IsRequired(false); - } - - private void BuildAbuseReportEntity(EntityTypeBuilder report) - { - report.HasKey(r => r.Key); - report.HasIndex(r => r.PackageId); - - report.Property(r => r.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); - report.Property(r => r.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); - report.Property(r => r.Reason).HasMaxLength(MaxAbuseReasonLength).IsRequired(); - report.Property(r => r.Details).HasMaxLength(DefaultMaxStringLength).IsRequired(); - report.Property(r => r.ReporterEmail).HasMaxLength(MaxEmailLength); - } - - private void BuildPackageDependencyEntity(EntityTypeBuilder dependency) - { - dependency.HasKey(d => d.Key); - dependency.HasIndex(d => d.Id); - - dependency.Property(d => d.Id).HasMaxLength(MaxPackageIdLength); - dependency.Property(d => d.VersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); - dependency.Property(d => d.TargetFramework).HasMaxLength(MaxTargetFrameworkLength); - } - - private void BuildPackageTypeEntity(EntityTypeBuilder type) - { - type.HasKey(d => d.Key); - type.HasIndex(d => d.Name); - - type.Property(d => d.Name).HasMaxLength(MaxPackageTypeNameLength); - type.Property(d => d.Version).HasMaxLength(MaxPackageTypeVersionLength); - } - - private void BuildTargetFrameworkEntity(EntityTypeBuilder targetFramework) - { - targetFramework.HasKey(f => f.Key); - targetFramework.HasIndex(f => f.Moniker); - - targetFramework.Property(f => f.Moniker).HasMaxLength(MaxTargetFrameworkLength); - } + organization.HasKey(o => o.Key); + organization.HasIndex(o => o.Name).IsUnique(); + + organization.Property(o => o.Name).HasMaxLength(MaxAccountNameLength).IsRequired(); + } + + private void BuildOrganizationMemberEntity(EntityTypeBuilder member) + { + member.HasKey(m => m.Key); + member.HasIndex(m => m.UserId); + + member.Property(m => m.UserId).HasMaxLength(MaxUserIdLength).IsRequired(); + + member + .HasOne(m => m.Organization) + .WithMany() + .HasForeignKey(m => m.OrganizationKey) + .IsRequired(false); + } + + private void BuildPackageOwnerEntity(EntityTypeBuilder owner) + { + owner.HasKey(o => o.Key); + owner.HasIndex(o => o.PackageId); + owner.HasIndex(o => o.OwnerName); + + owner.Property(o => o.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + owner.Property(o => o.OwnerName).HasMaxLength(MaxAccountNameLength).IsRequired(); + } + + private void BuildApiKeyEntity(EntityTypeBuilder apiKey) + { + apiKey.HasKey(k => k.Key); + apiKey.HasIndex(k => k.HashedKey).IsUnique(); + apiKey.HasIndex(k => k.UserId); + + apiKey.Property(k => k.UserId).HasMaxLength(MaxUserIdLength).IsRequired(); + apiKey.Property(k => k.Description).HasMaxLength(MaxApiKeyDescriptionLength); + apiKey.Property(k => k.HashedKey).HasMaxLength(MaxApiKeyHashLength).IsRequired(); + apiKey.Property(k => k.PackageGlobPattern).HasMaxLength(MaxPackageIdLength); + + apiKey + .Property(k => k.Scopes) + .HasMaxLength(DefaultMaxStringLength) + .HasConversion(StringArrayToJsonConverter.Instance) + .Metadata.SetValueComparer(StringArrayComparer.Instance); + } + + private void BuildPackageValidationEntity(EntityTypeBuilder validation) + { + validation.HasKey(v => v.Key); + validation.HasIndex(v => v.SubmissionId); + validation.HasIndex(v => v.PackageId); + + validation.Property(v => v.SubmissionId).HasMaxLength(MaxCatalogCommitIdLength).IsRequired(); + validation.Property(v => v.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + validation.Property(v => v.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + validation.Property(v => v.Type).HasMaxLength(MaxValidationTypeLength).IsRequired(); + validation.Property(v => v.Message).HasMaxLength(DefaultMaxStringLength); + + validation + .HasOne(v => v.Package) + .WithMany() + .HasForeignKey(v => v.PackageKey) + .IsRequired(false); + } + + private void BuildAbuseReportEntity(EntityTypeBuilder report) + { + report.HasKey(r => r.Key); + report.HasIndex(r => r.PackageId); + + report.Property(r => r.PackageId).HasMaxLength(MaxPackageIdLength).IsRequired(); + report.Property(r => r.PackageVersion).HasMaxLength(MaxPackageVersionLength).IsRequired(); + report.Property(r => r.Reason).HasMaxLength(MaxAbuseReasonLength).IsRequired(); + report.Property(r => r.Details).HasMaxLength(DefaultMaxStringLength).IsRequired(); + report.Property(r => r.ReporterEmail).HasMaxLength(MaxEmailLength); + } + + private void BuildPackageDependencyEntity(EntityTypeBuilder dependency) + { + dependency.HasKey(d => d.Key); + dependency.HasIndex(d => d.Id); + + dependency.Property(d => d.Id).HasMaxLength(MaxPackageIdLength); + dependency.Property(d => d.VersionRange).HasMaxLength(MaxPackageDependencyVersionRangeLength); + dependency.Property(d => d.TargetFramework).HasMaxLength(MaxTargetFrameworkLength); + } + + private void BuildPackageTypeEntity(EntityTypeBuilder type) + { + type.HasKey(d => d.Key); + type.HasIndex(d => d.Name); + + type.Property(d => d.Name).HasMaxLength(MaxPackageTypeNameLength); + type.Property(d => d.Version).HasMaxLength(MaxPackageTypeVersionLength); + } + + private void BuildTargetFrameworkEntity(EntityTypeBuilder targetFramework) + { + targetFramework.HasKey(f => f.Key); + targetFramework.HasIndex(f => f.Moniker); + + targetFramework.Property(f => f.Moniker).HasMaxLength(MaxTargetFrameworkLength); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/AbuseReport.cs b/src/BaGet.Core/Entities/AbuseReport.cs index 19f6363f8..f5fe693fe 100644 --- a/src/BaGet.Core/Entities/AbuseReport.cs +++ b/src/BaGet.Core/Entities/AbuseReport.cs @@ -1,41 +1,40 @@ using System; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A report that a package version is abusive, for its owners and the server's +/// administrator to act on. +/// +public class AbuseReport { /// - /// A report that a package version is abusive, for its owners and the server's - /// administrator to act on. + /// The reasons a report may give, as nuget.org offers them. /// - public class AbuseReport + public static readonly string[] Reasons = { - /// - /// The reasons a report may give, as nuget.org offers them. - /// - public static readonly string[] Reasons = - { - "Contains malicious code", - "Violates a license or copyright", - "Contains private or confidential data", - "Other", - }; + "Contains malicious code", + "Violates a license or copyright", + "Contains private or confidential data", + "Other", + }; - public int Key { get; set; } + public int Key { get; set; } - public string PackageId { get; set; } + public string PackageId { get; set; } - public string PackageVersion { get; set; } + public string PackageVersion { get; set; } - public string Reason { get; set; } + public string Reason { get; set; } - public string Details { get; set; } + public string Details { get; set; } - /// - /// Where to reply, if the reporter gave an address. - /// - public string ReporterEmail { get; set; } + /// + /// Where to reply, if the reporter gave an address. + /// + public string ReporterEmail { get; set; } - public DateTime Created { get; set; } + public DateTime Created { get; set; } - public DateTime? Resolved { get; set; } - } -} + public DateTime? Resolved { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Accounts.cs b/src/BaGet.Core/Entities/Accounts.cs index dde25ac53..9b06d517c 100644 --- a/src/BaGet.Core/Entities/Accounts.cs +++ b/src/BaGet.Core/Entities/Accounts.cs @@ -1,127 +1,126 @@ using System; using Microsoft.AspNetCore.Identity; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A signed in user. User names and organization names share one namespace, since +/// either can own a package. +/// +public class BaGetUser : IdentityUser +{ + public DateTime Created { get; set; } +} + +/// +/// An account that several users own packages through. +/// +public class Organization +{ + public int Key { get; set; } + + public string Name { get; set; } + + public DateTime Created { get; set; } +} + +public class OrganizationMember { + public int Key { get; set; } + + /// + /// Nullable so that the relationship is additive; see . + /// + public int? OrganizationKey { get; set; } + + public Organization Organization { get; set; } + /// - /// A signed in user. User names and organization names share one namespace, since - /// either can own a package. + /// The member's . /// - public class BaGetUser : IdentityUser - { - public DateTime Created { get; set; } - } + public string UserId { get; set; } /// - /// An account that several users own packages through. + /// An administrator can add and remove members. /// - public class Organization - { - public int Key { get; set; } + public bool IsAdmin { get; set; } +} - public string Name { get; set; } +/// +/// An owner of every version of a package ID. +/// +/// +/// A package ID with no owners predates accounts, and only the server's global API key +/// may change it. +/// +public class PackageOwner +{ + public int Key { get; set; } - public DateTime Created { get; set; } - } + public string PackageId { get; set; } - public class OrganizationMember - { - public int Key { get; set; } + /// + /// A user name or an organization name. + /// + public string OwnerName { get; set; } - /// - /// Nullable so that the relationship is additive; see . - /// - public int? OrganizationKey { get; set; } + /// + /// Set by the server's administrator to mark the ID as reserved for this owner, + /// which search reports as "verified". + /// + public bool IsVerified { get; set; } +} - public Organization Organization { get; set; } +/// +/// A user's API key. Only a hash of the key is kept. +/// +public class ApiKey +{ + public int Key { get; set; } - /// - /// The member's . - /// - public string UserId { get; set; } + public string UserId { get; set; } - /// - /// An administrator can add and remove members. - /// - public bool IsAdmin { get; set; } - } + public string Description { get; set; } /// - /// An owner of every version of a package ID. + /// The key's SHA-256 hash, as lowercase hex. /// - /// - /// A package ID with no owners predates accounts, and only the server's global API key - /// may change it. - /// - public class PackageOwner - { - public int Key { get; set; } - - public string PackageId { get; set; } - - /// - /// A user name or an organization name. - /// - public string OwnerName { get; set; } - - /// - /// Set by the server's administrator to mark the ID as reserved for this owner, - /// which search reports as "verified". - /// - public bool IsVerified { get; set; } - } + public string HashedKey { get; set; } /// - /// A user's API key. Only a hash of the key is kept. + /// What the key may do; see . /// - public class ApiKey - { - public int Key { get; set; } + public string[] Scopes { get; set; } - public string UserId { get; set; } - - public string Description { get; set; } - - /// - /// The key's SHA-256 hash, as lowercase hex. - /// - public string HashedKey { get; set; } + /// + /// The package IDs the key applies to, with "*" as a wildcard. + /// + public string PackageGlobPattern { get; set; } - /// - /// What the key may do; see . - /// - public string[] Scopes { get; set; } + public DateTime Created { get; set; } - /// - /// The package IDs the key applies to, with "*" as a wildcard. - /// - public string PackageGlobPattern { get; set; } + public DateTime? Expires { get; set; } +} - public DateTime Created { get; set; } +/// +/// The scopes an may hold, named as nuget.org names them. +/// +public static class ApiKeyScopes +{ + /// + /// Push new package IDs and new versions of owned ones. + /// + public const string Push = "package:push"; - public DateTime? Expires { get; set; } - } + /// + /// Push new versions of owned package IDs only. + /// + public const string PushVersion = "package:pushversion"; /// - /// The scopes an may hold, named as nuget.org names them. + /// Unlist and relist owned versions, and edit their deprecation and vulnerabilities. /// - public static class ApiKeyScopes - { - /// - /// Push new package IDs and new versions of owned ones. - /// - public const string Push = "package:push"; - - /// - /// Push new versions of owned package IDs only. - /// - public const string PushVersion = "package:pushversion"; - - /// - /// Unlist and relist owned versions, and edit their deprecation and vulnerabilities. - /// - public const string Unlist = "package:unlist"; - - public static readonly string[] All = { Push, PushVersion, Unlist }; - } -} + public const string Unlist = "package:unlist"; + + public static readonly string[] All = { Push, PushVersion, Unlist }; +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/CatalogEntry.cs b/src/BaGet.Core/Entities/CatalogEntry.cs index 4417d7c5c..6c27ab13a 100644 --- a/src/BaGet.Core/Entities/CatalogEntry.cs +++ b/src/BaGet.Core/Entities/CatalogEntry.cs @@ -1,43 +1,42 @@ using System; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// One entry in the append-only catalog log: a package version was added or changed, +/// or was deleted. +/// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource +/// +/// +/// There is deliberately no foreign key to : the log outlives the +/// packages it records, and a delete entry refers to a package that no longer exists. +/// +public class CatalogEntry { + public const string PackageDetailsType = "PackageDetails"; + public const string PackageDeleteType = "PackageDelete"; + + public int Key { get; set; } + + /// + /// The commit's unique ID. It also names the leaf document in storage. + /// + public string CommitId { get; set; } + + /// + /// When the entry was committed, in UTC. Strictly increasing in commit order. + /// + public DateTime CommitTimestamp { get; set; } + + /// + /// or . + /// + public string Type { get; set; } + + public string PackageId { get; set; } + /// - /// One entry in the append-only catalog log: a package version was added or changed, - /// or was deleted. - /// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource + /// The normalized version. /// - /// - /// There is deliberately no foreign key to : the log outlives the - /// packages it records, and a delete entry refers to a package that no longer exists. - /// - public class CatalogEntry - { - public const string PackageDetailsType = "PackageDetails"; - public const string PackageDeleteType = "PackageDelete"; - - public int Key { get; set; } - - /// - /// The commit's unique ID. It also names the leaf document in storage. - /// - public string CommitId { get; set; } - - /// - /// When the entry was committed, in UTC. Strictly increasing in commit order. - /// - public DateTime CommitTimestamp { get; set; } - - /// - /// or . - /// - public string Type { get; set; } - - public string PackageId { get; set; } - - /// - /// The normalized version. - /// - public string PackageVersion { get; set; } - } -} + public string PackageVersion { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Converters/StringArrayComparer.cs b/src/BaGet.Core/Entities/Converters/StringArrayComparer.cs index e76bcc626..fe769d645 100644 --- a/src/BaGet.Core/Entities/Converters/StringArrayComparer.cs +++ b/src/BaGet.Core/Entities/Converters/StringArrayComparer.cs @@ -2,18 +2,17 @@ using System.Linq; using Microsoft.EntityFrameworkCore.ChangeTracking; -namespace BaGet.Core +namespace BaGet.Core; + +public class StringArrayComparer : ValueComparer { - public class StringArrayComparer : ValueComparer - { - public static readonly StringArrayComparer Instance = new StringArrayComparer(); + public static readonly StringArrayComparer Instance = new StringArrayComparer(); - public StringArrayComparer() - : base( - (c1, c2) => c1.SequenceEqual(c2), - c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), - c => c.ToArray()) - { - } + public StringArrayComparer() + : base( + (c1, c2) => c1.SequenceEqual(c2), + c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())), + c => c.ToArray()) + { } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Converters/StringArrayToJsonConverter.cs b/src/BaGet.Core/Entities/Converters/StringArrayToJsonConverter.cs index 0991d1c3c..bc95e409a 100644 --- a/src/BaGet.Core/Entities/Converters/StringArrayToJsonConverter.cs +++ b/src/BaGet.Core/Entities/Converters/StringArrayToJsonConverter.cs @@ -1,17 +1,16 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Newtonsoft.Json; -namespace BaGet.Core +namespace BaGet.Core; + +public class StringArrayToJsonConverter : ValueConverter { - public class StringArrayToJsonConverter : ValueConverter - { - public static readonly StringArrayToJsonConverter Instance = new StringArrayToJsonConverter(); + public static readonly StringArrayToJsonConverter Instance = new StringArrayToJsonConverter(); - public StringArrayToJsonConverter() - : base( - v => JsonConvert.SerializeObject(v), - v => (!string.IsNullOrEmpty(v)) ? JsonConvert.DeserializeObject(v) : new string[0]) - { - } + public StringArrayToJsonConverter() + : base( + v => JsonConvert.SerializeObject(v), + v => (!string.IsNullOrEmpty(v)) ? JsonConvert.DeserializeObject(v) : new string[0]) + { } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Converters/UriToStringConverter.cs b/src/BaGet.Core/Entities/Converters/UriToStringConverter.cs index d8ace4a68..5c198c6c4 100644 --- a/src/BaGet.Core/Entities/Converters/UriToStringConverter.cs +++ b/src/BaGet.Core/Entities/Converters/UriToStringConverter.cs @@ -1,17 +1,16 @@ using System; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -namespace BaGet.Core +namespace BaGet.Core; + +public class UriToStringConverter : ValueConverter { - public class UriToStringConverter : ValueConverter - { - public static readonly UriToStringConverter Instance = new UriToStringConverter(); + public static readonly UriToStringConverter Instance = new UriToStringConverter(); - public UriToStringConverter() - : base( - v => v.AbsoluteUri, - v => new Uri(v)) - { - } + public UriToStringConverter() + : base( + v => v.AbsoluteUri, + v => new Uri(v)) + { } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/IContext.cs b/src/BaGet.Core/Entities/IContext.cs index b60c496b0..c853fcd08 100644 --- a/src/BaGet.Core/Entities/IContext.cs +++ b/src/BaGet.Core/Entities/IContext.cs @@ -3,71 +3,70 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace BaGet.Core +namespace BaGet.Core; + +public interface IContext { - public interface IContext - { - DatabaseFacade Database { get; } + DatabaseFacade Database { get; } - DbSet Packages { get; set; } + DbSet Packages { get; set; } - /// - /// The dependencies declared by packages. A dependency belongs to the package that - /// declares it, but the relationship is optional in the database, so deleting a - /// package does not delete them. - /// - DbSet PackageDependencies { get; set; } + /// + /// The dependencies declared by packages. A dependency belongs to the package that + /// declares it, but the relationship is optional in the database, so deleting a + /// package does not delete them. + /// + DbSet PackageDependencies { get; set; } - /// - /// The deprecations of package versions. - /// - DbSet PackageDeprecations { get; set; } + /// + /// The deprecations of package versions. + /// + DbSet PackageDeprecations { get; set; } - /// - /// The known vulnerabilities affecting package versions. - /// - DbSet PackageVulnerabilities { get; set; } + /// + /// The known vulnerabilities affecting package versions. + /// + DbSet PackageVulnerabilities { get; set; } - DbSet CatalogLeafs { get; set; } + DbSet CatalogLeafs { get; set; } - DbSet Organizations { get; set; } + DbSet Organizations { get; set; } - DbSet OrganizationMembers { get; set; } + DbSet OrganizationMembers { get; set; } - DbSet PackageOwners { get; set; } + DbSet PackageOwners { get; set; } - DbSet ApiKeys { get; set; } + DbSet ApiKeys { get; set; } - DbSet PackageValidations { get; set; } + DbSet PackageValidations { get; set; } - DbSet AbuseReports { get; set; } + DbSet AbuseReports { get; set; } - /// - /// Identity's users. Declared here so that account services can query them through - /// the same context as everything else. - /// - DbSet Users { get; set; } + /// + /// Identity's users. Declared here so that account services can query them through + /// the same context as everything else. + /// + DbSet Users { get; set; } - /// - /// Check whether a is due to a SQL unique constraint violation. - /// - /// The exception to inspect. - /// Whether the exception was caused to SQL unique constraint violation. - bool IsUniqueConstraintViolationException(DbUpdateException exception); + /// + /// Check whether a is due to a SQL unique constraint violation. + /// + /// The exception to inspect. + /// Whether the exception was caused to SQL unique constraint violation. + bool IsUniqueConstraintViolationException(DbUpdateException exception); - /// - /// Whether this database engine supports LINQ "Take" in subqueries. - /// - bool SupportsLimitInSubqueries { get; } + /// + /// Whether this database engine supports LINQ "Take" in subqueries. + /// + bool SupportsLimitInSubqueries { get; } - Task SaveChangesAsync(CancellationToken cancellationToken); + Task SaveChangesAsync(CancellationToken cancellationToken); - /// - /// Applies any pending migrations for the context to the database. - /// Creates the database if it does not already exist. - /// - /// A token to cancel the task. - /// A task that completes once migrations are applied. - Task RunMigrationsAsync(CancellationToken cancellationToken); - } -} + /// + /// Applies any pending migrations for the context to the database. + /// Creates the database if it does not already exist. + /// + /// A token to cancel the task. + /// A task that completes once migrations are applied. + Task RunMigrationsAsync(CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/NullContext.cs b/src/BaGet.Core/Entities/NullContext.cs index af364593c..71c7d2a85 100644 --- a/src/BaGet.Core/Entities/NullContext.cs +++ b/src/BaGet.Core/Entities/NullContext.cs @@ -4,51 +4,50 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -namespace BaGet.Core +namespace BaGet.Core; + +public class NullContext : IContext { - public class NullContext : IContext - { - public DatabaseFacade Database => throw new NotImplementedException(); + public DatabaseFacade Database => throw new NotImplementedException(); - public DbSet Packages { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet Packages { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet PackageDependencies { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet PackageDependencies { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet PackageDeprecations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet PackageDeprecations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet PackageVulnerabilities { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet PackageVulnerabilities { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet CatalogLeafs { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet CatalogLeafs { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet Organizations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet Organizations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet OrganizationMembers { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet OrganizationMembers { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet PackageOwners { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet PackageOwners { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet ApiKeys { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet ApiKeys { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet PackageValidations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet PackageValidations { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet AbuseReports { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet AbuseReports { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public DbSet Users { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public DbSet Users { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - public bool SupportsLimitInSubqueries => throw new NotImplementedException(); + public bool SupportsLimitInSubqueries => throw new NotImplementedException(); - public bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - throw new NotImplementedException(); - } + public bool IsUniqueConstraintViolationException(DbUpdateException exception) + { + throw new NotImplementedException(); + } - public Task RunMigrationsAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task RunMigrationsAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } - public Task SaveChangesAsync(CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } + public Task SaveChangesAsync(CancellationToken cancellationToken) + { + throw new NotImplementedException(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/Package.cs b/src/BaGet.Core/Entities/Package.cs index 7802d5403..ddb7937b5 100644 --- a/src/BaGet.Core/Entities/Package.cs +++ b/src/BaGet.Core/Entities/Package.cs @@ -2,102 +2,101 @@ using System.Collections.Generic; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +// See NuGetGallery's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/Package.cs +public class Package { - // See NuGetGallery's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/Package.cs - public class Package - { - public int Key { get; set; } + public int Key { get; set; } - public string Id { get; set; } + public string Id { get; set; } - public NuGetVersion Version + public NuGetVersion Version + { + get { - get - { - // Favor the original version string as it contains more information. - // Packages uploaded with older versions of BaGet may not have the original version string. - return NuGetVersion.Parse( - OriginalVersionString != null - ? OriginalVersionString - : NormalizedVersionString); - } - - set - { - NormalizedVersionString = value.ToNormalizedString().ToLowerInvariant(); - OriginalVersionString = value.OriginalVersion; - } + // Favor the original version string as it contains more information. + // Packages uploaded with older versions of BaGet may not have the original version string. + return NuGetVersion.Parse( + OriginalVersionString != null + ? OriginalVersionString + : NormalizedVersionString); } - public string[] Authors { get; set; } - public string Description { get; set; } - public long Downloads { get; set; } - public bool HasReadme { get; set; } - public bool HasEmbeddedIcon { get; set; } - public bool IsPrerelease { get; set; } - public string ReleaseNotes { get; set; } - public string Language { get; set; } - public bool Listed { get; set; } - public string MinClientVersion { get; set; } - - /// - /// The time at which the package was published, in UTC. - /// - /// - /// Always stored as UTC. The database returns a whose - /// is , which would - /// otherwise be read as local time when converted to a , - /// shifting the published timestamp by the server's UTC offset. - /// - public DateTime Published + set { - get => DateTime.SpecifyKind(_published, DateTimeKind.Utc); - set => _published = value; + NormalizedVersionString = value.ToNormalizedString().ToLowerInvariant(); + OriginalVersionString = value.OriginalVersion; } + } - private DateTime _published; + public string[] Authors { get; set; } + public string Description { get; set; } + public long Downloads { get; set; } + public bool HasReadme { get; set; } + public bool HasEmbeddedIcon { get; set; } + public bool IsPrerelease { get; set; } + public string ReleaseNotes { get; set; } + public string Language { get; set; } + public bool Listed { get; set; } + public string MinClientVersion { get; set; } + + /// + /// The time at which the package was published, in UTC. + /// + /// + /// Always stored as UTC. The database returns a whose + /// is , which would + /// otherwise be read as local time when converted to a , + /// shifting the published timestamp by the server's UTC offset. + /// + public DateTime Published + { + get => DateTime.SpecifyKind(_published, DateTimeKind.Utc); + set => _published = value; + } - public bool RequireLicenseAcceptance { get; set; } - public SemVerLevel SemVerLevel { get; set; } - public string Summary { get; set; } - public string Title { get; set; } + private DateTime _published; - public Uri IconUrl { get; set; } - public Uri LicenseUrl { get; set; } - public Uri ProjectUrl { get; set; } + public bool RequireLicenseAcceptance { get; set; } + public SemVerLevel SemVerLevel { get; set; } + public string Summary { get; set; } + public string Title { get; set; } - public Uri RepositoryUrl { get; set; } - public string RepositoryType { get; set; } + public Uri IconUrl { get; set; } + public Uri LicenseUrl { get; set; } + public Uri ProjectUrl { get; set; } - public string[] Tags { get; set; } + public Uri RepositoryUrl { get; set; } + public string RepositoryType { get; set; } - /// - /// Used for optimistic concurrency. - /// - public byte[] RowVersion { get; set; } + public string[] Tags { get; set; } - public List Dependencies { get; set; } - public List PackageTypes { get; set; } - public List TargetFrameworks { get; set; } + /// + /// Used for optimistic concurrency. + /// + public byte[] RowVersion { get; set; } - /// - /// The deprecation of this version, or null if it is not deprecated. - /// - public PackageDeprecation Deprecation { get; set; } + public List Dependencies { get; set; } + public List PackageTypes { get; set; } + public List TargetFrameworks { get; set; } - /// - /// The known vulnerabilities affecting this version. - /// - public List Vulnerabilities { get; set; } + /// + /// The deprecation of this version, or null if it is not deprecated. + /// + public PackageDeprecation Deprecation { get; set; } - public string NormalizedVersionString { get; set; } - public string OriginalVersionString { get; set; } + /// + /// The known vulnerabilities affecting this version. + /// + public List Vulnerabilities { get; set; } + public string NormalizedVersionString { get; set; } + public string OriginalVersionString { get; set; } - public string IconUrlString => IconUrl?.AbsoluteUri ?? string.Empty; - public string LicenseUrlString => LicenseUrl?.AbsoluteUri ?? string.Empty; - public string ProjectUrlString => ProjectUrl?.AbsoluteUri ?? string.Empty; - public string RepositoryUrlString => RepositoryUrl?.AbsoluteUri ?? string.Empty; - } -} + + public string IconUrlString => IconUrl?.AbsoluteUri ?? string.Empty; + public string LicenseUrlString => LicenseUrl?.AbsoluteUri ?? string.Empty; + public string ProjectUrlString => ProjectUrl?.AbsoluteUri ?? string.Empty; + public string RepositoryUrlString => RepositoryUrl?.AbsoluteUri ?? string.Empty; +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageDependency.cs b/src/BaGet.Core/Entities/PackageDependency.cs index 7ae6f61cd..08f4794a0 100644 --- a/src/BaGet.Core/Entities/PackageDependency.cs +++ b/src/BaGet.Core/Entities/PackageDependency.cs @@ -1,22 +1,21 @@ -namespace BaGet.Core +namespace BaGet.Core; + +// See NuGetGallery.Core's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/PackageDependency.cs +public class PackageDependency { - // See NuGetGallery.Core's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/PackageDependency.cs - public class PackageDependency - { - public int Key { get; set; } + public int Key { get; set; } - /// - /// The dependency's package ID. Null if this is a dependency group without any dependencies. - /// - public string Id { get; set; } + /// + /// The dependency's package ID. Null if this is a dependency group without any dependencies. + /// + public string Id { get; set; } - /// - /// The dependency's package version. Null if this is a dependency group without any dependencies. - /// - public string VersionRange { get; set; } + /// + /// The dependency's package version. Null if this is a dependency group without any dependencies. + /// + public string VersionRange { get; set; } - public string TargetFramework { get; set; } + public string TargetFramework { get; set; } - public Package Package { get; set; } - } -} + public Package Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageDeprecation.cs b/src/BaGet.Core/Entities/PackageDeprecation.cs index 1c8008ce9..462200aca 100644 --- a/src/BaGet.Core/Entities/PackageDeprecation.cs +++ b/src/BaGet.Core/Entities/PackageDeprecation.cs @@ -1,50 +1,49 @@ using System.Collections.Generic; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A package version marked as deprecated. +/// See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation +/// +public class PackageDeprecation { /// - /// A package version marked as deprecated. + /// The deprecation reasons the protocol defines. /// See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation /// - public class PackageDeprecation - { - /// - /// The deprecation reasons the protocol defines. - /// See: https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation - /// - public static readonly IReadOnlyList KnownReasons = new[] { "Legacy", "CriticalBugs", "Other" }; - - public int Key { get; set; } - - /// - /// Why the package was deprecated. The protocol defines "Legacy", "CriticalBugs" - /// and "Other"; a package may carry more than one. - /// - public string[] Reasons { get; set; } - - /// - /// Free text explaining the deprecation. Optional. - /// - public string Message { get; set; } - - /// - /// The ID of the package to use instead. Null if none was suggested. - /// - public string AlternatePackageId { get; set; } - - /// - /// The versions of the alternate package that may be used, or "*" for any. - /// Null if no alternate package was suggested. - /// - public string AlternateVersionRange { get; set; } - - /// - /// The key of the deprecated package version. Nullable so that the relationship - /// stays optional in the database: a required one would need a foreign key change, - /// which SQLite cannot make in place. - /// - public int? PackageKey { get; set; } - - public Package Package { get; set; } - } -} + public static readonly IReadOnlyList KnownReasons = new[] { "Legacy", "CriticalBugs", "Other" }; + + public int Key { get; set; } + + /// + /// Why the package was deprecated. The protocol defines "Legacy", "CriticalBugs" + /// and "Other"; a package may carry more than one. + /// + public string[] Reasons { get; set; } + + /// + /// Free text explaining the deprecation. Optional. + /// + public string Message { get; set; } + + /// + /// The ID of the package to use instead. Null if none was suggested. + /// + public string AlternatePackageId { get; set; } + + /// + /// The versions of the alternate package that may be used, or "*" for any. + /// Null if no alternate package was suggested. + /// + public string AlternateVersionRange { get; set; } + + /// + /// The key of the deprecated package version. Nullable so that the relationship + /// stays optional in the database: a required one would need a foreign key change, + /// which SQLite cannot make in place. + /// + public int? PackageKey { get; set; } + + public Package Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageType.cs b/src/BaGet.Core/Entities/PackageType.cs index 4e67d694b..6a3b9617d 100644 --- a/src/BaGet.Core/Entities/PackageType.cs +++ b/src/BaGet.Core/Entities/PackageType.cs @@ -1,13 +1,12 @@ -namespace BaGet.Core +namespace BaGet.Core; + +// See NuGetGallery.Core's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/PackageType.cs +public class PackageType { - // See NuGetGallery.Core's: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/Entities/PackageType.cs - public class PackageType - { - public int Key { get; set; } + public int Key { get; set; } - public string Name { get; set; } - public string Version { get; set; } + public string Name { get; set; } + public string Version { get; set; } - public Package Package { get; set; } - } -} + public Package Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageValidation.cs b/src/BaGet.Core/Entities/PackageValidation.cs index f53832a58..d7f99ba76 100644 --- a/src/BaGet.Core/Entities/PackageValidation.cs +++ b/src/BaGet.Core/Entities/PackageValidation.cs @@ -1,63 +1,62 @@ using System; -namespace BaGet.Core +namespace BaGet.Core; + +public enum PackageValidationState { - public enum PackageValidationState - { - Pending = 0, - Succeeded = 1, - Failed = 2, - } + Pending = 0, + Succeeded = 1, + Failed = 2, +} +/// +/// One step of validating a pushed package: a validator's verdict, or the final +/// indexing step. A submission is every row sharing a . +/// +/// +/// The package does not exist while it is validated: it is staged in storage and only +/// indexed once every validator succeeds. So nothing that serves packages needs to +/// know about validation, and a package being validated cannot be downloaded. +/// +public class PackageValidation +{ /// - /// One step of validating a pushed package: a validator's verdict, or the final - /// indexing step. A submission is every row sharing a . + /// The of the step that indexes the package once it is valid. /// - /// - /// The package does not exist while it is validated: it is staged in storage and only - /// indexed once every validator succeeds. So nothing that serves packages needs to - /// know about validation, and a package being validated cannot be downloaded. - /// - public class PackageValidation - { - /// - /// The of the step that indexes the package once it is valid. - /// - public const string IndexType = "Index"; + public const string IndexType = "Index"; - public int Key { get; set; } + public int Key { get; set; } - public string SubmissionId { get; set; } + public string SubmissionId { get; set; } - public string PackageId { get; set; } + public string PackageId { get; set; } - /// - /// The normalized version. - /// - public string PackageVersion { get; set; } + /// + /// The normalized version. + /// + public string PackageVersion { get; set; } - /// - /// The indexed package, once the submission succeeds. Nullable so that the - /// relationship is additive; see . - /// - public int? PackageKey { get; set; } + /// + /// The indexed package, once the submission succeeds. Nullable so that the + /// relationship is additive; see . + /// + public int? PackageKey { get; set; } - public Package Package { get; set; } + public Package Package { get; set; } - /// - /// The validator's name, or . - /// - public string Type { get; set; } + /// + /// The validator's name, or . + /// + public string Type { get; set; } - public PackageValidationState State { get; set; } + public PackageValidationState State { get; set; } - /// - /// Why the step failed, if it did. - /// - public string Message { get; set; } + /// + /// Why the step failed, if it did. + /// + public string Message { get; set; } - public DateTime Created { get; set; } + public DateTime Created { get; set; } - public DateTime? Completed { get; set; } - } -} + public DateTime? Completed { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/PackageVulnerability.cs b/src/BaGet.Core/Entities/PackageVulnerability.cs index 80666ea5d..805f71584 100644 --- a/src/BaGet.Core/Entities/PackageVulnerability.cs +++ b/src/BaGet.Core/Entities/PackageVulnerability.cs @@ -1,34 +1,33 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A known vulnerability affecting a package version. +/// See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info +/// +public class PackageVulnerability { + public int Key { get; set; } + /// - /// A known vulnerability affecting a package version. - /// See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info + /// The URL of the advisory describing the vulnerability. /// - public class PackageVulnerability - { - public int Key { get; set; } - - /// - /// The URL of the advisory describing the vulnerability. - /// - public string AdvisoryUrl { get; set; } + public string AdvisoryUrl { get; set; } - /// - /// The severity, as the protocol numbers it: 0 low, 1 moderate, 2 high, 3 critical. - /// - public int Severity { get; set; } + /// + /// The severity, as the protocol numbers it: 0 low, 1 moderate, 2 high, 3 critical. + /// + public int Severity { get; set; } - /// - /// The range of versions the advisory applies to. - /// - public string VersionRange { get; set; } + /// + /// The range of versions the advisory applies to. + /// + public string VersionRange { get; set; } - /// - /// The key of the affected package version. Nullable for the same reason as on - /// . - /// - public int? PackageKey { get; set; } + /// + /// The key of the affected package version. Nullable for the same reason as on + /// . + /// + public int? PackageKey { get; set; } - public Package Package { get; set; } - } -} + public Package Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/SemVerLevel.cs b/src/BaGet.Core/Entities/SemVerLevel.cs index 29aa5ae41..50a98a20d 100644 --- a/src/BaGet.Core/Entities/SemVerLevel.cs +++ b/src/BaGet.Core/Entities/SemVerLevel.cs @@ -1,15 +1,14 @@ -namespace BaGet.Core +namespace BaGet.Core; + +public enum SemVerLevel { - public enum SemVerLevel - { - /// - /// Either an invalid semantic version or a semantic version v1.0.0 - /// - Unknown = 0, + /// + /// Either an invalid semantic version or a semantic version v1.0.0 + /// + Unknown = 0, - /// - /// A valid semantic version v2.0.0 - /// - SemVer2 = 2 - } -} + /// + /// A valid semantic version v2.0.0 + /// + SemVer2 = 2 +} \ No newline at end of file diff --git a/src/BaGet.Core/Entities/TargetFramework.cs b/src/BaGet.Core/Entities/TargetFramework.cs index a8e4a9a84..9b7cfec65 100644 --- a/src/BaGet.Core/Entities/TargetFramework.cs +++ b/src/BaGet.Core/Entities/TargetFramework.cs @@ -1,11 +1,10 @@ -namespace BaGet.Core +namespace BaGet.Core; + +public class TargetFramework { - public class TargetFramework - { - public int Key { get; set; } + public int Key { get; set; } - public string Moniker { get; set; } + public string Moniker { get; set; } - public Package Package { get; set; } - } -} + public Package Package { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/BaGetApplicationExtensions.cs b/src/BaGet.Core/Extensions/BaGetApplicationExtensions.cs index 7dc2967f3..e223c778a 100644 --- a/src/BaGet.Core/Extensions/BaGetApplicationExtensions.cs +++ b/src/BaGet.Core/Extensions/BaGetApplicationExtensions.cs @@ -3,36 +3,35 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet +namespace BaGet; + +public static class BaGetApplicationExtensions { - public static class BaGetApplicationExtensions + public static BaGetApplication AddFileStorage(this BaGetApplication app) { - public static BaGetApplication AddFileStorage(this BaGetApplication app) - { - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - return app; - } + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + return app; + } - public static BaGetApplication AddFileStorage( - this BaGetApplication app, - Action configure) - { - app.AddFileStorage(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddFileStorage( + this BaGetApplication app, + Action configure) + { + app.AddFileStorage(); + app.Services.Configure(configure); + return app; + } - public static BaGetApplication AddNullStorage(this BaGetApplication app) - { - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - return app; - } + public static BaGetApplication AddNullStorage(this BaGetApplication app) + { + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + return app; + } - public static BaGetApplication AddNullSearch(this BaGetApplication app) - { - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); - return app; - } + public static BaGetApplication AddNullSearch(this BaGetApplication app) + { + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs index 7981d7712..df186b09d 100644 --- a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs +++ b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.Providers.cs @@ -5,134 +5,133 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet.Core +namespace BaGet.Core; + +public static partial class DependencyInjectionExtensions { - public static partial class DependencyInjectionExtensions + private static readonly string DatabaseTypeKey = $"{nameof(BaGetOptions.Database)}:{nameof(DatabaseOptions.Type)}"; + private static readonly string SearchTypeKey = $"{nameof(BaGetOptions.Search)}:{nameof(SearchOptions.Type)}"; + private static readonly string StorageTypeKey = $"{nameof(BaGetOptions.Storage)}:{nameof(StorageOptions.Type)}"; + + private static readonly string DatabaseSearchType = "Database"; + + /// + /// Add a new provider to the dependency injection container. The provider may + /// provide an implementation of the service, or it may return null. + /// + /// The service that may be provided. + /// The dependency injection container. + /// A handler that provides the service, or null. + /// The dependency injection container. + public static IServiceCollection AddProvider( + this IServiceCollection services, + Func func) + where TService : class { - private static readonly string DatabaseTypeKey = $"{nameof(BaGetOptions.Database)}:{nameof(DatabaseOptions.Type)}"; - private static readonly string SearchTypeKey = $"{nameof(BaGetOptions.Search)}:{nameof(SearchOptions.Type)}"; - private static readonly string StorageTypeKey = $"{nameof(BaGetOptions.Storage)}:{nameof(StorageOptions.Type)}"; - - private static readonly string DatabaseSearchType = "Database"; - - /// - /// Add a new provider to the dependency injection container. The provider may - /// provide an implementation of the service, or it may return null. - /// - /// The service that may be provided. - /// The dependency injection container. - /// A handler that provides the service, or null. - /// The dependency injection container. - public static IServiceCollection AddProvider( - this IServiceCollection services, - Func func) - where TService : class - { - services.AddSingleton>(new DelegateProvider(func)); + services.AddSingleton>(new DelegateProvider(func)); - return services; - } + return services; + } - /// - /// Determine whether a database type is currently active. - /// - /// The application's configuration. - /// The database type that should be checked. - /// Whether the database type is active. - public static bool HasDatabaseType(this IConfiguration config, string value) - { - return config[DatabaseTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); - } + /// + /// Determine whether a database type is currently active. + /// + /// The application's configuration. + /// The database type that should be checked. + /// Whether the database type is active. + public static bool HasDatabaseType(this IConfiguration config, string value) + { + return config[DatabaseTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); + } - /// - /// Determine whether a search type is currently active. - /// - /// The application's configuration. - /// The search type that should be checked. - /// Whether the search type is active. - public static bool HasSearchType(this IConfiguration config, string value) - { - return config[SearchTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); - } + /// + /// Determine whether a search type is currently active. + /// + /// The application's configuration. + /// The search type that should be checked. + /// Whether the search type is active. + public static bool HasSearchType(this IConfiguration config, string value) + { + return config[SearchTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); + } - /// - /// Determine whether a storage type is currently active. - /// - /// The application's configuration. - /// The storage type that should be checked. - /// Whether the database type is active. - public static bool HasStorageType(this IConfiguration config, string value) - { - return config[StorageTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); - } + /// + /// Determine whether a storage type is currently active. + /// + /// The application's configuration. + /// The storage type that should be checked. + /// Whether the database type is active. + public static bool HasStorageType(this IConfiguration config, string value) + { + return config[StorageTypeKey].Equals(value, StringComparison.OrdinalIgnoreCase); + } - public static IServiceCollection AddBaGetDbContextProvider( - this IServiceCollection services, - string databaseType, - Action configureContext) - where TContext : DbContext, IContext - { - services.TryAddScoped(provider => provider.GetRequiredService()); - services.TryAddTransient(provider => provider.GetRequiredService()); + public static IServiceCollection AddBaGetDbContextProvider( + this IServiceCollection services, + string databaseType, + Action configureContext) + where TContext : DbContext, IContext + { + services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddTransient(provider => provider.GetRequiredService()); - services.AddDbContext(configureContext); + services.AddDbContext(configureContext); - services.AddProvider((provider, config) => - { - if (!config.HasDatabaseType(databaseType)) return null; + services.AddProvider((provider, config) => + { + if (!config.HasDatabaseType(databaseType)) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - services.AddProvider((provider, config) => - { - if (!config.HasDatabaseType(databaseType)) return null; + services.AddProvider((provider, config) => + { + if (!config.HasDatabaseType(databaseType)) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - services.AddProvider((provider, config) => - { - if (!config.HasSearchType(DatabaseSearchType)) return null; - if (!config.HasDatabaseType(databaseType)) return null; + services.AddProvider((provider, config) => + { + if (!config.HasSearchType(DatabaseSearchType)) return null; + if (!config.HasDatabaseType(databaseType)) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - services.AddProvider((provider, config) => - { - if (!config.HasSearchType(DatabaseSearchType)) return null; - if (!config.HasDatabaseType(databaseType)) return null; + services.AddProvider((provider, config) => + { + if (!config.HasSearchType(DatabaseSearchType)) return null; + if (!config.HasDatabaseType(databaseType)) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return services; - } + return services; + } - /// - /// Runs through all providers to resolve the . - /// - /// The service that will be resolved using providers. - /// The dependency injection container. - /// An instance of the service created by the providers. - public static TService GetServiceFromProviders(IServiceProvider services) - where TService : class - { - // Run through all the providers for the type. Find the first provider that results a non-null result. - var providers = services.GetRequiredService>>(); - var configuration = services.GetRequiredService(); + /// + /// Runs through all providers to resolve the . + /// + /// The service that will be resolved using providers. + /// The dependency injection container. + /// An instance of the service created by the providers. + public static TService GetServiceFromProviders(IServiceProvider services) + where TService : class + { + // Run through all the providers for the type. Find the first provider that results a non-null result. + var providers = services.GetRequiredService>>(); + var configuration = services.GetRequiredService(); - foreach (var provider in providers) + foreach (var provider in providers) + { + var result = provider.GetOrNull(services, configuration); + if (result != null) { - var result = provider.GetOrNull(services, configuration); - if (result != null) - { - return result; - } + return result; } - - return null; } + + return null; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs index 5c8801c8c..ac31feddb 100644 --- a/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs +++ b/src/BaGet.Core/Extensions/DependencyInjectionExtensions.cs @@ -8,211 +8,210 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +public static partial class DependencyInjectionExtensions { - public static partial class DependencyInjectionExtensions + public static IServiceCollection AddBaGetApplication( + this IServiceCollection services, + Action configureAction) { - public static IServiceCollection AddBaGetApplication( - this IServiceCollection services, - Action configureAction) - { - var app = new BaGetApplication(services); - - services.AddConfiguration(); - services.AddBaGetServices(); - services.AddDefaultProviders(); - - configureAction(app); - - services.AddFallbackServices(); - - return services; - } - - /// - /// Configures and validates options. - /// - /// The options type that should be added. - /// The dependency injection container to add options. - /// - /// The configuration key that should be used when configuring the options. - /// If null, the root configuration will be used to configure the options. - /// - /// The dependency injection container. - public static IServiceCollection AddBaGetOptions( - this IServiceCollection services, - string key = null) - where TOptions : class + var app = new BaGetApplication(services); + + services.AddConfiguration(); + services.AddBaGetServices(); + services.AddDefaultProviders(); + + configureAction(app); + + services.AddFallbackServices(); + + return services; + } + + /// + /// Configures and validates options. + /// + /// The options type that should be added. + /// The dependency injection container to add options. + /// + /// The configuration key that should be used when configuring the options. + /// If null, the root configuration will be used to configure the options. + /// + /// The dependency injection container. + public static IServiceCollection AddBaGetOptions( + this IServiceCollection services, + string key = null) + where TOptions : class + { + services.AddSingleton>(new ValidateBaGetOptions(key)); + services.AddSingleton>(provider => { - services.AddSingleton>(new ValidateBaGetOptions(key)); - services.AddSingleton>(provider => + var config = provider.GetRequiredService(); + if (key != null) { - var config = provider.GetRequiredService(); - if (key != null) - { - config = config.GetSection(key); - } + config = config.GetSection(key); + } - return new BindOptions(config); - }); + return new BindOptions(config); + }); - return services; - } + return services; + } - private static void AddConfiguration(this IServiceCollection services) + private static void AddConfiguration(this IServiceCollection services) + { + services.AddBaGetOptions(); + services.AddBaGetOptions(nameof(BaGetOptions.Database)); + services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + services.AddBaGetOptions(nameof(BaGetOptions.Mirror)); + services.AddBaGetOptions(nameof(BaGetOptions.Feeds)); + services.AddBaGetOptions(nameof(BaGetOptions.Accounts)); + services.AddBaGetOptions(nameof(BaGetOptions.Validation)); + services.AddBaGetOptions(nameof(BaGetOptions.Search)); + services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + } + + private static void AddBaGetServices(this IServiceCollection services) + { + services.TryAddSingleton(); + services.TryAddSingleton(); + + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + services.TryAddSingleton(HttpClientFactory); + services.TryAddSingleton(NuGetClientFactoryFactory); + + services.TryAddScoped(); + services.TryAddScoped(); + + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddTransient(); + services.TryAddSingleton(); + services.TryAddTransient(); + + services.TryAddTransient(UpstreamClientFactory); + } + + private static void AddDefaultProviders(this IServiceCollection services) + { + services.AddProvider((provider, configuration) => { - services.AddBaGetOptions(); - services.AddBaGetOptions(nameof(BaGetOptions.Database)); - services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - services.AddBaGetOptions(nameof(BaGetOptions.Mirror)); - services.AddBaGetOptions(nameof(BaGetOptions.Feeds)); - services.AddBaGetOptions(nameof(BaGetOptions.Accounts)); - services.AddBaGetOptions(nameof(BaGetOptions.Validation)); - services.AddBaGetOptions(nameof(BaGetOptions.Search)); - services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - } - - private static void AddBaGetServices(this IServiceCollection services) + if (!configuration.HasSearchType("null")) return null; + + return provider.GetRequiredService(); + }); + + services.AddProvider((provider, configuration) => { - services.TryAddSingleton(); - services.TryAddSingleton(); - - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - services.TryAddSingleton(); - - services.TryAddSingleton(HttpClientFactory); - services.TryAddSingleton(NuGetClientFactoryFactory); - - services.TryAddScoped(); - services.TryAddScoped(); - - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddTransient(); - services.TryAddSingleton(); - services.TryAddTransient(); - - services.TryAddTransient(UpstreamClientFactory); - } - - private static void AddDefaultProviders(this IServiceCollection services) + if (!configuration.HasSearchType("null")) return null; + + return provider.GetRequiredService(); + }); + + services.AddProvider((provider, configuration) => { - services.AddProvider((provider, configuration) => + if (configuration.HasStorageType("filesystem")) { - if (!configuration.HasSearchType("null")) return null; - - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + } - services.AddProvider((provider, configuration) => + if (configuration.HasStorageType("null")) { - if (!configuration.HasSearchType("null")) return null; + return provider.GetRequiredService(); + } - return provider.GetRequiredService(); - }); + return null; + }); + } - services.AddProvider((provider, configuration) => - { - if (configuration.HasStorageType("filesystem")) - { - return provider.GetRequiredService(); - } + private static void AddFallbackServices(this IServiceCollection services) + { + services.TryAddScoped(); + + // BaGet's services have multiple implementations that live side-by-side. + // The application will choose the implementation using one of two ways: + // + // 1. Using the first implementation that was registered in the dependency injection + // container. This is the strategy used by applications that embed BaGet. + // 2. Using "providers". The providers will examine the application's configuration to + // determine whether its service implementation is active. Thsi is the strategy used + // by the default BaGet application. + // + // BaGet has database and search services, but the database services are special + // in that they may also act as search services. If an application registers the + // database service first and the search service second, the application should + // use the search service even though it wasn't registered first. Furthermore, + // if an application registers a database service without a search service, the + // database service should be used for search. This effect is achieved by deferring + // the database search service's registration until the very end. + services.TryAddTransient(provider => provider.GetRequiredService()); + services.TryAddTransient(provider => provider.GetRequiredService()); + } - if (configuration.HasStorageType("null")) - { - return provider.GetRequiredService(); - } + private static HttpClient HttpClientFactory(IServiceProvider provider) + { + var options = provider.GetRequiredService>().Value; - return null; - }); - } + var assembly = Assembly.GetEntryAssembly(); + var assemblyName = assembly.GetName().Name; + var assemblyVersion = assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; - private static void AddFallbackServices(this IServiceCollection services) - { - services.TryAddScoped(); - - // BaGet's services have multiple implementations that live side-by-side. - // The application will choose the implementation using one of two ways: - // - // 1. Using the first implementation that was registered in the dependency injection - // container. This is the strategy used by applications that embed BaGet. - // 2. Using "providers". The providers will examine the application's configuration to - // determine whether its service implementation is active. Thsi is the strategy used - // by the default BaGet application. - // - // BaGet has database and search services, but the database services are special - // in that they may also act as search services. If an application registers the - // database service first and the search service second, the application should - // use the search service even though it wasn't registered first. Furthermore, - // if an application registers a database service without a search service, the - // database service should be used for search. This effect is achieved by deferring - // the database search service's registration until the very end. - services.TryAddTransient(provider => provider.GetRequiredService()); - services.TryAddTransient(provider => provider.GetRequiredService()); - } - - private static HttpClient HttpClientFactory(IServiceProvider provider) + var client = new HttpClient(new HttpClientHandler { - var options = provider.GetRequiredService>().Value; + AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, + }); - var assembly = Assembly.GetEntryAssembly(); - var assemblyName = assembly.GetName().Name; - var assemblyVersion = assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; + client.DefaultRequestHeaders.Add("User-Agent", $"{assemblyName}/{assemblyVersion}"); + client.Timeout = TimeSpan.FromSeconds(options.PackageDownloadTimeoutSeconds); - var client = new HttpClient(new HttpClientHandler - { - AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, - }); - - client.DefaultRequestHeaders.Add("User-Agent", $"{assemblyName}/{assemblyVersion}"); - client.Timeout = TimeSpan.FromSeconds(options.PackageDownloadTimeoutSeconds); + return client; + } - return client; - } + private static NuGetClientFactory NuGetClientFactoryFactory(IServiceProvider provider) + { + var httpClient = provider.GetRequiredService(); + var options = provider.GetRequiredService>(); - private static NuGetClientFactory NuGetClientFactoryFactory(IServiceProvider provider) - { - var httpClient = provider.GetRequiredService(); - var options = provider.GetRequiredService>(); + return new NuGetClientFactory( + httpClient, + options.Value.PackageSource.ToString()); + } - return new NuGetClientFactory( - httpClient, - options.Value.PackageSource.ToString()); - } + private static IUpstreamClient UpstreamClientFactory(IServiceProvider provider) + { + var options = provider.GetRequiredService>(); - private static IUpstreamClient UpstreamClientFactory(IServiceProvider provider) + return options.Value switch { - var options = provider.GetRequiredService>(); - - return options.Value switch - { - { Enabled: false } => provider.GetRequiredService(), - { Legacy: true } => provider.GetRequiredService(), - _ => provider.GetRequiredService(), - }; - } + { Enabled: false } => provider.GetRequiredService(), + { Legacy: true } => provider.GetRequiredService(), + _ => provider.GetRequiredService(), + }; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/IProvider.cs b/src/BaGet.Core/Extensions/IProvider.cs index 1a7b5612d..8aa434906 100644 --- a/src/BaGet.Core/Extensions/IProvider.cs +++ b/src/BaGet.Core/Extensions/IProvider.cs @@ -1,47 +1,46 @@ using System; using Microsoft.Extensions.Configuration; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Attempts to provide the . +/// +/// The service that may be provided. +public interface IProvider { /// - /// Attempts to provide the . + /// Attempt to provide the . /// - /// The service that may be provided. - public interface IProvider - { - /// - /// Attempt to provide the . - /// - /// The dependency injection container. - /// The app's configuration. - /// - /// An instance of , or, null if the - /// provider is not currently active in the . - /// - TService GetOrNull(IServiceProvider provider, IConfiguration configuration); - } + /// The dependency injection container. + /// The app's configuration. + /// + /// An instance of , or, null if the + /// provider is not currently active in the . + /// + TService GetOrNull(IServiceProvider provider, IConfiguration configuration); +} + +/// +/// Implements as a delegate. +/// +internal class DelegateProvider : IProvider +{ + private readonly Func _func; /// - /// Implements as a delegate. + /// Create an using a delegate. /// - internal class DelegateProvider : IProvider + /// + /// A delegate that returns an instance of , or, + /// null if the provider is not currently active due to the app's configuration. + public DelegateProvider(Func func) { - private readonly Func _func; - - /// - /// Create an using a delegate. - /// - /// - /// A delegate that returns an instance of , or, - /// null if the provider is not currently active due to the app's configuration. - public DelegateProvider(Func func) - { - _func = func ?? throw new ArgumentNullException(nameof(func)); - } + _func = func ?? throw new ArgumentNullException(nameof(func)); + } - public TService GetOrNull(IServiceProvider provider, IConfiguration configuration) - { - return _func(provider, configuration); - } + public TService GetOrNull(IServiceProvider provider, IConfiguration configuration) + { + return _func(provider, configuration); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/PackageArchiveReaderExtensions.cs b/src/BaGet.Core/Extensions/PackageArchiveReaderExtensions.cs index dc5f1eb71..4ddc6cb22 100644 --- a/src/BaGet.Core/Extensions/PackageArchiveReaderExtensions.cs +++ b/src/BaGet.Core/Extensions/PackageArchiveReaderExtensions.cs @@ -7,222 +7,221 @@ using NuGet.Common; using NuGet.Packaging; -namespace BaGet.Core +namespace BaGet.Core; + +using NuGetPackageType = NuGet.Packaging.Core.PackageType; + +public static class PackageArchiveReaderExtensions { - using NuGetPackageType = NuGet.Packaging.Core.PackageType; + public static bool HasReadme(this PackageArchiveReader package) + => !string.IsNullOrEmpty(package.NuspecReader.GetReadme()); + + public static bool HasEmbeddedIcon(this PackageArchiveReader package) + => !string.IsNullOrEmpty(package.NuspecReader.GetIcon()); - public static class PackageArchiveReaderExtensions + public async static Task GetReadmeAsync( + this PackageArchiveReader package, + CancellationToken cancellationToken) { - public static bool HasReadme(this PackageArchiveReader package) - => !string.IsNullOrEmpty(package.NuspecReader.GetReadme()); + var readmePath = package.NuspecReader.GetReadme(); + if (readmePath == null) + { + throw new InvalidOperationException("Package does not have a readme!"); + } - public static bool HasEmbeddedIcon(this PackageArchiveReader package) - => !string.IsNullOrEmpty(package.NuspecReader.GetIcon()); + return await package.GetStreamAsync(readmePath, cancellationToken); + } - public async static Task GetReadmeAsync( - this PackageArchiveReader package, - CancellationToken cancellationToken) - { - var readmePath = package.NuspecReader.GetReadme(); - if (readmePath == null) - { - throw new InvalidOperationException("Package does not have a readme!"); - } + public async static Task GetIconAsync( + this PackageArchiveReader package, + CancellationToken cancellationToken) + { + return await package.GetStreamAsync( + PathUtility.StripLeadingDirectorySeparators(package.NuspecReader.GetIcon()), + cancellationToken); + } - return await package.GetStreamAsync(readmePath, cancellationToken); - } + public static Package GetPackageMetadata(this PackageArchiveReader packageReader) + { + var nuspec = packageReader.NuspecReader; - public async static Task GetIconAsync( - this PackageArchiveReader package, - CancellationToken cancellationToken) - { - return await package.GetStreamAsync( - PathUtility.StripLeadingDirectorySeparators(package.NuspecReader.GetIcon()), - cancellationToken); - } + (var repositoryUri, var repositoryType) = GetRepositoryMetadata(nuspec); - public static Package GetPackageMetadata(this PackageArchiveReader packageReader) + return new Package { - var nuspec = packageReader.NuspecReader; - - (var repositoryUri, var repositoryType) = GetRepositoryMetadata(nuspec); + Id = nuspec.GetId(), + Version = nuspec.GetVersion(), + Authors = ParseAuthors(nuspec.GetAuthors()), + Description = nuspec.GetDescription(), + HasReadme = packageReader.HasReadme(), + HasEmbeddedIcon = packageReader.HasEmbeddedIcon(), + IsPrerelease = nuspec.GetVersion().IsPrerelease, + Language = nuspec.GetLanguage() ?? string.Empty, + ReleaseNotes = nuspec.GetReleaseNotes() ?? string.Empty, + Listed = true, + MinClientVersion = nuspec.GetMinClientVersion()?.ToNormalizedString() ?? string.Empty, + Published = DateTime.UtcNow, + RequireLicenseAcceptance = nuspec.GetRequireLicenseAcceptance(), + SemVerLevel = GetSemVerLevel(nuspec), + Summary = nuspec.GetSummary(), + Title = nuspec.GetTitle(), + IconUrl = ParseUri(nuspec.GetIconUrl()), + LicenseUrl = ParseUri(nuspec.GetLicenseUrl()), + ProjectUrl = ParseUri(nuspec.GetProjectUrl()), + RepositoryUrl = repositoryUri, + RepositoryType = repositoryType, + Dependencies = GetDependencies(nuspec), + Tags = ParseTags(nuspec.GetTags()), + PackageTypes = GetPackageTypes(nuspec), + TargetFrameworks = GetTargetFrameworks(packageReader), + }; + } - return new Package - { - Id = nuspec.GetId(), - Version = nuspec.GetVersion(), - Authors = ParseAuthors(nuspec.GetAuthors()), - Description = nuspec.GetDescription(), - HasReadme = packageReader.HasReadme(), - HasEmbeddedIcon = packageReader.HasEmbeddedIcon(), - IsPrerelease = nuspec.GetVersion().IsPrerelease, - Language = nuspec.GetLanguage() ?? string.Empty, - ReleaseNotes = nuspec.GetReleaseNotes() ?? string.Empty, - Listed = true, - MinClientVersion = nuspec.GetMinClientVersion()?.ToNormalizedString() ?? string.Empty, - Published = DateTime.UtcNow, - RequireLicenseAcceptance = nuspec.GetRequireLicenseAcceptance(), - SemVerLevel = GetSemVerLevel(nuspec), - Summary = nuspec.GetSummary(), - Title = nuspec.GetTitle(), - IconUrl = ParseUri(nuspec.GetIconUrl()), - LicenseUrl = ParseUri(nuspec.GetLicenseUrl()), - ProjectUrl = ParseUri(nuspec.GetProjectUrl()), - RepositoryUrl = repositoryUri, - RepositoryType = repositoryType, - Dependencies = GetDependencies(nuspec), - Tags = ParseTags(nuspec.GetTags()), - PackageTypes = GetPackageTypes(nuspec), - TargetFrameworks = GetTargetFrameworks(packageReader), - }; + // Based off https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/SemVerLevelKey.cs + private static SemVerLevel GetSemVerLevel(NuspecReader nuspec) + { + if (nuspec.GetVersion().IsSemVer2) + { + return SemVerLevel.SemVer2; } - // Based off https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/SemVerLevelKey.cs - private static SemVerLevel GetSemVerLevel(NuspecReader nuspec) + foreach (var dependencyGroup in nuspec.GetDependencyGroups()) { - if (nuspec.GetVersion().IsSemVer2) + foreach (var dependency in dependencyGroup.Packages) { - return SemVerLevel.SemVer2; - } - - foreach (var dependencyGroup in nuspec.GetDependencyGroups()) - { - foreach (var dependency in dependencyGroup.Packages) + if ((dependency.VersionRange.MinVersion != null && dependency.VersionRange.MinVersion.IsSemVer2) + || (dependency.VersionRange.MaxVersion != null && dependency.VersionRange.MaxVersion.IsSemVer2)) { - if ((dependency.VersionRange.MinVersion != null && dependency.VersionRange.MinVersion.IsSemVer2) - || (dependency.VersionRange.MaxVersion != null && dependency.VersionRange.MaxVersion.IsSemVer2)) - { - return SemVerLevel.SemVer2; - } + return SemVerLevel.SemVer2; } } - - return SemVerLevel.Unknown; } - private static Uri ParseUri(string uriString) - { - if (string.IsNullOrEmpty(uriString)) return null; + return SemVerLevel.Unknown; + } - // These URLs are optional display metadata and are not validated when a package - // is built, so a package can carry a relative or malformed one. Ignore a URL that - // cannot be served rather than failing the whole package, which is how the - // repository URL below is already treated. - if (!Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) return null; + private static Uri ParseUri(string uriString) + { + if (string.IsNullOrEmpty(uriString)) return null; - return uri; - } + // These URLs are optional display metadata and are not validated when a package + // is built, so a package can carry a relative or malformed one. Ignore a URL that + // cannot be served rather than failing the whole package, which is how the + // repository URL below is already treated. + if (!Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) return null; - private static string[] ParseAuthors(string authors) - { - if (string.IsNullOrEmpty(authors)) return new string[0]; + return uri; + } - return authors.Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - } + private static string[] ParseAuthors(string authors) + { + if (string.IsNullOrEmpty(authors)) return new string[0]; - private static string[] ParseTags(string tags) - { - if (string.IsNullOrEmpty(tags)) return new string[0]; + return authors.Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + } - return tags.Split(new[] { ',', ';', ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - } + private static string[] ParseTags(string tags) + { + if (string.IsNullOrEmpty(tags)) return new string[0]; - private static (Uri repositoryUrl, string repositoryType) GetRepositoryMetadata(NuspecReader nuspec) - { - var repository = nuspec.GetRepositoryMetadata(); + return tags.Split(new[] { ',', ';', ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + } - if (string.IsNullOrEmpty(repository?.Url) || - !Uri.TryCreate(repository.Url, UriKind.Absolute, out var repositoryUri)) - { - return (null, null); - } + private static (Uri repositoryUrl, string repositoryType) GetRepositoryMetadata(NuspecReader nuspec) + { + var repository = nuspec.GetRepositoryMetadata(); - if (repositoryUri.Scheme != Uri.UriSchemeHttps) - { - return (null, null); - } + if (string.IsNullOrEmpty(repository?.Url) || + !Uri.TryCreate(repository.Url, UriKind.Absolute, out var repositoryUri)) + { + return (null, null); + } - if (repository.Type.Length > 100) - { - throw new InvalidOperationException("Repository type must be less than or equal 100 characters"); - } + if (repositoryUri.Scheme != Uri.UriSchemeHttps) + { + return (null, null); + } - return (repositoryUri, repository.Type); + if (repository.Type.Length > 100) + { + throw new InvalidOperationException("Repository type must be less than or equal 100 characters"); } - private static List GetDependencies(NuspecReader nuspec) + return (repositoryUri, repository.Type); + } + + private static List GetDependencies(NuspecReader nuspec) + { + var dependencies = new List(); + + foreach (var group in nuspec.GetDependencyGroups()) { - var dependencies = new List(); + var targetFramework = group.TargetFramework.GetShortFolderName(); - foreach (var group in nuspec.GetDependencyGroups()) + if (!group.Packages.Any()) { - var targetFramework = group.TargetFramework.GetShortFolderName(); - - if (!group.Packages.Any()) + dependencies.Add(new PackageDependency { - dependencies.Add(new PackageDependency - { - Id = null, - VersionRange = null, - TargetFramework = targetFramework, - }); - } + Id = null, + VersionRange = null, + TargetFramework = targetFramework, + }); + } - foreach (var dependency in group.Packages) + foreach (var dependency in group.Packages) + { + dependencies.Add(new PackageDependency { - dependencies.Add(new PackageDependency - { - Id = dependency.Id, - VersionRange = dependency.VersionRange?.ToString(), - TargetFramework = targetFramework, - }); - } + Id = dependency.Id, + VersionRange = dependency.VersionRange?.ToString(), + TargetFramework = targetFramework, + }); } - - return dependencies; } - private static List GetPackageTypes(NuspecReader nuspec) - { - var packageTypes = nuspec - .GetPackageTypes() - .Select(t => new PackageType - { - Name = t.Name, - Version = t.Version.ToString() - }) - .ToList(); + return dependencies; + } - // Default to the standard "dependency" package type if no types were found. - if (packageTypes.Count == 0) + private static List GetPackageTypes(NuspecReader nuspec) + { + var packageTypes = nuspec + .GetPackageTypes() + .Select(t => new PackageType { - packageTypes.Add(new PackageType - { - Name = NuGetPackageType.Dependency.Name, - Version = NuGetPackageType.Dependency.Version.ToString(), - }); - } + Name = t.Name, + Version = t.Version.ToString() + }) + .ToList(); - return packageTypes; + // Default to the standard "dependency" package type if no types were found. + if (packageTypes.Count == 0) + { + packageTypes.Add(new PackageType + { + Name = NuGetPackageType.Dependency.Name, + Version = NuGetPackageType.Dependency.Version.ToString(), + }); } - private static List GetTargetFrameworks(PackageArchiveReader packageReader) - { - var targetFrameworks = packageReader - .GetSupportedFrameworks() - .Select(f => new TargetFramework - { - Moniker = f.GetShortFolderName() - }) - .ToList(); + return packageTypes; + } - // Default to the "any" framework if no frameworks were found. - if (targetFrameworks.Count == 0) + private static List GetTargetFrameworks(PackageArchiveReader packageReader) + { + var targetFrameworks = packageReader + .GetSupportedFrameworks() + .Select(f => new TargetFramework { - targetFrameworks.Add(new TargetFramework { Moniker = "any" }); - } + Moniker = f.GetShortFolderName() + }) + .ToList(); - return targetFrameworks; + // Default to the "any" framework if no frameworks were found. + if (targetFrameworks.Count == 0) + { + targetFrameworks.Add(new TargetFramework { Moniker = "any" }); } + + return targetFrameworks; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/StreamExtensions.cs b/src/BaGet.Core/Extensions/StreamExtensions.cs index bfe9d840a..b55013ca7 100644 --- a/src/BaGet.Core/Extensions/StreamExtensions.cs +++ b/src/BaGet.Core/Extensions/StreamExtensions.cs @@ -5,55 +5,54 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public static class StreamExtensions { - public static class StreamExtensions + // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 + private const int DefaultCopyBufferSize = 81920; + + /// + /// Copies a stream to a file, and returns that file as a stream. The underlying file will be + /// deleted when the resulting stream is disposed. + /// + /// The stream to be copied, at its current position. + /// + /// The copied stream, with its position reset to the beginning. + public static async Task AsTemporaryFileStreamAsync( + this Stream original, + CancellationToken cancellationToken = default) { - // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 - private const int DefaultCopyBufferSize = 81920; + var result = new FileStream( + Path.GetTempFileName(), + FileMode.Create, + FileAccess.ReadWrite, + FileShare.None, + DefaultCopyBufferSize, + FileOptions.DeleteOnClose); - /// - /// Copies a stream to a file, and returns that file as a stream. The underlying file will be - /// deleted when the resulting stream is disposed. - /// - /// The stream to be copied, at its current position. - /// - /// The copied stream, with its position reset to the beginning. - public static async Task AsTemporaryFileStreamAsync( - this Stream original, - CancellationToken cancellationToken = default) + try { - var result = new FileStream( - Path.GetTempFileName(), - FileMode.Create, - FileAccess.ReadWrite, - FileShare.None, - DefaultCopyBufferSize, - FileOptions.DeleteOnClose); - - try - { - await original.CopyToAsync(result, DefaultCopyBufferSize, cancellationToken); - result.Position = 0; - } - catch (Exception) - { - result.Dispose(); - throw; - } - - return result; + await original.CopyToAsync(result, DefaultCopyBufferSize, cancellationToken); + result.Position = 0; } + catch (Exception) + { + result.Dispose(); + throw; + } + + return result; + } - public static bool Matches(this Stream content, Stream target) + public static bool Matches(this Stream content, Stream target) + { + using (var sha256 = SHA256.Create()) { - using (var sha256 = SHA256.Create()) - { - var contentHash = sha256.ComputeHash(content); - var targetHash = sha256.ComputeHash(target); + var contentHash = sha256.ComputeHash(content); + var targetHash = sha256.ComputeHash(target); - return contentHash.SequenceEqual(targetHash); - } + return contentHash.SequenceEqual(targetHash); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Extensions/SystemTime.cs b/src/BaGet.Core/Extensions/SystemTime.cs index 4d8195fc8..d565908f4 100644 --- a/src/BaGet.Core/Extensions/SystemTime.cs +++ b/src/BaGet.Core/Extensions/SystemTime.cs @@ -1,12 +1,11 @@ using System; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A wrapper that allows for unit tests related to system time. +/// +public class SystemTime { - /// - /// A wrapper that allows for unit tests related to system time. - /// - public class SystemTime - { - public virtual DateTime UtcNow => DateTime.UtcNow; - } -} + public virtual DateTime UtcNow => DateTime.UtcNow; +} \ No newline at end of file diff --git a/src/BaGet.Core/IPackageDatabase.cs b/src/BaGet.Core/IPackageDatabase.cs index c145cd24d..62f071c4e 100644 --- a/src/BaGet.Core/IPackageDatabase.cs +++ b/src/BaGet.Core/IPackageDatabase.cs @@ -3,144 +3,143 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The "source of truth" for packages' state. Packages' content +/// are stored by the . +/// +public interface IPackageDatabase { /// - /// The "source of truth" for packages' state. Packages' content - /// are stored by the . + /// Attempt to add a new package to the database. + /// + /// The package to add to the database. + /// A token to cancel the task. + /// The result of attempting to add the package to the database. + Task AddAsync(Package package, CancellationToken cancellationToken); + + /// + /// Attempt to find a package with the given id and version. /// - public interface IPackageDatabase - { - /// - /// Attempt to add a new package to the database. - /// - /// The package to add to the database. - /// A token to cancel the task. - /// The result of attempting to add the package to the database. - Task AddAsync(Package package, CancellationToken cancellationToken); - - /// - /// Attempt to find a package with the given id and version. - /// - /// The package's id. - /// The package's version. - /// Whether unlisted results should be included. - /// A token to cancel the task. - /// The package found, or null. - Task FindOrNullAsync( - string id, - NuGetVersion version, - bool includeUnlisted, - CancellationToken cancellationToken); - - /// - /// Attempt to find all packages with a given id. - /// - /// The packages' id. - /// Whether unlisted results should be included. - /// A token to cancel the task. - /// The packages found. Always non-null. - Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken); - - /// - /// Determine whether a package exists in the database (even if the package is unlisted). - /// - /// The package id to search. - /// A token to cancel the task. - /// Whether the package exists in the database. - Task ExistsAsync(string id, CancellationToken cancellationToken); - - /// - /// Determine whether a package exists in the database (even if the package is unlisted). - /// - /// The package id to search. - /// The package version to search. - /// A token to cancel the task. - /// Whether the package exists in the database. - Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Unlist a package, making it undiscoverable. - /// - /// The id of the package to unlist. - /// The version of the package to unlist. - /// A token to cancel the task. - /// False if the package does not exist. - Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Relist a package, making it discoverable. - /// - /// The id of the package to relist. - /// The version of the package to relist. - /// A token to cancel the task. - /// False if the package does not exist. - Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Increment a package's download count. - /// - /// The id of the package to update. - /// The id of the package to update. - /// A token to cancel the task. - /// Task that completes when the package's download has been incremented. - Task AddDownloadAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Completely remove the package from the database. - /// - /// The id of the package to remove. - /// The version of the pacakge to remove. - /// A token to cancel the task. - /// False if the package doesn't exist. - Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Mark a package version as deprecated, replacing any earlier deprecation. - /// - /// False if the package version does not exist. - Task SetDeprecationAsync( - string id, - NuGetVersion version, - PackageDeprecation deprecation, - CancellationToken cancellationToken); - - /// - /// Remove a package version's deprecation, if it has one. - /// - /// False if the package version does not exist. - Task RemoveDeprecationAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - - /// - /// Replace the known vulnerabilities of a package version. An empty list clears them. - /// - /// False if the package version does not exist. - Task SetVulnerabilitiesAsync( - string id, - NuGetVersion version, - IReadOnlyList vulnerabilities, - CancellationToken cancellationToken); - - /// - /// Every known vulnerability, with the package version it affects. - /// - Task> GetAllVulnerabilitiesAsync(CancellationToken cancellationToken); - } + /// The package's id. + /// The package's version. + /// Whether unlisted results should be included. + /// A token to cancel the task. + /// The package found, or null. + Task FindOrNullAsync( + string id, + NuGetVersion version, + bool includeUnlisted, + CancellationToken cancellationToken); /// - /// The result of attempting to add the package to the database. - /// See + /// Attempt to find all packages with a given id. /// - public enum PackageAddResult - { - /// - /// Failed to add the package as it already exists. - /// - PackageAlreadyExists, - - /// - /// The package was added successfully. - /// - Success - } + /// The packages' id. + /// Whether unlisted results should be included. + /// A token to cancel the task. + /// The packages found. Always non-null. + Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken); + + /// + /// Determine whether a package exists in the database (even if the package is unlisted). + /// + /// The package id to search. + /// A token to cancel the task. + /// Whether the package exists in the database. + Task ExistsAsync(string id, CancellationToken cancellationToken); + + /// + /// Determine whether a package exists in the database (even if the package is unlisted). + /// + /// The package id to search. + /// The package version to search. + /// A token to cancel the task. + /// Whether the package exists in the database. + Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Unlist a package, making it undiscoverable. + /// + /// The id of the package to unlist. + /// The version of the package to unlist. + /// A token to cancel the task. + /// False if the package does not exist. + Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Relist a package, making it discoverable. + /// + /// The id of the package to relist. + /// The version of the package to relist. + /// A token to cancel the task. + /// False if the package does not exist. + Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Increment a package's download count. + /// + /// The id of the package to update. + /// The id of the package to update. + /// A token to cancel the task. + /// Task that completes when the package's download has been incremented. + Task AddDownloadAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Completely remove the package from the database. + /// + /// The id of the package to remove. + /// The version of the pacakge to remove. + /// A token to cancel the task. + /// False if the package doesn't exist. + Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Mark a package version as deprecated, replacing any earlier deprecation. + /// + /// False if the package version does not exist. + Task SetDeprecationAsync( + string id, + NuGetVersion version, + PackageDeprecation deprecation, + CancellationToken cancellationToken); + + /// + /// Remove a package version's deprecation, if it has one. + /// + /// False if the package version does not exist. + Task RemoveDeprecationAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + + /// + /// Replace the known vulnerabilities of a package version. An empty list clears them. + /// + /// False if the package version does not exist. + Task SetVulnerabilitiesAsync( + string id, + NuGetVersion version, + IReadOnlyList vulnerabilities, + CancellationToken cancellationToken); + + /// + /// Every known vulnerability, with the package version it affects. + /// + Task> GetAllVulnerabilitiesAsync(CancellationToken cancellationToken); } + +/// +/// The result of attempting to add the package to the database. +/// See +/// +public enum PackageAddResult +{ + /// + /// Failed to add the package as it already exists. + /// + PackageAlreadyExists, + + /// + /// The package was added successfully. + /// + Success +} \ No newline at end of file diff --git a/src/BaGet.Core/IPackageService.cs b/src/BaGet.Core/IPackageService.cs index 768813d23..d026a86ef 100644 --- a/src/BaGet.Core/IPackageService.cs +++ b/src/BaGet.Core/IPackageService.cs @@ -3,68 +3,67 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The service that combines the state of indexed packages and +/// upstream packages. +/// For upstream packages, see . +/// For indexed packages, see . +/// +public interface IPackageService { /// - /// The service that combines the state of indexed packages and - /// upstream packages. - /// For upstream packages, see . - /// For indexed packages, see . + /// Attempt to find a package's versions using mirroring. This will merge + /// results from the configured upstream source with the locally indexed packages. /// - public interface IPackageService - { - /// - /// Attempt to find a package's versions using mirroring. This will merge - /// results from the configured upstream source with the locally indexed packages. - /// - /// The package's id to lookup - /// The token to cancel the lookup - /// - /// The package's versions, or an empty list if the package cannot be found. - /// This includes unlisted versions. - /// - Task> FindPackageVersionsAsync(string id, CancellationToken cancellationToken); + /// The package's id to lookup + /// The token to cancel the lookup + /// + /// The package's versions, or an empty list if the package cannot be found. + /// This includes unlisted versions. + /// + Task> FindPackageVersionsAsync(string id, CancellationToken cancellationToken); - /// - /// Attempt to find a package's metadata using mirroring. This will merge - /// results from the configured upstream source with the locally indexed packages. - /// - /// The package's id to lookup - /// The token to cancel the lookup - /// - /// The metadata for all versions of a package, including unlisted versions. - /// Returns an empty list if the package cannot be found. - /// - Task> FindPackagesAsync(string id, CancellationToken cancellationToken); + /// + /// Attempt to find a package's metadata using mirroring. This will merge + /// results from the configured upstream source with the locally indexed packages. + /// + /// The package's id to lookup + /// The token to cancel the lookup + /// + /// The metadata for all versions of a package, including unlisted versions. + /// Returns an empty list if the package cannot be found. + /// + Task> FindPackagesAsync(string id, CancellationToken cancellationToken); - /// - /// Attempt to find a package's metadata using mirroring. This will merge - /// results from the configured upstream source with the locally indexed packages. - /// - /// The package's id to lookup - /// The package's version to lookup - /// The token to cancel the lookup - /// - /// The metadata for single version of a package. - /// Returns null if the package does not exist. - /// - Task FindPackageOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Attempt to find a package's metadata using mirroring. This will merge + /// results from the configured upstream source with the locally indexed packages. + /// + /// The package's id to lookup + /// The package's version to lookup + /// The token to cancel the lookup + /// + /// The metadata for single version of a package. + /// Returns null if the package does not exist. + /// + Task FindPackageOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Determine whether a package exists locally or on the upstream source. - /// - /// The package id to search. - /// The package version to search. - /// A token to cancel the task. - /// Whether the package exists in the database. - Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Determine whether a package exists locally or on the upstream source. + /// + /// The package id to search. + /// The package version to search. + /// A token to cancel the task. + /// Whether the package exists in the database. + Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Increment a package's download count. - /// - /// The id of the package to update. - /// The id of the package to update. - /// A token to cancel the task. - Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken); - } -} + /// + /// Increment a package's download count. + /// + /// The id of the package to update. + /// The id of the package to update. + /// A token to cancel the task. + Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/IUrlGenerator.cs b/src/BaGet.Core/IUrlGenerator.cs index 2bf918201..4ef039967 100644 --- a/src/BaGet.Core/IUrlGenerator.cs +++ b/src/BaGet.Core/IUrlGenerator.cs @@ -1,166 +1,165 @@ using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Used to create URLs to resources in the NuGet protocol. +/// +public interface IUrlGenerator { /// - /// Used to create URLs to resources in the NuGet protocol. - /// - public interface IUrlGenerator - { - /// - /// Get the URL for the package source (also known as the "service index"). - /// See: https://docs.microsoft.com/en-us/nuget/api/service-index - /// - string GetServiceIndexUrl(); - - /// - /// Get the URL for the root of the package content resource. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource - /// - string GetPackageContentResourceUrl(); - - /// - /// Get the URL for the root of the package metadata resource. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource - /// - string GetPackageMetadataResourceUrl(); - - /// - /// Get the URL to publish packages. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource - /// - string GetPackagePublishResourceUrl(); - - /// - /// Get the URL to publish symbol packages. - /// See: https://docs.microsoft.com/en-us/nuget/api/symbol-package-publish-resource - /// - string GetSymbolPublishResourceUrl(); - - /// - /// Get the URL to search for packages. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource - /// - string GetSearchResourceUrl(); - - /// - /// Get the URL to autocomplete package IDs. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource - /// - string GetAutocompleteResourceUrl(); - - /// - /// Get the URL of the V2 (OData) feed, for clients that cannot use V3. - /// - string GetV2FeedUrl(); - - /// - /// Get the URI template a client expands to reach a package's details page. - /// The literal "{id}" and "{version}" placeholders are part of the value. - /// See: https://learn.microsoft.com/en-us/nuget/api/service-index#resources - /// - string GetPackageDetailsUriTemplate(); - - /// - /// Get the URI template a client expands to report a package as abusive. - /// The literal "{id}" and "{version}" placeholders are part of the value. - /// See: https://learn.microsoft.com/en-us/nuget/api/service-index#resources - /// - string GetReportAbuseUriTemplate(); - - /// - /// Get the URL of the vulnerability index, which lists the vulnerability pages. - /// See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info - /// - string GetVulnerabilityIndexUrl(); - - /// - /// Get the URL of one page of vulnerability data. - /// - /// The page's name, such as "base". - string GetVulnerabilityPageUrl(string pageName); - - /// - /// Get the URL of the catalog index. - /// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource - /// - string GetCatalogIndexUrl(); - - /// - /// Get the URL of one catalog page. - /// - /// The page's zero based index. - string GetCatalogPageUrl(int pageIndex); - - /// - /// Get the URL of one catalog leaf. - /// - /// The ID of the commit that wrote the leaf. - string GetCatalogLeafUrl(string commitId); - - /// - /// Get the URL of the repository signatures resource. - /// See: https://learn.microsoft.com/en-us/nuget/api/repository-signatures-resource - /// - string GetRepositorySignaturesUrl(); - - /// - /// Get the URL to download a repository signing certificate. - /// - /// The certificate's SHA-256 fingerprint, as lowercase hex. - string GetRepositorySigningCertificateUrl(string fingerprint); - - /// - /// Get the URL for the entry point of a package's metadata. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index - /// - /// The package's ID. - string GetRegistrationIndexUrl(string id); - - /// - /// Get the URL for the metadata of several versions of a single package. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - /// The package's ID - /// The lowest SemVer 2.0.0 version in the page (inclusive) - /// The highest SemVer 2.0.0 version in the page (inclusive) - string GetRegistrationPageUrl(string id, NuGetVersion lower, NuGetVersion upper); - - /// - /// Get the URL for the metadata of a specific package ID and version. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf - /// - /// The package's ID - /// The package's version - string GetRegistrationLeafUrl(string id, NuGetVersion version); - - /// - /// Get the URL that lists a package's versions. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions - /// - /// The package's ID - string GetPackageVersionsUrl(string id); - - /// - /// Get the URL to download a package (.nupkg). - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg - /// - /// The package's ID - /// The package's version - string GetPackageDownloadUrl(string id, NuGetVersion version); - - /// - /// Get the URL to download a package's manifest (.nuspec). - /// - /// The package's ID - /// The package's version - string GetPackageManifestDownloadUrl(string id, NuGetVersion version); - - /// - /// Get the URL to download a package icon. - /// - /// The package's ID - /// The package's version - string GetPackageIconDownloadUrl(string id, NuGetVersion version); - } -} + /// Get the URL for the package source (also known as the "service index"). + /// See: https://docs.microsoft.com/en-us/nuget/api/service-index + /// + string GetServiceIndexUrl(); + + /// + /// Get the URL for the root of the package content resource. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource + /// + string GetPackageContentResourceUrl(); + + /// + /// Get the URL for the root of the package metadata resource. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource + /// + string GetPackageMetadataResourceUrl(); + + /// + /// Get the URL to publish packages. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource + /// + string GetPackagePublishResourceUrl(); + + /// + /// Get the URL to publish symbol packages. + /// See: https://docs.microsoft.com/en-us/nuget/api/symbol-package-publish-resource + /// + string GetSymbolPublishResourceUrl(); + + /// + /// Get the URL to search for packages. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// + string GetSearchResourceUrl(); + + /// + /// Get the URL to autocomplete package IDs. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// + string GetAutocompleteResourceUrl(); + + /// + /// Get the URL of the V2 (OData) feed, for clients that cannot use V3. + /// + string GetV2FeedUrl(); + + /// + /// Get the URI template a client expands to reach a package's details page. + /// The literal "{id}" and "{version}" placeholders are part of the value. + /// See: https://learn.microsoft.com/en-us/nuget/api/service-index#resources + /// + string GetPackageDetailsUriTemplate(); + + /// + /// Get the URI template a client expands to report a package as abusive. + /// The literal "{id}" and "{version}" placeholders are part of the value. + /// See: https://learn.microsoft.com/en-us/nuget/api/service-index#resources + /// + string GetReportAbuseUriTemplate(); + + /// + /// Get the URL of the vulnerability index, which lists the vulnerability pages. + /// See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info + /// + string GetVulnerabilityIndexUrl(); + + /// + /// Get the URL of one page of vulnerability data. + /// + /// The page's name, such as "base". + string GetVulnerabilityPageUrl(string pageName); + + /// + /// Get the URL of the catalog index. + /// See: https://learn.microsoft.com/en-us/nuget/api/catalog-resource + /// + string GetCatalogIndexUrl(); + + /// + /// Get the URL of one catalog page. + /// + /// The page's zero based index. + string GetCatalogPageUrl(int pageIndex); + + /// + /// Get the URL of one catalog leaf. + /// + /// The ID of the commit that wrote the leaf. + string GetCatalogLeafUrl(string commitId); + + /// + /// Get the URL of the repository signatures resource. + /// See: https://learn.microsoft.com/en-us/nuget/api/repository-signatures-resource + /// + string GetRepositorySignaturesUrl(); + + /// + /// Get the URL to download a repository signing certificate. + /// + /// The certificate's SHA-256 fingerprint, as lowercase hex. + string GetRepositorySigningCertificateUrl(string fingerprint); + + /// + /// Get the URL for the entry point of a package's metadata. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index + /// + /// The package's ID. + string GetRegistrationIndexUrl(string id); + + /// + /// Get the URL for the metadata of several versions of a single package. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page + /// + /// The package's ID + /// The lowest SemVer 2.0.0 version in the page (inclusive) + /// The highest SemVer 2.0.0 version in the page (inclusive) + string GetRegistrationPageUrl(string id, NuGetVersion lower, NuGetVersion upper); + + /// + /// Get the URL for the metadata of a specific package ID and version. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf + /// + /// The package's ID + /// The package's version + string GetRegistrationLeafUrl(string id, NuGetVersion version); + + /// + /// Get the URL that lists a package's versions. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions + /// + /// The package's ID + string GetPackageVersionsUrl(string id); + + /// + /// Get the URL to download a package (.nupkg). + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg + /// + /// The package's ID + /// The package's version + string GetPackageDownloadUrl(string id, NuGetVersion version); + + /// + /// Get the URL to download a package's manifest (.nuspec). + /// + /// The package's ID + /// The package's version + string GetPackageManifestDownloadUrl(string id, NuGetVersion version); + + /// + /// Get the URL to download a package icon. + /// + /// The package's ID + /// The package's version + string GetPackageIconDownloadUrl(string id, NuGetVersion version); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/FrameworkCompatibilityService.cs b/src/BaGet.Core/Indexing/FrameworkCompatibilityService.cs index 4cf4820b2..cb7ce9691 100644 --- a/src/BaGet.Core/Indexing/FrameworkCompatibilityService.cs +++ b/src/BaGet.Core/Indexing/FrameworkCompatibilityService.cs @@ -4,87 +4,86 @@ using System.Linq; using NuGet.Frameworks; -namespace BaGet.Core +namespace BaGet.Core; + +using static NuGet.Frameworks.FrameworkConstants; + +public class FrameworkCompatibilityService : IFrameworkCompatibilityService { - using static NuGet.Frameworks.FrameworkConstants; + private const string AnyFramework = "any"; - public class FrameworkCompatibilityService : IFrameworkCompatibilityService + private static readonly Dictionary KnownFrameworks; + private static readonly IReadOnlyList CompatibilityMapping; + private static readonly ConcurrentDictionary> CompatibleFrameworks; + + static FrameworkCompatibilityService() { - private const string AnyFramework = "any"; + var supportedFrameworks = new HashSet(); + supportedFrameworks.Add(FrameworkIdentifiers.NetStandard); + supportedFrameworks.Add(FrameworkIdentifiers.NetCoreApp); + supportedFrameworks.Add(FrameworkIdentifiers.Net); - private static readonly Dictionary KnownFrameworks; - private static readonly IReadOnlyList CompatibilityMapping; - private static readonly ConcurrentDictionary> CompatibleFrameworks; + CompatibilityMapping = DefaultFrameworkMappings.Instance.CompatibilityMappings.ToList(); + CompatibleFrameworks = new ConcurrentDictionary>(); - static FrameworkCompatibilityService() - { - var supportedFrameworks = new HashSet(); - supportedFrameworks.Add(FrameworkIdentifiers.NetStandard); - supportedFrameworks.Add(FrameworkIdentifiers.NetCoreApp); - supportedFrameworks.Add(FrameworkIdentifiers.Net); + KnownFrameworks = typeof(CommonFrameworks) + .GetFields() + .Where(f => f.IsStatic) + .Where(f => f.FieldType == typeof(NuGetFramework)) + .Select(f => (NuGetFramework)f.GetValue(null)) + .Where(f => supportedFrameworks.Contains(f.Framework)) + .ToDictionary(f => f.GetShortFolderName()); - CompatibilityMapping = DefaultFrameworkMappings.Instance.CompatibilityMappings.ToList(); - CompatibleFrameworks = new ConcurrentDictionary>(); - - KnownFrameworks = typeof(CommonFrameworks) - .GetFields() - .Where(f => f.IsStatic) - .Where(f => f.FieldType == typeof(NuGetFramework)) - .Select(f => (NuGetFramework)f.GetValue(null)) - .Where(f => supportedFrameworks.Contains(f.Framework)) - .ToDictionary(f => f.GetShortFolderName()); + // Add more frameworks missing from "CommonFrameworks" + KnownFrameworks["net472"] = new NuGetFramework(FrameworkIdentifiers.Net, new Version(4, 7, 2, 0)); + KnownFrameworks["net471"] = new NuGetFramework(FrameworkIdentifiers.Net, new Version(4, 7, 1, 0)); + } - // Add more frameworks missing from "CommonFrameworks" - KnownFrameworks["net472"] = new NuGetFramework(FrameworkIdentifiers.Net, new Version(4, 7, 2, 0)); - KnownFrameworks["net471"] = new NuGetFramework(FrameworkIdentifiers.Net, new Version(4, 7, 1, 0)); + public IReadOnlyList FindAllCompatibleFrameworks(string name) + { + if (!KnownFrameworks.TryGetValue(name, out var framework)) + { + return new List { name, AnyFramework }; } - public IReadOnlyList FindAllCompatibleFrameworks(string name) - { - if (!KnownFrameworks.TryGetValue(name, out var framework)) - { - return new List { name, AnyFramework }; - } + return CompatibleFrameworks.GetOrAdd(framework, FindAllCompatibleFrameworks); + } - return CompatibleFrameworks.GetOrAdd(framework, FindAllCompatibleFrameworks); - } + private IReadOnlyList FindAllCompatibleFrameworks(NuGetFramework targetFramework) + { + var results = new HashSet { AnyFramework }; - private IReadOnlyList FindAllCompatibleFrameworks(NuGetFramework targetFramework) + // Find all framework mappings that apply to the target framework + foreach (var mapping in CompatibilityMapping) { - var results = new HashSet { AnyFramework }; - - // Find all framework mappings that apply to the target framework - foreach (var mapping in CompatibilityMapping) + // Skip this mapping if it isn't for our target framework. + if (!mapping.TargetFrameworkRange.Satisfies(targetFramework)) { - // Skip this mapping if it isn't for our target framework. - if (!mapping.TargetFrameworkRange.Satisfies(targetFramework)) - { - continue; - } - - // Any framework that satisfies this mapping is compatible with the target framework. - foreach (var possibleFramework in KnownFrameworks.Values) - { - if (mapping.SupportedFrameworkRange.Satisfies(possibleFramework)) - { - results.Add(possibleFramework.GetShortFolderName()); - } - } + continue; } - // Find all frameworks that have the same "framework identifier" and a version - // less than equal to our target framework. For example, "net45" is compatible - // with "net20" and "net45". + // Any framework that satisfies this mapping is compatible with the target framework. foreach (var possibleFramework in KnownFrameworks.Values) { - if (possibleFramework.Framework == targetFramework.Framework && - possibleFramework.Version <= targetFramework.Version) + if (mapping.SupportedFrameworkRange.Satisfies(possibleFramework)) { results.Add(possibleFramework.GetShortFolderName()); } } + } - return results.ToList(); + // Find all frameworks that have the same "framework identifier" and a version + // less than equal to our target framework. For example, "net45" is compatible + // with "net20" and "net45". + foreach (var possibleFramework in KnownFrameworks.Values) + { + if (possibleFramework.Framework == targetFramework.Framework && + possibleFramework.Version <= targetFramework.Version) + { + results.Add(possibleFramework.GetShortFolderName()); + } } + + return results.ToList(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IFrameworkCompatibilityService.cs b/src/BaGet.Core/Indexing/IFrameworkCompatibilityService.cs index 50f07256e..fec73792d 100644 --- a/src/BaGet.Core/Indexing/IFrameworkCompatibilityService.cs +++ b/src/BaGet.Core/Indexing/IFrameworkCompatibilityService.cs @@ -1,17 +1,16 @@ using System.Collections.Generic; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Used to determine the compatibility matrix between frameworks. +/// +public interface IFrameworkCompatibilityService { /// - /// Used to determine the compatibility matrix between frameworks. + /// Given a framework, find all other compatible frameworks. /// - public interface IFrameworkCompatibilityService - { - /// - /// Given a framework, find all other compatible frameworks. - /// - /// The input framework. - /// The list of compatible frameworks. - IReadOnlyList FindAllCompatibleFrameworks(string framework); - } -} + /// The input framework. + /// The list of compatible frameworks. + IReadOnlyList FindAllCompatibleFrameworks(string framework); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IPackageChangeHandler.cs b/src/BaGet.Core/Indexing/IPackageChangeHandler.cs index feabd6030..3a96a8654 100644 --- a/src/BaGet.Core/Indexing/IPackageChangeHandler.cs +++ b/src/BaGet.Core/Indexing/IPackageChangeHandler.cs @@ -2,22 +2,21 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Told about every change to a package version after it has been committed. Register +/// any number of these; calls each in turn. +/// +public interface IPackageChangeHandler { /// - /// Told about every change to a package version after it has been committed. Register - /// any number of these; calls each in turn. + /// The package version was added, relisted or unlisted, or its metadata changed. /// - public interface IPackageChangeHandler - { - /// - /// The package version was added, relisted or unlisted, or its metadata changed. - /// - Task OnPackageChangedAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + Task OnPackageChangedAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// The package version was permanently deleted. - /// - Task OnPackageDeletedAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - } -} + /// + /// The package version was permanently deleted. + /// + Task OnPackageDeletedAsync(string id, NuGetVersion version, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IPackageDeletionService.cs b/src/BaGet.Core/Indexing/IPackageDeletionService.cs index 691b99e8b..4d0c25ac1 100644 --- a/src/BaGet.Core/Indexing/IPackageDeletionService.cs +++ b/src/BaGet.Core/Indexing/IPackageDeletionService.cs @@ -2,17 +2,16 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public interface IPackageDeletionService { - public interface IPackageDeletionService - { - /// - /// Attempt to delete a package. - /// - /// The id of the package to delete. - /// The version of the package to delete. - /// - /// False if the package does not exist. - Task TryDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - } -} + /// + /// Attempt to delete a package. + /// + /// The id of the package to delete. + /// The version of the package to delete. + /// + /// False if the package does not exist. + Task TryDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IPackageIndexingService.cs b/src/BaGet.Core/Indexing/IPackageIndexingService.cs index db7844559..dea59eefc 100644 --- a/src/BaGet.Core/Indexing/IPackageIndexingService.cs +++ b/src/BaGet.Core/Indexing/IPackageIndexingService.cs @@ -2,46 +2,45 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The result of attempting to index a package. +/// See . +/// +public enum PackageIndexingResult { /// - /// The result of attempting to index a package. - /// See . + /// The package is malformed. This may also happen if BaGet is in a corrupted state. /// - public enum PackageIndexingResult - { - /// - /// The package is malformed. This may also happen if BaGet is in a corrupted state. - /// - InvalidPackage, - - /// - /// The package has already been indexed. - /// - PackageAlreadyExists, + InvalidPackage, - /// - /// The package has been indexed successfully. - /// - Success, + /// + /// The package has already been indexed. + /// + PackageAlreadyExists, - /// - /// The package was queued for validation and is not available yet. - /// - Accepted, - } + /// + /// The package has been indexed successfully. + /// + Success, /// - /// The service used to accept new packages. + /// The package was queued for validation and is not available yet. /// - public interface IPackageIndexingService - { - /// - /// Attempt to index a new package. - /// - /// The stream containing the package's content. - /// - /// The result of the attempted indexing operation. - Task IndexAsync(Stream stream, CancellationToken cancellationToken); - } + Accepted, } + +/// +/// The service used to accept new packages. +/// +public interface IPackageIndexingService +{ + /// + /// Attempt to index a new package. + /// + /// The stream containing the package's content. + /// + /// The result of the attempted indexing operation. + Task IndexAsync(Stream stream, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/IPackageSubmissionService.cs b/src/BaGet.Core/Indexing/IPackageSubmissionService.cs index c6e5466c4..1e9209437 100644 --- a/src/BaGet.Core/Indexing/IPackageSubmissionService.cs +++ b/src/BaGet.Core/Indexing/IPackageSubmissionService.cs @@ -2,34 +2,33 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core -{ - /// - /// Accepts a package a user pushed. Unlike , which - /// always indexes at once and which mirroring uses, a submission may be validated first. - /// - public interface IPackageSubmissionService - { - /// - /// if the package is queued for - /// validation, otherwise the result of indexing it. - /// - Task SubmitAsync(Stream package, CancellationToken cancellationToken); - } +namespace BaGet.Core; - /// - /// Indexes every submission at once: the behaviour without validation. - /// - public class DirectPackageSubmissionService : IPackageSubmissionService - { - private readonly IPackageIndexingService _indexer; +/// +/// Accepts a package a user pushed. Unlike , which +/// always indexes at once and which mirroring uses, a submission may be validated first. +/// +public interface IPackageSubmissionService +{ + /// + /// if the package is queued for + /// validation, otherwise the result of indexing it. + /// + Task SubmitAsync(Stream package, CancellationToken cancellationToken); +} - public DirectPackageSubmissionService(IPackageIndexingService indexer) - { - _indexer = indexer ?? throw new System.ArgumentNullException(nameof(indexer)); - } +/// +/// Indexes every submission at once: the behaviour without validation. +/// +public class DirectPackageSubmissionService : IPackageSubmissionService +{ + private readonly IPackageIndexingService _indexer; - public Task SubmitAsync(Stream package, CancellationToken cancellationToken) - => _indexer.IndexAsync(package, cancellationToken); + public DirectPackageSubmissionService(IPackageIndexingService indexer) + { + _indexer = indexer ?? throw new System.ArgumentNullException(nameof(indexer)); } -} + + public Task SubmitAsync(Stream package, CancellationToken cancellationToken) + => _indexer.IndexAsync(package, cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/ISymbolIndexingService.cs b/src/BaGet.Core/Indexing/ISymbolIndexingService.cs index 85a671a96..0abe307ce 100644 --- a/src/BaGet.Core/Indexing/ISymbolIndexingService.cs +++ b/src/BaGet.Core/Indexing/ISymbolIndexingService.cs @@ -2,41 +2,40 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The result of attempting to index a symbol package. +/// See . +/// +public enum SymbolIndexingResult { /// - /// The result of attempting to index a symbol package. - /// See . + /// The symbol package is malformed. /// - public enum SymbolIndexingResult - { - /// - /// The symbol package is malformed. - /// - InvalidSymbolPackage, - - /// - /// A corresponding package with the provided ID and version does not exist. - /// - PackageNotFound, + InvalidSymbolPackage, - /// - /// The symbol package has been indexed successfully. - /// - Success, - } + /// + /// A corresponding package with the provided ID and version does not exist. + /// + PackageNotFound, /// - /// The service used to accept new symbol packages. + /// The symbol package has been indexed successfully. /// - public interface ISymbolIndexingService - { - /// - /// Attempt to index a new symbol package. - /// - /// The stream containing the symbol package's content. - /// - /// The result of the attempted indexing operation. - Task IndexAsync(Stream stream, CancellationToken cancellationToken); - } + Success, } + +/// +/// The service used to accept new symbol packages. +/// +public interface ISymbolIndexingService +{ + /// + /// Attempt to index a new symbol package. + /// + /// The stream containing the symbol package's content. + /// + /// The result of the attempted indexing operation. + Task IndexAsync(Stream stream, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/PackageChangeNotifier.cs b/src/BaGet.Core/Indexing/PackageChangeNotifier.cs index 1d503c37e..bea132ca9 100644 --- a/src/BaGet.Core/Indexing/PackageChangeNotifier.cs +++ b/src/BaGet.Core/Indexing/PackageChangeNotifier.cs @@ -6,60 +6,59 @@ using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Calls every registered . The change has already +/// been committed when this runs, so a handler's failure is logged and never fails the +/// operation that made the change. +/// +public class PackageChangeNotifier { /// - /// Calls every registered . The change has already - /// been committed when this runs, so a handler's failure is logged and never fails the - /// operation that made the change. + /// A notifier with no handlers, for callers constructed without one. /// - public class PackageChangeNotifier - { - /// - /// A notifier with no handlers, for callers constructed without one. - /// - public static readonly PackageChangeNotifier None = - new PackageChangeNotifier(Array.Empty(), logger: null); + public static readonly PackageChangeNotifier None = + new PackageChangeNotifier(Array.Empty(), logger: null); - private readonly IReadOnlyList _handlers; - private readonly ILogger _logger; + private readonly IReadOnlyList _handlers; + private readonly ILogger _logger; - public PackageChangeNotifier( - IEnumerable handlers, - ILogger logger) - { - _handlers = handlers?.ToList() ?? throw new ArgumentNullException(nameof(handlers)); - _logger = logger; - } + public PackageChangeNotifier( + IEnumerable handlers, + ILogger logger) + { + _handlers = handlers?.ToList() ?? throw new ArgumentNullException(nameof(handlers)); + _logger = logger; + } - public Task PackageChangedAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - => NotifyAsync(id, version, (h, ct) => h.OnPackageChangedAsync(id, version, ct), cancellationToken); + public Task PackageChangedAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + => NotifyAsync(id, version, (h, ct) => h.OnPackageChangedAsync(id, version, ct), cancellationToken); - public Task PackageDeletedAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - => NotifyAsync(id, version, (h, ct) => h.OnPackageDeletedAsync(id, version, ct), cancellationToken); + public Task PackageDeletedAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + => NotifyAsync(id, version, (h, ct) => h.OnPackageDeletedAsync(id, version, ct), cancellationToken); - private async Task NotifyAsync( - string id, - NuGetVersion version, - Func notify, - CancellationToken cancellationToken) + private async Task NotifyAsync( + string id, + NuGetVersion version, + Func notify, + CancellationToken cancellationToken) + { + foreach (var handler in _handlers) { - foreach (var handler in _handlers) + try + { + await notify(handler, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException && cancellationToken.IsCancellationRequested)) { - try - { - await notify(handler, cancellationToken); - } - catch (Exception e) when (!(e is OperationCanceledException && cancellationToken.IsCancellationRequested)) - { - _logger?.LogError( - e, - "{Handler} failed for package {PackageId} {PackageVersion}", - handler.GetType().Name, - id, - version); - } + _logger?.LogError( + e, + "{Handler} failed for package {PackageId} {PackageVersion}", + handler.GetType().Name, + id, + version); } } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/PackageDeletionService.cs b/src/BaGet.Core/Indexing/PackageDeletionService.cs index da6f9ab1b..245dbd202 100644 --- a/src/BaGet.Core/Indexing/PackageDeletionService.cs +++ b/src/BaGet.Core/Indexing/PackageDeletionService.cs @@ -5,107 +5,106 @@ using Microsoft.Extensions.Options; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageDeletionService : IPackageDeletionService { - public class PackageDeletionService : IPackageDeletionService + private readonly IPackageDatabase _packages; + private readonly IPackageStorageService _storage; + private readonly BaGetOptions _options; + private readonly ILogger _logger; + private readonly PackageChangeNotifier _notifier; + + public PackageDeletionService( + IPackageDatabase packages, + IPackageStorageService storage, + IOptionsSnapshot options, + ILogger logger) + : this(packages, storage, options, logger, PackageChangeNotifier.None) { - private readonly IPackageDatabase _packages; - private readonly IPackageStorageService _storage; - private readonly BaGetOptions _options; - private readonly ILogger _logger; - private readonly PackageChangeNotifier _notifier; - - public PackageDeletionService( - IPackageDatabase packages, - IPackageStorageService storage, - IOptionsSnapshot options, - ILogger logger) - : this(packages, storage, options, logger, PackageChangeNotifier.None) - { - } + } - public PackageDeletionService( - IPackageDatabase packages, - IPackageStorageService storage, - IOptionsSnapshot options, - ILogger logger, - PackageChangeNotifier notifier) - { - _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public PackageDeletionService( + IPackageDatabase packages, + IPackageStorageService storage, + IOptionsSnapshot options, + ILogger logger, + PackageChangeNotifier notifier) + { + _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task TryDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + public async Task TryDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + switch (_options.PackageDeletionBehavior) { - switch (_options.PackageDeletionBehavior) - { - case PackageDeletionBehavior.Unlist: - return await TryUnlistPackageAsync(id, version, cancellationToken); + case PackageDeletionBehavior.Unlist: + return await TryUnlistPackageAsync(id, version, cancellationToken); - case PackageDeletionBehavior.HardDelete: - return await TryHardDeletePackageAsync(id, version, cancellationToken); + case PackageDeletionBehavior.HardDelete: + return await TryHardDeletePackageAsync(id, version, cancellationToken); - default: - throw new InvalidOperationException($"Unknown deletion behavior '{_options.PackageDeletionBehavior}'"); - } + default: + throw new InvalidOperationException($"Unknown deletion behavior '{_options.PackageDeletionBehavior}'"); } + } + + private async Task TryUnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + _logger.LogInformation("Unlisting package {PackageId} {PackageVersion}...", id, version); - private async Task TryUnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + if (!await _packages.UnlistPackageAsync(id, version, cancellationToken)) { - _logger.LogInformation("Unlisting package {PackageId} {PackageVersion}...", id, version); + _logger.LogWarning("Could not find package {PackageId} {PackageVersion}", id, version); - if (!await _packages.UnlistPackageAsync(id, version, cancellationToken)) - { - _logger.LogWarning("Could not find package {PackageId} {PackageVersion}", id, version); + return false; + } - return false; - } + _logger.LogInformation("Unlisted package {PackageId} {PackageVersion}", id, version); - _logger.LogInformation("Unlisted package {PackageId} {PackageVersion}", id, version); + await _notifier.PackageChangedAsync(id, version, cancellationToken); - await _notifier.PackageChangedAsync(id, version, cancellationToken); + return true; + } - return true; - } + private async Task TryHardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + _logger.LogInformation( + "Hard deleting package {PackageId} {PackageVersion} from the database...", + id, + version); - private async Task TryHardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + var found = await _packages.HardDeletePackageAsync(id, version, cancellationToken); + if (!found) { - _logger.LogInformation( - "Hard deleting package {PackageId} {PackageVersion} from the database...", - id, - version); - - var found = await _packages.HardDeletePackageAsync(id, version, cancellationToken); - if (!found) - { - _logger.LogWarning( - "Could not find package {PackageId} {PackageVersion} in the database", - id, - version); - } - - // Delete the package from storage. This is necessary even if the package isn't - // in the database to ensure that the storage is consistent with the database. - _logger.LogInformation("Hard deleting package {PackageId} {PackageVersion} from storage...", + _logger.LogWarning( + "Could not find package {PackageId} {PackageVersion} in the database", id, version); + } - await _storage.DeleteAsync(id, version, cancellationToken); + // Delete the package from storage. This is necessary even if the package isn't + // in the database to ensure that the storage is consistent with the database. + _logger.LogInformation("Hard deleting package {PackageId} {PackageVersion} from storage...", + id, + version); - _logger.LogInformation( - "Hard deleted package {PackageId} {PackageVersion} from storage", - id, - version); + await _storage.DeleteAsync(id, version, cancellationToken); - if (found) - { - await _notifier.PackageDeletedAsync(id, version, cancellationToken); - } + _logger.LogInformation( + "Hard deleted package {PackageId} {PackageVersion} from storage", + id, + version); - return found; + if (found) + { + await _notifier.PackageDeletedAsync(id, version, cancellationToken); } + + return found; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/PackageIndexingService.cs b/src/BaGet.Core/Indexing/PackageIndexingService.cs index 358e5b4c6..6444fb11b 100644 --- a/src/BaGet.Core/Indexing/PackageIndexingService.cs +++ b/src/BaGet.Core/Indexing/PackageIndexingService.cs @@ -6,197 +6,196 @@ using Microsoft.Extensions.Options; using NuGet.Packaging; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageIndexingService : IPackageIndexingService { - public class PackageIndexingService : IPackageIndexingService + private readonly IPackageDatabase _packages; + private readonly IPackageStorageService _storage; + private readonly ISearchIndexer _search; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + private readonly ILogger _logger; + private readonly PackageChangeNotifier _notifier; + + public PackageIndexingService( + IPackageDatabase packages, + IPackageStorageService storage, + ISearchIndexer search, + SystemTime time, + IOptionsSnapshot options, + ILogger logger) + : this(packages, storage, search, time, options, logger, PackageChangeNotifier.None) { - private readonly IPackageDatabase _packages; - private readonly IPackageStorageService _storage; - private readonly ISearchIndexer _search; - private readonly SystemTime _time; - private readonly IOptionsSnapshot _options; - private readonly ILogger _logger; - private readonly PackageChangeNotifier _notifier; - - public PackageIndexingService( - IPackageDatabase packages, - IPackageStorageService storage, - ISearchIndexer search, - SystemTime time, - IOptionsSnapshot options, - ILogger logger) - : this(packages, storage, search, time, options, logger, PackageChangeNotifier.None) - { - } + } - public PackageIndexingService( - IPackageDatabase packages, - IPackageStorageService storage, - ISearchIndexer search, - SystemTime time, - IOptionsSnapshot options, - ILogger logger, - PackageChangeNotifier notifier) - { - _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _search = search ?? throw new ArgumentNullException(nameof(search)); - _time = time ?? throw new ArgumentNullException(nameof(time)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public PackageIndexingService( + IPackageDatabase packages, + IPackageStorageService storage, + ISearchIndexer search, + SystemTime time, + IOptionsSnapshot options, + ILogger logger, + PackageChangeNotifier notifier) + { + _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _search = search ?? throw new ArgumentNullException(nameof(search)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task IndexAsync(Stream packageStream, CancellationToken cancellationToken) - { - // Try to extract all the necessary information from the package. - Package package; - Stream nuspecStream; - Stream readmeStream; - Stream iconStream; + public async Task IndexAsync(Stream packageStream, CancellationToken cancellationToken) + { + // Try to extract all the necessary information from the package. + Package package; + Stream nuspecStream; + Stream readmeStream; + Stream iconStream; - try - { - using (var packageReader = new PackageArchiveReader(packageStream, leaveStreamOpen: true)) - { - // Reject packages whose entries cannot be extracted safely, such as an - // entry whose path escapes the extraction directory. - await packageReader.ValidatePackageEntriesAsync(cancellationToken); - - package = packageReader.GetPackageMetadata(); - package.Published = _time.UtcNow; - - nuspecStream = await packageReader.GetNuspecAsync(cancellationToken); - nuspecStream = await nuspecStream.AsTemporaryFileStreamAsync(cancellationToken); - - if (package.HasReadme) - { - readmeStream = await packageReader.GetReadmeAsync(cancellationToken); - readmeStream = await readmeStream.AsTemporaryFileStreamAsync(cancellationToken); - } - else - { - readmeStream = null; - } - - if (package.HasEmbeddedIcon) - { - iconStream = await packageReader.GetIconAsync(cancellationToken); - iconStream = await iconStream.AsTemporaryFileStreamAsync(cancellationToken); - } - else - { - iconStream = null; - } - } - } - catch (Exception e) + try + { + using (var packageReader = new PackageArchiveReader(packageStream, leaveStreamOpen: true)) { - _logger.LogError(e, "Uploaded package is invalid"); + // Reject packages whose entries cannot be extracted safely, such as an + // entry whose path escapes the extraction directory. + await packageReader.ValidatePackageEntriesAsync(cancellationToken); - return PackageIndexingResult.InvalidPackage; - } + package = packageReader.GetPackageMetadata(); + package.Published = _time.UtcNow; - // The package is well-formed. Ensure this is a new package. - if (await _packages.ExistsAsync(package.Id, package.Version, cancellationToken)) - { - if (!_options.Value.AllowPackageOverwrites) + nuspecStream = await packageReader.GetNuspecAsync(cancellationToken); + nuspecStream = await nuspecStream.AsTemporaryFileStreamAsync(cancellationToken); + + if (package.HasReadme) + { + readmeStream = await packageReader.GetReadmeAsync(cancellationToken); + readmeStream = await readmeStream.AsTemporaryFileStreamAsync(cancellationToken); + } + else { - return PackageIndexingResult.PackageAlreadyExists; + readmeStream = null; } - await _packages.HardDeletePackageAsync(package.Id, package.Version, cancellationToken); - await _storage.DeleteAsync(package.Id, package.Version, cancellationToken); + if (package.HasEmbeddedIcon) + { + iconStream = await packageReader.GetIconAsync(cancellationToken); + iconStream = await iconStream.AsTemporaryFileStreamAsync(cancellationToken); + } + else + { + iconStream = null; + } } + } + catch (Exception e) + { + _logger.LogError(e, "Uploaded package is invalid"); - // TODO: Add more package validations - _logger.LogInformation( - "Validated package {PackageId} {PackageVersion}, persisting content to storage...", - package.Id, - package.NormalizedVersionString); - - PackageSaveResult storageResult; + return PackageIndexingResult.InvalidPackage; + } - try + // The package is well-formed. Ensure this is a new package. + if (await _packages.ExistsAsync(package.Id, package.Version, cancellationToken)) + { + if (!_options.Value.AllowPackageOverwrites) { - packageStream.Position = 0; - - storageResult = await _storage.SavePackageContentAsync( - package, - packageStream, - nuspecStream, - readmeStream, - iconStream, - cancellationToken); + return PackageIndexingResult.PackageAlreadyExists; } - catch (Exception e) - { - _logger.LogError( - e, - "Failed to persist package {PackageId} {PackageVersion} content to storage", - package.Id, - package.NormalizedVersionString); - throw; - } + await _packages.HardDeletePackageAsync(package.Id, package.Version, cancellationToken); + await _storage.DeleteAsync(package.Id, package.Version, cancellationToken); + } - if (storageResult == PackageSaveResult.Conflict) - { - // Content for this id/version is already stored and differs from what was pushed. - // This may happen due to concurrent pushes. - _logger.LogWarning( - "Package {PackageId} {PackageVersion} content conflicts with the content already in storage", - package.Id, - package.NormalizedVersionString); + // TODO: Add more package validations + _logger.LogInformation( + "Validated package {PackageId} {PackageVersion}, persisting content to storage...", + package.Id, + package.NormalizedVersionString); - return PackageIndexingResult.PackageAlreadyExists; - } + PackageSaveResult storageResult; - if (storageResult != PackageSaveResult.Success) - { - _logger.LogError($"Unknown {nameof(PackageSaveResult)} value: {{PackageSaveResult}}", storageResult); + try + { + packageStream.Position = 0; + + storageResult = await _storage.SavePackageContentAsync( + package, + packageStream, + nuspecStream, + readmeStream, + iconStream, + cancellationToken); + } + catch (Exception e) + { + _logger.LogError( + e, + "Failed to persist package {PackageId} {PackageVersion} content to storage", + package.Id, + package.NormalizedVersionString); - throw new InvalidOperationException($"Unknown {nameof(PackageSaveResult)} value: {storageResult}"); - } + throw; + } - _logger.LogInformation( - "Persisted package {Id} {Version} content to storage, saving metadata to database...", + if (storageResult == PackageSaveResult.Conflict) + { + // Content for this id/version is already stored and differs from what was pushed. + // This may happen due to concurrent pushes. + _logger.LogWarning( + "Package {PackageId} {PackageVersion} content conflicts with the content already in storage", package.Id, package.NormalizedVersionString); - var result = await _packages.AddAsync(package, cancellationToken); - if (result == PackageAddResult.PackageAlreadyExists) - { - _logger.LogWarning( - "Package {Id} {Version} metadata already exists in database", - package.Id, - package.NormalizedVersionString); + return PackageIndexingResult.PackageAlreadyExists; + } - return PackageIndexingResult.PackageAlreadyExists; - } + if (storageResult != PackageSaveResult.Success) + { + _logger.LogError($"Unknown {nameof(PackageSaveResult)} value: {{PackageSaveResult}}", storageResult); - if (result != PackageAddResult.Success) - { - _logger.LogError($"Unknown {nameof(PackageAddResult)} value: {{PackageAddResult}}", result); + throw new InvalidOperationException($"Unknown {nameof(PackageSaveResult)} value: {storageResult}"); + } - throw new InvalidOperationException($"Unknown {nameof(PackageAddResult)} value: {result}"); - } + _logger.LogInformation( + "Persisted package {Id} {Version} content to storage, saving metadata to database...", + package.Id, + package.NormalizedVersionString); - _logger.LogInformation( - "Successfully persisted package {Id} {Version} metadata to database. Indexing in search...", + var result = await _packages.AddAsync(package, cancellationToken); + if (result == PackageAddResult.PackageAlreadyExists) + { + _logger.LogWarning( + "Package {Id} {Version} metadata already exists in database", package.Id, package.NormalizedVersionString); - await _search.IndexAsync(package, cancellationToken); - - _logger.LogInformation( - "Successfully indexed package {Id} {Version} in search", - package.Id, - package.NormalizedVersionString); + return PackageIndexingResult.PackageAlreadyExists; + } - await _notifier.PackageChangedAsync(package.Id, package.Version, cancellationToken); + if (result != PackageAddResult.Success) + { + _logger.LogError($"Unknown {nameof(PackageAddResult)} value: {{PackageAddResult}}", result); - return PackageIndexingResult.Success; + throw new InvalidOperationException($"Unknown {nameof(PackageAddResult)} value: {result}"); } + + _logger.LogInformation( + "Successfully persisted package {Id} {Version} metadata to database. Indexing in search...", + package.Id, + package.NormalizedVersionString); + + await _search.IndexAsync(package, cancellationToken); + + _logger.LogInformation( + "Successfully indexed package {Id} {Version} in search", + package.Id, + package.NormalizedVersionString); + + await _notifier.PackageChangedAsync(package.Id, package.Version, cancellationToken); + + return PackageIndexingResult.Success; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Indexing/SymbolIndexingService.cs b/src/BaGet.Core/Indexing/SymbolIndexingService.cs index 1bd6c14d0..5a1dbb6be 100644 --- a/src/BaGet.Core/Indexing/SymbolIndexingService.cs +++ b/src/BaGet.Core/Indexing/SymbolIndexingService.cs @@ -11,445 +11,444 @@ using NuGet.Packaging.Core; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +// Based off: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery/Services/SymbolPackageUploadService.cs +// Based off: https://github.com/NuGet/NuGet.Jobs/blob/master/src/Validation.Symbols/SymbolsValidatorService.cs#L44 +public class SymbolIndexingService : ISymbolIndexingService { - // Based off: https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery/Services/SymbolPackageUploadService.cs - // Based off: https://github.com/NuGet/NuGet.Jobs/blob/master/src/Validation.Symbols/SymbolsValidatorService.cs#L44 - public class SymbolIndexingService : ISymbolIndexingService + // Entry paths inside a package are matched case-insensitively, so an extension + // must be too: a symbol package carrying "Library.PDB" is valid. + private static readonly HashSet ValidSymbolPackageContentExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) { - // Entry paths inside a package are matched case-insensitively, so an extension - // must be too: a symbol package carrying "Library.PDB" is valid. - private static readonly HashSet ValidSymbolPackageContentExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) - { - ".pdb", - ".nuspec", - ".xml", - ".psmdcp", - ".rels", - ".p7s" - }; - - // The extensions of the files a PDB can describe, most likely first. - private static readonly string[] AssemblyExtensions = { ".dll", ".exe" }; - - // "BSJB": the signature at the start of the ECMA-335 metadata root, which is what a - // portable PDB is. A Windows PDB starts with "Microsoft C/C++ MSF 7.00" instead, and - // a file that is not a PDB at all starts with something else again. - private static readonly byte[] PortablePdbSignature = { 0x42, 0x53, 0x4A, 0x42 }; - - // The length of a portable PDB's debug metadata id: a 16 byte GUID and a 4 byte stamp. - private const int DebugMetadataIdLength = 20; - - private readonly IPackageDatabase _packages; - private readonly IPackageStorageService _packageStorage; - private readonly ISymbolStorageService _storage; - private readonly ILogger _logger; - - public SymbolIndexingService( - IPackageDatabase packages, - IPackageStorageService packageStorage, - ISymbolStorageService storage, - ILogger logger) - { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _packageStorage = packageStorage ?? throw new ArgumentNullException(nameof(packageStorage)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + ".pdb", + ".nuspec", + ".xml", + ".psmdcp", + ".rels", + ".p7s" + }; + + // The extensions of the files a PDB can describe, most likely first. + private static readonly string[] AssemblyExtensions = { ".dll", ".exe" }; + + // "BSJB": the signature at the start of the ECMA-335 metadata root, which is what a + // portable PDB is. A Windows PDB starts with "Microsoft C/C++ MSF 7.00" instead, and + // a file that is not a PDB at all starts with something else again. + private static readonly byte[] PortablePdbSignature = { 0x42, 0x53, 0x4A, 0x42 }; + + // The length of a portable PDB's debug metadata id: a 16 byte GUID and a 4 byte stamp. + private const int DebugMetadataIdLength = 20; + + private readonly IPackageDatabase _packages; + private readonly IPackageStorageService _packageStorage; + private readonly ISymbolStorageService _storage; + private readonly ILogger _logger; + + public SymbolIndexingService( + IPackageDatabase packages, + IPackageStorageService packageStorage, + ISymbolStorageService storage, + ILogger logger) + { + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _packageStorage = packageStorage ?? throw new ArgumentNullException(nameof(packageStorage)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task IndexAsync(Stream stream, CancellationToken cancellationToken) + public async Task IndexAsync(Stream stream, CancellationToken cancellationToken) + { + try { - try + using (var symbolPackage = new PackageArchiveReader(stream, leaveStreamOpen: true)) { - using (var symbolPackage = new PackageArchiveReader(stream, leaveStreamOpen: true)) + var pdbPaths = await GetSymbolPackagePdbPathsOrNullAsync(symbolPackage, cancellationToken); + if (pdbPaths == null) { - var pdbPaths = await GetSymbolPackagePdbPathsOrNullAsync(symbolPackage, cancellationToken); - if (pdbPaths == null) - { - return SymbolIndexingResult.InvalidSymbolPackage; - } + return SymbolIndexingResult.InvalidSymbolPackage; + } - // Ensure a corresponding NuGet package exists. - var packageId = symbolPackage.NuspecReader.GetId(); - var packageVersion = symbolPackage.NuspecReader.GetVersion(); + // Ensure a corresponding NuGet package exists. + var packageId = symbolPackage.NuspecReader.GetId(); + var packageVersion = symbolPackage.NuspecReader.GetVersion(); - var package = await _packages.FindOrNullAsync(packageId, packageVersion, includeUnlisted: true, cancellationToken); - if (package == null) - { - _logger.LogWarning( - "Rejecting symbol package {PackageId} {PackageVersion}: the package it belongs to does not exist", - packageId, - packageVersion.ToNormalizedString()); - return SymbolIndexingResult.PackageNotFound; - } + var package = await _packages.FindOrNullAsync(packageId, packageVersion, includeUnlisted: true, cancellationToken); + if (package == null) + { + _logger.LogWarning( + "Rejecting symbol package {PackageId} {PackageVersion}: the package it belongs to does not exist", + packageId, + packageVersion.ToNormalizedString()); + return SymbolIndexingResult.PackageNotFound; + } - using (var pdbs = new PdbList()) + using (var pdbs = new PdbList()) + { + // Extract the portable PDBs from the snupkg. Nothing is persisted until after all + // PDBs have been extracted and validated sucessfully. + foreach (var pdbPath in pdbPaths) { - // Extract the portable PDBs from the snupkg. Nothing is persisted until after all - // PDBs have been extracted and validated sucessfully. - foreach (var pdbPath in pdbPaths) - { - var portablePdb = await ExtractPortablePdbOrNullAsync(symbolPackage, pdbPath, cancellationToken); - if (portablePdb == null) - { - return SymbolIndexingResult.InvalidSymbolPackage; - } - - pdbs.Add(portablePdb); - } - - // Every PDB must describe a file the package itself ships, otherwise the - // symbol server would serve symbols for code that is not in the package. - if (!await PdbsDescribePackageAsync(packageId, packageVersion, pdbs, cancellationToken)) + var portablePdb = await ExtractPortablePdbOrNullAsync(symbolPackage, pdbPath, cancellationToken); + if (portablePdb == null) { return SymbolIndexingResult.InvalidSymbolPackage; } - // Persist the portable PDBs to storage. - foreach (var pdb in pdbs) - { - pdb.Content.Position = 0; - await _storage.SavePortablePdbContentAsync(pdb.Filename, pdb.Key, pdb.Content, cancellationToken); - } + pdbs.Add(portablePdb); + } + + // Every PDB must describe a file the package itself ships, otherwise the + // symbol server would serve symbols for code that is not in the package. + if (!await PdbsDescribePackageAsync(packageId, packageVersion, pdbs, cancellationToken)) + { + return SymbolIndexingResult.InvalidSymbolPackage; + } - return SymbolIndexingResult.Success; + // Persist the portable PDBs to storage. + foreach (var pdb in pdbs) + { + pdb.Content.Position = 0; + await _storage.SavePortablePdbContentAsync(pdb.Filename, pdb.Key, pdb.Content, cancellationToken); } + + return SymbolIndexingResult.Success; } } - catch (Exception e) - { - _logger.LogError(e, "Unable to index symbol package due to exception"); - return SymbolIndexingResult.InvalidSymbolPackage; - } } - - private async Task> GetSymbolPackagePdbPathsOrNullAsync( - PackageArchiveReader symbolPackage, - CancellationToken cancellationToken) + catch (Exception e) { - try - { - await symbolPackage.ValidatePackageEntriesAsync(cancellationToken); - } - catch (PackagingException e) - { - // An entry whose path escapes the extraction directory, such as "../../evil.pdb", - // or that is otherwise unusable. Say so: otherwise the only trace a rejected - // upload leaves is an "invalid symbol package" with no reason attached. - _logger.LogError(e, "Rejecting symbol package: its entries are not safe to extract"); - return null; - } - - var files = (await symbolPackage.GetFilesAsync(cancellationToken)).ToList(); - - // Ensure there are no unexpected file extensions within the symbol package. - var invalidFiles = files.Where(file => !IsValidSymbolFile(file)).ToList(); - if (invalidFiles.Count > 0) - { - _logger.LogError( - "Rejecting symbol package: the entries {InvalidEntries} do not have an extension a symbol package may contain", - string.Join(", ", invalidFiles)); - return null; - } - - return files.Where(IsPdbPath).ToList(); + _logger.LogError(e, "Unable to index symbol package due to exception"); + return SymbolIndexingResult.InvalidSymbolPackage; } + } - internal static bool IsPdbPath(string path) + private async Task> GetSymbolPackagePdbPathsOrNullAsync( + PackageArchiveReader symbolPackage, + CancellationToken cancellationToken) + { + try { - return string.Equals(Path.GetExtension(path), ".pdb", StringComparison.OrdinalIgnoreCase); + await symbolPackage.ValidatePackageEntriesAsync(cancellationToken); } - - internal static bool IsValidSymbolFile(string entry) + catch (PackagingException e) { - if (string.IsNullOrEmpty(Path.GetFileName(entry))) return false; - - var extension = Path.GetExtension(entry); - if (string.IsNullOrEmpty(extension)) return false; - - return ValidSymbolPackageContentExtensions.Contains(extension); + // An entry whose path escapes the extraction directory, such as "../../evil.pdb", + // or that is otherwise unusable. Say so: otherwise the only trace a rejected + // upload leaves is an "invalid symbol package" with no reason attached. + _logger.LogError(e, "Rejecting symbol package: its entries are not safe to extract"); + return null; } - internal static bool AreSymbolFilesValid(IReadOnlyList entries) + var files = (await symbolPackage.GetFilesAsync(cancellationToken)).ToList(); + + // Ensure there are no unexpected file extensions within the symbol package. + var invalidFiles = files.Where(file => !IsValidSymbolFile(file)).ToList(); + if (invalidFiles.Count > 0) { - return entries.All(IsValidSymbolFile); + _logger.LogError( + "Rejecting symbol package: the entries {InvalidEntries} do not have an extension a symbol package may contain", + string.Join(", ", invalidFiles)); + return null; } - private async Task ExtractPortablePdbOrNullAsync( - PackageArchiveReader symbolPackage, - string pdbPath, - CancellationToken cancellationToken) - { - Stream pdbStream = null; - PortablePdb result = null; + return files.Where(IsPdbPath).ToList(); + } - try - { - using (var rawPdbStream = await symbolPackage.GetStreamAsync(pdbPath, cancellationToken)) - { - pdbStream = await rawPdbStream.AsTemporaryFileStreamAsync(cancellationToken); + internal static bool IsPdbPath(string path) + { + return string.Equals(Path.GetExtension(path), ".pdb", StringComparison.OrdinalIgnoreCase); + } - // A symbol package may only carry portable PDBs. A Windows PDB cannot be read - // as metadata and cannot be keyed for the symbol server, so reject it here - // with a reason rather than letting the metadata reader throw. - if (!HasPortablePdbSignature(pdbStream)) - { - _logger.LogError( - "Rejecting symbol package: the entry {PdbPath} is not a portable PDB", - pdbPath); - return null; - } + internal static bool IsValidSymbolFile(string entry) + { + if (string.IsNullOrEmpty(Path.GetFileName(entry))) return false; - var signature = ReadPortablePdbSignatureOrNull(pdbStream, pdbPath); - if (signature == null) - { - return null; - } + var extension = Path.GetExtension(entry); + if (string.IsNullOrEmpty(extension)) return false; - var fileName = Path.GetFileName(pdbPath).ToLowerInvariant(); - var key = $"{signature.Value.ToString("N").ToUpperInvariant()}ffffffff"; + return ValidSymbolPackageContentExtensions.Contains(extension); + } - pdbStream.Position = 0; - result = new PortablePdb(pdbPath, fileName, key, signature.Value, pdbStream); - } - } - finally - { - if (result == null) - { - pdbStream?.Dispose(); - } - } + internal static bool AreSymbolFilesValid(IReadOnlyList entries) + { + return entries.All(IsValidSymbolFile); + } - return result; - } + private async Task ExtractPortablePdbOrNullAsync( + PackageArchiveReader symbolPackage, + string pdbPath, + CancellationToken cancellationToken) + { + Stream pdbStream = null; + PortablePdb result = null; - /// - /// Whether the stream starts with the signature every portable PDB starts with. - /// - internal static bool HasPortablePdbSignature(Stream pdbStream) + try { - if (pdbStream == null) throw new ArgumentNullException(nameof(pdbStream)); - if (!pdbStream.CanSeek) throw new ArgumentException("The stream must be seekable", nameof(pdbStream)); - - var position = pdbStream.Position; - - try + using (var rawPdbStream = await symbolPackage.GetStreamAsync(pdbPath, cancellationToken)) { - pdbStream.Position = 0; + pdbStream = await rawPdbStream.AsTemporaryFileStreamAsync(cancellationToken); - var signature = new byte[PortablePdbSignature.Length]; - var read = pdbStream.ReadAtLeast(signature, signature.Length, throwOnEndOfStream: false); - - // A file shorter than the signature - including an empty one - is not a PDB. - return read == signature.Length && signature.SequenceEqual(PortablePdbSignature); - } - finally - { - pdbStream.Position = position; - } - } - - private Guid? ReadPortablePdbSignatureOrNull(Stream pdbStream, string pdbPath) - { - pdbStream.Position = 0; + // A symbol package may only carry portable PDBs. A Windows PDB cannot be read + // as metadata and cannot be keyed for the symbol server, so reject it here + // with a reason rather than letting the metadata reader throw. + if (!HasPortablePdbSignature(pdbStream)) + { + _logger.LogError( + "Rejecting symbol package: the entry {PdbPath} is not a portable PDB", + pdbPath); + return null; + } - try - { - using (var pdbReaderProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream, MetadataStreamOptions.LeaveOpen)) + var signature = ReadPortablePdbSignatureOrNull(pdbStream, pdbPath); + if (signature == null) { - var reader = pdbReaderProvider.GetMetadataReader(); + return null; + } - // Metadata that starts with the right signature but carries no debug metadata - // header is not a PDB, it is an assembly's metadata. - var header = reader.DebugMetadataHeader; - if (header == null || header.Id.Length != DebugMetadataIdLength) - { - _logger.LogError( - "Rejecting symbol package: the entry {PdbPath} does not contain portable PDB debug metadata", - pdbPath); - return null; - } + var fileName = Path.GetFileName(pdbPath).ToLowerInvariant(); + var key = $"{signature.Value.ToString("N").ToUpperInvariant()}ffffffff"; - return new BlobContentId(header.Id).Guid; - } - } - catch (BadImageFormatException e) - { - _logger.LogError(e, "Rejecting symbol package: the entry {PdbPath} is a malformed portable PDB", pdbPath); - return null; + pdbStream.Position = 0; + result = new PortablePdb(pdbPath, fileName, key, signature.Value, pdbStream); } } - - /// - /// Whether every PDB describes a file shipped by the package it claims to belong to. - /// See: https://github.com/NuGet/NuGet.Jobs/blob/master/src/Validation.Symbols/SymbolsValidatorService.cs#L170 - /// - private async Task PdbsDescribePackageAsync( - string packageId, - NuGetVersion packageVersion, - IReadOnlyList pdbs, - CancellationToken cancellationToken) + finally { - if (pdbs.Count == 0) + if (result == null) { - return true; + pdbStream?.Dispose(); } + } - using (var packageStream = await _packageStorage.GetPackageStreamAsync(packageId, packageVersion, cancellationToken)) - using (var package = new PackageArchiveReader(packageStream, leaveStreamOpen: true)) - { - var packageFiles = (await package.GetFilesAsync(cancellationToken)).ToList(); + return result; + } - foreach (var pdb in pdbs) - { - var assemblyPath = FindAssemblyPathOrNull(packageFiles, pdb.Path); - if (assemblyPath == null) - { - _logger.LogError( - "Rejecting symbol package {PackageId} {PackageVersion}: its PDB {PdbPath} has no corresponding assembly in the package", - packageId, - packageVersion.ToNormalizedString(), - pdb.Path); - return false; - } + /// + /// Whether the stream starts with the signature every portable PDB starts with. + /// + internal static bool HasPortablePdbSignature(Stream pdbStream) + { + if (pdbStream == null) throw new ArgumentNullException(nameof(pdbStream)); + if (!pdbStream.CanSeek) throw new ArgumentException("The stream must be seekable", nameof(pdbStream)); - if (!await AssemblyMatchesPdbAsync(package, assemblyPath, pdb, cancellationToken)) - { - return false; - } - } - } + var position = pdbStream.Position; - return true; + try + { + pdbStream.Position = 0; + + var signature = new byte[PortablePdbSignature.Length]; + var read = pdbStream.ReadAtLeast(signature, signature.Length, throwOnEndOfStream: false); + + // A file shorter than the signature - including an empty one - is not a PDB. + return read == signature.Length && signature.SequenceEqual(PortablePdbSignature); + } + finally + { + pdbStream.Position = position; } + } + + private Guid? ReadPortablePdbSignatureOrNull(Stream pdbStream, string pdbPath) + { + pdbStream.Position = 0; - /// - /// A symbol package mirrors the layout of the package it belongs to, so the assembly a - /// PDB describes sits at the same path with an assembly extension. - /// - private static string FindAssemblyPathOrNull(IReadOnlyList packageFiles, string pdbPath) + try { - foreach (var extension in AssemblyExtensions) + using (var pdbReaderProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream, MetadataStreamOptions.LeaveOpen)) { - var candidate = NormalizePath(Path.ChangeExtension(pdbPath, extension)); + var reader = pdbReaderProvider.GetMetadataReader(); - foreach (var packageFile in packageFiles) + // Metadata that starts with the right signature but carries no debug metadata + // header is not a PDB, it is an assembly's metadata. + var header = reader.DebugMetadataHeader; + if (header == null || header.Id.Length != DebugMetadataIdLength) { - if (string.Equals(NormalizePath(packageFile), candidate, StringComparison.OrdinalIgnoreCase)) - { - return packageFile; - } + _logger.LogError( + "Rejecting symbol package: the entry {PdbPath} does not contain portable PDB debug metadata", + pdbPath); + return null; } - } + return new BlobContentId(header.Id).Guid; + } + } + catch (BadImageFormatException e) + { + _logger.LogError(e, "Rejecting symbol package: the entry {PdbPath} is a malformed portable PDB", pdbPath); return null; } + } - private static string NormalizePath(string path) + /// + /// Whether every PDB describes a file shipped by the package it claims to belong to. + /// See: https://github.com/NuGet/NuGet.Jobs/blob/master/src/Validation.Symbols/SymbolsValidatorService.cs#L170 + /// + private async Task PdbsDescribePackageAsync( + string packageId, + NuGetVersion packageVersion, + IReadOnlyList pdbs, + CancellationToken cancellationToken) + { + if (pdbs.Count == 0) { - return path.Replace('\\', '/').TrimStart('/'); + return true; } - private async Task AssemblyMatchesPdbAsync( - PackageArchiveReader package, - string assemblyPath, - PortablePdb pdb, - CancellationToken cancellationToken) + using (var packageStream = await _packageStorage.GetPackageStreamAsync(packageId, packageVersion, cancellationToken)) + using (var package = new PackageArchiveReader(packageStream, leaveStreamOpen: true)) { - using (var rawAssemblyStream = await package.GetStreamAsync(assemblyPath, cancellationToken)) - using (var assemblyStream = await rawAssemblyStream.AsTemporaryFileStreamAsync(cancellationToken)) - { - IReadOnlyList signatures; + var packageFiles = (await package.GetFilesAsync(cancellationToken)).ToList(); - try - { - signatures = ReadCodeViewSignatures(assemblyStream); - } - catch (BadImageFormatException e) + foreach (var pdb in pdbs) + { + var assemblyPath = FindAssemblyPathOrNull(packageFiles, pdb.Path); + if (assemblyPath == null) { _logger.LogError( - e, - "Rejecting symbol package: the package's {AssemblyPath} is not a readable assembly, so its PDB {PdbPath} cannot be matched to it", - assemblyPath, + "Rejecting symbol package {PackageId} {PackageVersion}: its PDB {PdbPath} has no corresponding assembly in the package", + packageId, + packageVersion.ToNormalizedString(), pdb.Path); return false; } - if (signatures.Count == 0) - { - // The assembly ships without a debug directory, so there is nothing to match - // the PDB against. Index it rather than reject what cannot be checked. - _logger.LogWarning( - "The package's {AssemblyPath} has no debug directory, so its PDB {PdbPath} cannot be matched to it", - assemblyPath, - pdb.Path); - return true; - } - - if (!signatures.Contains(pdb.Signature)) + if (!await AssemblyMatchesPdbAsync(package, assemblyPath, pdb, cancellationToken)) { - _logger.LogError( - "Rejecting symbol package: its PDB {PdbPath} does not describe the package's {AssemblyPath}", - pdb.Path, - assemblyPath); return false; } - - return true; } } - /// - /// The debug signatures an assembly's CodeView debug directory entries point at. A - /// portable PDB describes the assembly when it carries one of them. - /// - private static IReadOnlyList ReadCodeViewSignatures(Stream assemblyStream) + return true; + } + + /// + /// A symbol package mirrors the layout of the package it belongs to, so the assembly a + /// PDB describes sits at the same path with an assembly extension. + /// + private static string FindAssemblyPathOrNull(IReadOnlyList packageFiles, string pdbPath) + { + foreach (var extension in AssemblyExtensions) { - assemblyStream.Position = 0; + var candidate = NormalizePath(Path.ChangeExtension(pdbPath, extension)); - using (var peReader = new PEReader(assemblyStream, PEStreamOptions.LeaveOpen)) + foreach (var packageFile in packageFiles) { - return peReader - .ReadDebugDirectory() - .Where(entry => entry.Type == DebugDirectoryEntryType.CodeView) - .Select(entry => peReader.ReadCodeViewDebugDirectoryData(entry).Guid) - .ToList(); + if (string.Equals(NormalizePath(packageFile), candidate, StringComparison.OrdinalIgnoreCase)) + { + return packageFile; + } } } - private class PortablePdb : IDisposable + return null; + } + + private static string NormalizePath(string path) + { + return path.Replace('\\', '/').TrimStart('/'); + } + + private async Task AssemblyMatchesPdbAsync( + PackageArchiveReader package, + string assemblyPath, + PortablePdb pdb, + CancellationToken cancellationToken) + { + using (var rawAssemblyStream = await package.GetStreamAsync(assemblyPath, cancellationToken)) + using (var assemblyStream = await rawAssemblyStream.AsTemporaryFileStreamAsync(cancellationToken)) { - public PortablePdb(string path, string filename, string key, Guid signature, Stream content) + IReadOnlyList signatures; + + try { - Path = path; - Filename = filename; - Key = key; - Signature = signature; - Content = content; + signatures = ReadCodeViewSignatures(assemblyStream); + } + catch (BadImageFormatException e) + { + _logger.LogError( + e, + "Rejecting symbol package: the package's {AssemblyPath} is not a readable assembly, so its PDB {PdbPath} cannot be matched to it", + assemblyPath, + pdb.Path); + return false; } - /// The PDB's path within the symbol package. - public string Path { get; } - public string Filename { get; } - public string Key { get; } + if (signatures.Count == 0) + { + // The assembly ships without a debug directory, so there is nothing to match + // the PDB against. Index it rather than reject what cannot be checked. + _logger.LogWarning( + "The package's {AssemblyPath} has no debug directory, so its PDB {PdbPath} cannot be matched to it", + assemblyPath, + pdb.Path); + return true; + } - /// The PDB's debug signature GUID. - public Guid Signature { get; } - public Stream Content { get; } + if (!signatures.Contains(pdb.Signature)) + { + _logger.LogError( + "Rejecting symbol package: its PDB {PdbPath} does not describe the package's {AssemblyPath}", + pdb.Path, + assemblyPath); + return false; + } - public void Dispose() => Content.Dispose(); + return true; } + } - private class PdbList : List, IDisposable + /// + /// The debug signatures an assembly's CodeView debug directory entries point at. A + /// portable PDB describes the assembly when it carries one of them. + /// + private static IReadOnlyList ReadCodeViewSignatures(Stream assemblyStream) + { + assemblyStream.Position = 0; + + using (var peReader = new PEReader(assemblyStream, PEStreamOptions.LeaveOpen)) { - public void Dispose() + return peReader + .ReadDebugDirectory() + .Where(entry => entry.Type == DebugDirectoryEntryType.CodeView) + .Select(entry => peReader.ReadCodeViewDebugDirectoryData(entry).Guid) + .ToList(); + } + } + + private class PortablePdb : IDisposable + { + public PortablePdb(string path, string filename, string key, Guid signature, Stream content) + { + Path = path; + Filename = filename; + Key = key; + Signature = signature; + Content = content; + } + + /// The PDB's path within the symbol package. + public string Path { get; } + public string Filename { get; } + public string Key { get; } + + /// The PDB's debug signature GUID. + public Guid Signature { get; } + public Stream Content { get; } + + public void Dispose() => Content.Dispose(); + } + + private class PdbList : List, IDisposable + { + public void Dispose() + { + foreach (var pdb in this) { - foreach (var pdb in this) - { - pdb.Dispose(); - } + pdb.Dispose(); } } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/BaGetPackageMetadata.cs b/src/BaGet.Core/Metadata/BaGetPackageMetadata.cs index f84747d41..3b82a9fbf 100644 --- a/src/BaGet.Core/Metadata/BaGetPackageMetadata.cs +++ b/src/BaGet.Core/Metadata/BaGetPackageMetadata.cs @@ -2,33 +2,32 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// BaGet's extensions to the package metadata model. These additions +/// are not part of the official protocol. +/// +public class BaGetPackageMetadata : PackageMetadata { - /// - /// BaGet's extensions to the package metadata model. These additions - /// are not part of the official protocol. - /// - public class BaGetPackageMetadata : PackageMetadata - { - [JsonPropertyName("downloads")] - public long Downloads { get; set; } + [JsonPropertyName("downloads")] + public long Downloads { get; set; } - [JsonPropertyName("hasReadme")] - public bool HasReadme { get; set; } + [JsonPropertyName("hasReadme")] + public bool HasReadme { get; set; } - [JsonPropertyName("packageTypes")] - public IReadOnlyList PackageTypes { get; set; } + [JsonPropertyName("packageTypes")] + public IReadOnlyList PackageTypes { get; set; } - /// - /// The package's release notes. - /// - [JsonPropertyName("releaseNotes")] - public string ReleaseNotes { get; set; } + /// + /// The package's release notes. + /// + [JsonPropertyName("releaseNotes")] + public string ReleaseNotes { get; set; } - [JsonPropertyName("repositoryUrl")] - public string RepositoryUrl { get; set; } + [JsonPropertyName("repositoryUrl")] + public string RepositoryUrl { get; set; } - [JsonPropertyName("repositoryType")] - public string RepositoryType { get; set; } - } -} + [JsonPropertyName("repositoryType")] + public string RepositoryType { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/BaGetRegistrationIndexPage.cs b/src/BaGet.Core/Metadata/BaGetRegistrationIndexPage.cs index 8076a1abc..1cee07257 100644 --- a/src/BaGet.Core/Metadata/BaGetRegistrationIndexPage.cs +++ b/src/BaGet.Core/Metadata/BaGetRegistrationIndexPage.cs @@ -2,21 +2,20 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// BaGet's extensions to a registration index page. Extends +/// , shadowing the single property whose type +/// differs. +/// +public class BaGetRegistrationIndexPage : RegistrationIndexPage { /// - /// BaGet's extensions to a registration index page. Extends - /// , shadowing the single property whose type - /// differs. + /// This was modified to use BaGet's extended registration index page item model. /// - public class BaGetRegistrationIndexPage : RegistrationIndexPage - { - /// - /// This was modified to use BaGet's extended registration index page item model. - /// - // Ordered so the serialized property order is unchanged by inheriting the base type. - [JsonPropertyName("items")] - [JsonPropertyOrder(1)] - public new IReadOnlyList ItemsOrNull { get; set; } - } -} + // Ordered so the serialized property order is unchanged by inheriting the base type. + [JsonPropertyName("items")] + [JsonPropertyOrder(1)] + public new IReadOnlyList ItemsOrNull { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/BaGetRegistrationIndexPageItem.cs b/src/BaGet.Core/Metadata/BaGetRegistrationIndexPageItem.cs index aaf068a73..59bbe6ef4 100644 --- a/src/BaGet.Core/Metadata/BaGetRegistrationIndexPageItem.cs +++ b/src/BaGet.Core/Metadata/BaGetRegistrationIndexPageItem.cs @@ -1,21 +1,20 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// BaGet's extensions to a registration index page item. Extends +/// , shadowing the single property whose type +/// differs. +/// +public class BaGetRegistrationIndexPageItem : RegistrationIndexPageItem { /// - /// BaGet's extensions to a registration index page item. Extends - /// , shadowing the single property whose type - /// differs. + /// This was modified to use BaGet's extended package metadata model. /// - public class BaGetRegistrationIndexPageItem : RegistrationIndexPageItem - { - /// - /// This was modified to use BaGet's extended package metadata model. - /// - // Ordered so the serialized property order is unchanged by inheriting the base type. - [JsonPropertyName("catalogEntry")] - [JsonPropertyOrder(1)] - public new BaGetPackageMetadata PackageMetadata { get; set; } - } -} + // Ordered so the serialized property order is unchanged by inheriting the base type. + [JsonPropertyName("catalogEntry")] + [JsonPropertyOrder(1)] + public new BaGetPackageMetadata PackageMetadata { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/BaGetRegistrationIndexResponse.cs b/src/BaGet.Core/Metadata/BaGetRegistrationIndexResponse.cs index 4a3e8ece1..7de940e86 100644 --- a/src/BaGet.Core/Metadata/BaGetRegistrationIndexResponse.cs +++ b/src/BaGet.Core/Metadata/BaGetRegistrationIndexResponse.cs @@ -2,31 +2,30 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// BaGet's extensions to a registration index response. Extends +/// , shadowing the property whose type differs +/// and adding BaGet's own total download count. +/// +public class BaGetRegistrationIndexResponse : RegistrationIndexResponse { /// - /// BaGet's extensions to a registration index response. Extends - /// , shadowing the property whose type differs - /// and adding BaGet's own total download count. + /// The pages that contain all of the versions of the package, ordered + /// by the package's version. This was modified to use BaGet's extended + /// registration index page model. /// - public class BaGetRegistrationIndexResponse : RegistrationIndexResponse - { - /// - /// The pages that contain all of the versions of the package, ordered - /// by the package's version. This was modified to use BaGet's extended - /// registration index page model. - /// - // Ordered so the serialized property order is unchanged by inheriting the base type. - [JsonPropertyName("items")] - [JsonPropertyOrder(1)] - public new IReadOnlyList Pages { get; set; } + // Ordered so the serialized property order is unchanged by inheriting the base type. + [JsonPropertyName("items")] + [JsonPropertyOrder(1)] + public new IReadOnlyList Pages { get; set; } - /// - /// The package's total downloads across all versions. - /// This is not part of the official NuGet protocol. - /// - [JsonPropertyName("totalDownloads")] - [JsonPropertyOrder(2)] - public long TotalDownloads { get; set; } - } -} + /// + /// The package's total downloads across all versions. + /// This is not part of the official NuGet protocol. + /// + [JsonPropertyName("totalDownloads")] + [JsonPropertyOrder(2)] + public long TotalDownloads { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/DefaultPackageMetadataService.cs b/src/BaGet.Core/Metadata/DefaultPackageMetadataService.cs index 130e1e59b..b5d857b43 100644 --- a/src/BaGet.Core/Metadata/DefaultPackageMetadataService.cs +++ b/src/BaGet.Core/Metadata/DefaultPackageMetadataService.cs @@ -5,50 +5,49 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +public class DefaultPackageMetadataService : IPackageMetadataService { - /// - public class DefaultPackageMetadataService : IPackageMetadataService + private readonly IPackageService _packages; + private readonly RegistrationBuilder _builder; + + public DefaultPackageMetadataService( + IPackageService packages, + RegistrationBuilder builder) { - private readonly IPackageService _packages; - private readonly RegistrationBuilder _builder; + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _builder = builder ?? throw new ArgumentNullException(nameof(builder)); + } - public DefaultPackageMetadataService( - IPackageService packages, - RegistrationBuilder builder) + public async Task GetRegistrationIndexOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var packages = await _packages.FindPackagesAsync(packageId, cancellationToken); + if (!packages.Any()) { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _builder = builder ?? throw new ArgumentNullException(nameof(builder)); + return null; } - public async Task GetRegistrationIndexOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var packages = await _packages.FindPackagesAsync(packageId, cancellationToken); - if (!packages.Any()) - { - return null; - } - - return _builder.BuildIndex( - new PackageRegistration( - packageId, - packages)); - } + return _builder.BuildIndex( + new PackageRegistration( + packageId, + packages)); + } - public async Task GetRegistrationLeafOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken = default) + public async Task GetRegistrationLeafOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken = default) + { + var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); + if (package == null) { - var package = await _packages.FindPackageOrNullAsync(id, version, cancellationToken); - if (package == null) - { - return null; - } - - return _builder.BuildLeaf(package); + return null; } + + return _builder.BuildLeaf(package); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/IPackageMetadataService.cs b/src/BaGet.Core/Metadata/IPackageMetadataService.cs index 83bf3fab0..488715f03 100644 --- a/src/BaGet.Core/Metadata/IPackageMetadataService.cs +++ b/src/BaGet.Core/Metadata/IPackageMetadataService.cs @@ -3,34 +3,33 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The Package Metadata client, used to fetch packages' metadata. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource +/// +public interface IPackageMetadataService { /// - /// The Package Metadata client, used to fetch packages' metadata. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource + /// Attempt to get a package's registration index, if it exists. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page /// - public interface IPackageMetadataService - { - /// - /// Attempt to get a package's registration index, if it exists. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - /// The package's ID. - /// A token to cancel the task. - /// The package's registration index, or null if the package does not exist - Task GetRegistrationIndexOrNullAsync(string packageId, CancellationToken cancellationToken = default); + /// The package's ID. + /// A token to cancel the task. + /// The package's registration index, or null if the package does not exist + Task GetRegistrationIndexOrNullAsync(string packageId, CancellationToken cancellationToken = default); - /// - /// Get the metadata for a single package version, if the package exists. - /// - /// The package's id. - /// The package's version. - /// A token to cancel the task. - /// The registration leaf, or null if the package does not exist. - Task GetRegistrationLeafOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default); - } -} + /// + /// Get the metadata for a single package version, if the package exists. + /// + /// The package's id. + /// The package's version. + /// A token to cancel the task. + /// The registration leaf, or null if the package does not exist. + Task GetRegistrationLeafOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/PackageRegistration.cs b/src/BaGet.Core/Metadata/PackageRegistration.cs index 6e583574a..ee8505c98 100644 --- a/src/BaGet.Core/Metadata/PackageRegistration.cs +++ b/src/BaGet.Core/Metadata/PackageRegistration.cs @@ -1,34 +1,33 @@ using System; using System.Collections.Generic; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The information on all versions of a package. +/// +public class PackageRegistration { /// - /// The information on all versions of a package. + /// Create a new registration object. /// - public class PackageRegistration + /// + /// All versions of the package. + public PackageRegistration( + string packageId, + IReadOnlyList packages) { - /// - /// Create a new registration object. - /// - /// - /// All versions of the package. - public PackageRegistration( - string packageId, - IReadOnlyList packages) - { - PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); - Packages = packages ?? throw new ArgumentNullException(nameof(packages)); - } + PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); + Packages = packages ?? throw new ArgumentNullException(nameof(packages)); + } - /// - /// The package's ID. - /// - public string PackageId { get; } + /// + /// The package's ID. + /// + public string PackageId { get; } - /// - /// The information for each version of the package. - /// - public IReadOnlyList Packages { get; } - } -} + /// + /// The information for each version of the package. + /// + public IReadOnlyList Packages { get; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Metadata/RegistrationBuilder.cs b/src/BaGet.Core/Metadata/RegistrationBuilder.cs index 82a128d0c..189640a2f 100644 --- a/src/BaGet.Core/Metadata/RegistrationBuilder.cs +++ b/src/BaGet.Core/Metadata/RegistrationBuilder.cs @@ -4,164 +4,163 @@ using System.Linq; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +public class RegistrationBuilder { - public class RegistrationBuilder + private readonly IUrlGenerator _url; + + public RegistrationBuilder(IUrlGenerator url) { - private readonly IUrlGenerator _url; + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - public RegistrationBuilder(IUrlGenerator url) - { - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public virtual BaGetRegistrationIndexResponse BuildIndex(PackageRegistration registration) + { + var sortedPackages = registration.Packages.OrderBy(p => p.Version).ToList(); - public virtual BaGetRegistrationIndexResponse BuildIndex(PackageRegistration registration) + // TODO: Paging of registration items. + // "Un-paged" example: https://api.nuget.org/v3/registration3/newtonsoft.json/index.json + // Paged example: https://api.nuget.org/v3/registration3/fake/index.json + return new BaGetRegistrationIndexResponse { - var sortedPackages = registration.Packages.OrderBy(p => p.Version).ToList(); - - // TODO: Paging of registration items. - // "Un-paged" example: https://api.nuget.org/v3/registration3/newtonsoft.json/index.json - // Paged example: https://api.nuget.org/v3/registration3/fake/index.json - return new BaGetRegistrationIndexResponse + RegistrationIndexUrl = _url.GetRegistrationIndexUrl(registration.PackageId), + Type = RegistrationIndexResponse.DefaultType, + Count = 1, + TotalDownloads = registration.Packages.Sum(p => p.Downloads), + Pages = new[] { - RegistrationIndexUrl = _url.GetRegistrationIndexUrl(registration.PackageId), - Type = RegistrationIndexResponse.DefaultType, - Count = 1, - TotalDownloads = registration.Packages.Sum(p => p.Downloads), - Pages = new[] + new BaGetRegistrationIndexPage { - new BaGetRegistrationIndexPage - { - RegistrationPageUrl = _url.GetRegistrationIndexUrl(registration.PackageId), - Count = registration.Packages.Count(), - Lower = sortedPackages.First().Version.ToNormalizedString().ToLowerInvariant(), - Upper = sortedPackages.Last().Version.ToNormalizedString().ToLowerInvariant(), - ItemsOrNull = sortedPackages.Select(ToRegistrationIndexPageItem).ToList(), - } + RegistrationPageUrl = _url.GetRegistrationIndexUrl(registration.PackageId), + Count = registration.Packages.Count(), + Lower = sortedPackages.First().Version.ToNormalizedString().ToLowerInvariant(), + Upper = sortedPackages.Last().Version.ToNormalizedString().ToLowerInvariant(), + ItemsOrNull = sortedPackages.Select(ToRegistrationIndexPageItem).ToList(), } - }; - } + } + }; + } - public virtual RegistrationLeafResponse BuildLeaf(Package package) + public virtual RegistrationLeafResponse BuildLeaf(Package package) + { + var id = package.Id; + var version = package.Version; + + return new RegistrationLeafResponse { - var id = package.Id; - var version = package.Version; + Type = RegistrationLeafResponse.DefaultType, + Listed = package.Listed, + Published = package.Published, + RegistrationLeafUrl = _url.GetRegistrationLeafUrl(id, version), + PackageContentUrl = _url.GetPackageDownloadUrl(id, version), + RegistrationIndexUrl = _url.GetRegistrationIndexUrl(id) + }; + } - return new RegistrationLeafResponse + private BaGetRegistrationIndexPageItem ToRegistrationIndexPageItem(Package package) => + new BaGetRegistrationIndexPageItem + { + RegistrationLeafUrl = _url.GetRegistrationLeafUrl(package.Id, package.Version), + PackageContentUrl = _url.GetPackageDownloadUrl(package.Id, package.Version), + PackageMetadata = new BaGetPackageMetadata { - Type = RegistrationLeafResponse.DefaultType, + PackageId = package.Id, + Version = package.Version.ToFullString(), + Authors = string.Join(", ", package.Authors), + Description = package.Description, + Downloads = package.Downloads, + HasReadme = package.HasReadme, + IconUrl = package.HasEmbeddedIcon + ? _url.GetPackageIconDownloadUrl(package.Id, package.Version) + : package.IconUrlString, + Language = package.Language, + LicenseUrl = package.LicenseUrlString, Listed = package.Listed, - Published = package.Published, - RegistrationLeafUrl = _url.GetRegistrationLeafUrl(id, version), - PackageContentUrl = _url.GetPackageDownloadUrl(id, version), - RegistrationIndexUrl = _url.GetRegistrationIndexUrl(id) - }; + MinClientVersion = package.MinClientVersion, + ReleaseNotes = package.ReleaseNotes, + PackageContentUrl = _url.GetPackageDownloadUrl(package.Id, package.Version), + PackageTypes = package.PackageTypes.Select(t => t.Name).ToList(), + ProjectUrl = package.ProjectUrlString, + RepositoryUrl = package.RepositoryUrlString, + RepositoryType = package.RepositoryType, + Published = package.Published==DateTime.MinValue?DateTimeOffset.Now : package.Published, + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + Summary = package.Summary, + Tags = package.Tags, + Title = package.Title, + DependencyGroups = ToDependencyGroups(package), + Deprecation = ToDeprecation(package.Deprecation), + Vulnerabilities = ToVulnerabilities(package.Vulnerabilities), + }, + }; + + // Inside BaGet.Core the entity BaGet.Core.PackageDeprecation is found before the + // protocol model of the same name, so the protocol model is named in full. + internal static Protocol.Models.PackageDeprecation ToDeprecation(PackageDeprecation deprecation) + { + if (deprecation == null) + { + return null; } - private BaGetRegistrationIndexPageItem ToRegistrationIndexPageItem(Package package) => - new BaGetRegistrationIndexPageItem - { - RegistrationLeafUrl = _url.GetRegistrationLeafUrl(package.Id, package.Version), - PackageContentUrl = _url.GetPackageDownloadUrl(package.Id, package.Version), - PackageMetadata = new BaGetPackageMetadata + return new Protocol.Models.PackageDeprecation + { + Reasons = deprecation.Reasons ?? Array.Empty(), + Message = deprecation.Message, + AlternatePackage = string.IsNullOrEmpty(deprecation.AlternatePackageId) + ? null + : new AlternatePackage { - PackageId = package.Id, - Version = package.Version.ToFullString(), - Authors = string.Join(", ", package.Authors), - Description = package.Description, - Downloads = package.Downloads, - HasReadme = package.HasReadme, - IconUrl = package.HasEmbeddedIcon - ? _url.GetPackageIconDownloadUrl(package.Id, package.Version) - : package.IconUrlString, - Language = package.Language, - LicenseUrl = package.LicenseUrlString, - Listed = package.Listed, - MinClientVersion = package.MinClientVersion, - ReleaseNotes = package.ReleaseNotes, - PackageContentUrl = _url.GetPackageDownloadUrl(package.Id, package.Version), - PackageTypes = package.PackageTypes.Select(t => t.Name).ToList(), - ProjectUrl = package.ProjectUrlString, - RepositoryUrl = package.RepositoryUrlString, - RepositoryType = package.RepositoryType, - Published = package.Published==DateTime.MinValue?DateTimeOffset.Now : package.Published, - RequireLicenseAcceptance = package.RequireLicenseAcceptance, - Summary = package.Summary, - Tags = package.Tags, - Title = package.Title, - DependencyGroups = ToDependencyGroups(package), - Deprecation = ToDeprecation(package.Deprecation), - Vulnerabilities = ToVulnerabilities(package.Vulnerabilities), + Id = deprecation.AlternatePackageId, + + // The protocol writes "*" for "any version". + Range = string.IsNullOrEmpty(deprecation.AlternateVersionRange) + ? "*" + : deprecation.AlternateVersionRange, }, - }; + }; + } - // Inside BaGet.Core the entity BaGet.Core.PackageDeprecation is found before the - // protocol model of the same name, so the protocol model is named in full. - internal static Protocol.Models.PackageDeprecation ToDeprecation(PackageDeprecation deprecation) + internal static IReadOnlyList ToVulnerabilities( + IReadOnlyCollection vulnerabilities) + { + // Null rather than empty, so a version with no known vulnerabilities serialises + // exactly as it did before vulnerabilities existed. + if (vulnerabilities == null || vulnerabilities.Count == 0) { - if (deprecation == null) - { - return null; - } - - return new Protocol.Models.PackageDeprecation - { - Reasons = deprecation.Reasons ?? Array.Empty(), - Message = deprecation.Message, - AlternatePackage = string.IsNullOrEmpty(deprecation.AlternatePackageId) - ? null - : new AlternatePackage - { - Id = deprecation.AlternatePackageId, - - // The protocol writes "*" for "any version". - Range = string.IsNullOrEmpty(deprecation.AlternateVersionRange) - ? "*" - : deprecation.AlternateVersionRange, - }, - }; + return null; } - internal static IReadOnlyList ToVulnerabilities( - IReadOnlyCollection vulnerabilities) - { - // Null rather than empty, so a version with no known vulnerabilities serialises - // exactly as it did before vulnerabilities existed. - if (vulnerabilities == null || vulnerabilities.Count == 0) + return vulnerabilities + .Select(v => new PackageVulnerabilityMetadata { - return null; - } - - return vulnerabilities - .Select(v => new PackageVulnerabilityMetadata - { - AdvisoryUrl = v.AdvisoryUrl, - Severity = v.Severity.ToString(CultureInfo.InvariantCulture), - }) - .ToList(); - } + AdvisoryUrl = v.AdvisoryUrl, + Severity = v.Severity.ToString(CultureInfo.InvariantCulture), + }) + .ToList(); + } - internal static IReadOnlyList ToDependencyGroups(Package package) - { - return package.Dependencies - .GroupBy(d => d.TargetFramework) - .Select(group => new DependencyGroupItem - { - TargetFramework = group.Key, + internal static IReadOnlyList ToDependencyGroups(Package package) + { + return package.Dependencies + .GroupBy(d => d.TargetFramework) + .Select(group => new DependencyGroupItem + { + TargetFramework = group.Key, - // A package that supports a target framework but does not have dependencies while on - // that target framework is represented by a fake dependency with a null "Id" and "VersionRange". - // This fake dependency should not be included in the output. - Dependencies = group - .Where(d => d.Id != null && d.VersionRange != null) - .Select(d => new DependencyItem - { - Id = d.Id, - Range = d.VersionRange - }) - .ToList() - }) - .ToList(); - } + // A package that supports a target framework but does not have dependencies while on + // that target framework is represented by a fake dependency with a null "Id" and "VersionRange". + // This fake dependency should not be included in the output. + Dependencies = group + .Where(d => d.Id != null && d.VersionRange != null) + .Select(d => new DependencyItem + { + Id = d.Id, + Range = d.VersionRange + }) + .ToList() + }) + .ToList(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/PackageDatabase.cs b/src/BaGet.Core/PackageDatabase.cs index 8b5140897..2bc01e493 100644 --- a/src/BaGet.Core/PackageDatabase.cs +++ b/src/BaGet.Core/PackageDatabase.cs @@ -6,254 +6,253 @@ using Microsoft.EntityFrameworkCore; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageDatabase : IPackageDatabase { - public class PackageDatabase : IPackageDatabase + private readonly IContext _context; + + public PackageDatabase(IContext context) { - private readonly IContext _context; + _context = context ?? throw new ArgumentNullException(nameof(context)); + } - public PackageDatabase(IContext context) + public async Task AddAsync(Package package, CancellationToken cancellationToken) + { + try { - _context = context ?? throw new ArgumentNullException(nameof(context)); - } + _context.Packages.Add(package); - public async Task AddAsync(Package package, CancellationToken cancellationToken) - { - try - { - _context.Packages.Add(package); - - await _context.SaveChangesAsync(cancellationToken); - - return PackageAddResult.Success; - } - catch (DbUpdateException e) - when (_context.IsUniqueConstraintViolationException(e)) - { - return PackageAddResult.PackageAlreadyExists; - } - } + await _context.SaveChangesAsync(cancellationToken); - public async Task ExistsAsync(string id, CancellationToken cancellationToken) - { - return await _context - .Packages - .Where(p => p.Id == id) - .AnyAsync(cancellationToken); + return PackageAddResult.Success; } - - public async Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + catch (DbUpdateException e) + when (_context.IsUniqueConstraintViolationException(e)) { - return await _context - .Packages - .Where(p => p.Id == id) - .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) - .AnyAsync(cancellationToken); + return PackageAddResult.PackageAlreadyExists; } + } - public async Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken) - { - var query = _context.Packages - .Include(p => p.Dependencies) - .Include(p => p.PackageTypes) - .Include(p => p.TargetFrameworks) - .Include(p => p.Deprecation) - .Include(p => p.Vulnerabilities) - .AsSplitQuery() - .Where(p => p.Id == id); - - if (!includeUnlisted) - { - query = query.Where(p => p.Listed); - } - - return (await query.ToListAsync(cancellationToken)).AsReadOnly(); - } + public async Task ExistsAsync(string id, CancellationToken cancellationToken) + { + return await _context + .Packages + .Where(p => p.Id == id) + .AnyAsync(cancellationToken); + } - public Task FindOrNullAsync( - string id, - NuGetVersion version, - bool includeUnlisted, - CancellationToken cancellationToken) - { - var query = _context.Packages - .Include(p => p.Dependencies) - .Include(p => p.TargetFrameworks) - .Include(p => p.Deprecation) - .Include(p => p.Vulnerabilities) - .AsSplitQuery() - .Where(p => p.Id == id) - .Where(p => p.NormalizedVersionString == version.ToNormalizedString()); - - if (!includeUnlisted) - { - query = query.Where(p => p.Listed); - } - - return query.FirstOrDefaultAsync(cancellationToken); - } + public async Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await _context + .Packages + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) + .AnyAsync(cancellationToken); + } - public Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + public async Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken) + { + var query = _context.Packages + .Include(p => p.Dependencies) + .Include(p => p.PackageTypes) + .Include(p => p.TargetFrameworks) + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .Where(p => p.Id == id); + + if (!includeUnlisted) { - return TryUpdatePackageAsync(id, version, p => p.Listed = false, cancellationToken); + query = query.Where(p => p.Listed); } - public Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return TryUpdatePackageAsync(id, version, p => p.Listed = true, cancellationToken); - } + return (await query.ToListAsync(cancellationToken)).AsReadOnly(); + } - public async Task AddDownloadAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + public Task FindOrNullAsync( + string id, + NuGetVersion version, + bool includeUnlisted, + CancellationToken cancellationToken) + { + var query = _context.Packages + .Include(p => p.Dependencies) + .Include(p => p.TargetFrameworks) + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()); + + if (!includeUnlisted) { - await TryUpdatePackageAsync(id, version, p => p.Downloads += 1, cancellationToken); + query = query.Where(p => p.Listed); } - public async Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - var package = await _context.Packages - .Where(p => p.Id == id) - .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) - .Include(p => p.Dependencies) - .Include(p => p.TargetFrameworks) - .Include(p => p.Deprecation) - .Include(p => p.Vulnerabilities) - .AsSplitQuery() - .FirstOrDefaultAsync(cancellationToken); - - if (package == null) - { - return false; - } - - // The package to dependency relationship is optional in the database, so EF would - // null the foreign key and leave these rows behind rather than delete them. - _context.PackageDependencies.RemoveRange(package.Dependencies); - - // The same holds for a package's deprecation and vulnerabilities. - if (package.Deprecation != null) - { - _context.PackageDeprecations.Remove(package.Deprecation); - } - - _context.PackageVulnerabilities.RemoveRange(package.Vulnerabilities); - _context.Packages.Remove(package); - await _context.SaveChangesAsync(cancellationToken); + return query.FirstOrDefaultAsync(cancellationToken); + } - return true; - } + public Task UnlistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return TryUpdatePackageAsync(id, version, p => p.Listed = false, cancellationToken); + } - public async Task SetDeprecationAsync( - string id, - NuGetVersion version, - PackageDeprecation deprecation, - CancellationToken cancellationToken) - { - if (deprecation == null) throw new ArgumentNullException(nameof(deprecation)); + public Task RelistPackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return TryUpdatePackageAsync(id, version, p => p.Listed = true, cancellationToken); + } - var package = await FindForUpdateAsync(id, version, cancellationToken); - if (package == null) - { - return false; - } + public async Task AddDownloadAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + await TryUpdatePackageAsync(id, version, p => p.Downloads += 1, cancellationToken); + } - // A version has at most one deprecation, so setting one replaces the last. - if (package.Deprecation != null) - { - _context.PackageDeprecations.Remove(package.Deprecation); - } + public async Task HardDeletePackageAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + var package = await _context.Packages + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) + .Include(p => p.Dependencies) + .Include(p => p.TargetFrameworks) + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .FirstOrDefaultAsync(cancellationToken); + + if (package == null) + { + return false; + } - package.Deprecation = deprecation; - await _context.SaveChangesAsync(cancellationToken); + // The package to dependency relationship is optional in the database, so EF would + // null the foreign key and leave these rows behind rather than delete them. + _context.PackageDependencies.RemoveRange(package.Dependencies); - return true; + // The same holds for a package's deprecation and vulnerabilities. + if (package.Deprecation != null) + { + _context.PackageDeprecations.Remove(package.Deprecation); } - public async Task RemoveDeprecationAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) - { - var package = await FindForUpdateAsync(id, version, cancellationToken); - if (package == null) - { - return false; - } - - if (package.Deprecation != null) - { - _context.PackageDeprecations.Remove(package.Deprecation); - await _context.SaveChangesAsync(cancellationToken); - } + _context.PackageVulnerabilities.RemoveRange(package.Vulnerabilities); + _context.Packages.Remove(package); + await _context.SaveChangesAsync(cancellationToken); - return true; + return true; + } + + public async Task SetDeprecationAsync( + string id, + NuGetVersion version, + PackageDeprecation deprecation, + CancellationToken cancellationToken) + { + if (deprecation == null) throw new ArgumentNullException(nameof(deprecation)); + + var package = await FindForUpdateAsync(id, version, cancellationToken); + if (package == null) + { + return false; } - public async Task SetVulnerabilitiesAsync( - string id, - NuGetVersion version, - IReadOnlyList vulnerabilities, - CancellationToken cancellationToken) + // A version has at most one deprecation, so setting one replaces the last. + if (package.Deprecation != null) { - if (vulnerabilities == null) throw new ArgumentNullException(nameof(vulnerabilities)); + _context.PackageDeprecations.Remove(package.Deprecation); + } - var package = await FindForUpdateAsync(id, version, cancellationToken); - if (package == null) - { - return false; - } + package.Deprecation = deprecation; + await _context.SaveChangesAsync(cancellationToken); - // The list replaces whatever the version had, so an empty list clears it. - _context.PackageVulnerabilities.RemoveRange(package.Vulnerabilities); - package.Vulnerabilities = vulnerabilities.ToList(); - await _context.SaveChangesAsync(cancellationToken); + return true; + } - return true; + public async Task RemoveDeprecationAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + var package = await FindForUpdateAsync(id, version, cancellationToken); + if (package == null) + { + return false; } - public async Task> GetAllVulnerabilitiesAsync( - CancellationToken cancellationToken) + if (package.Deprecation != null) { - return await _context.PackageVulnerabilities - .Include(v => v.Package) - .Where(v => v.Package != null) - .AsNoTracking() - .ToListAsync(cancellationToken); + _context.PackageDeprecations.Remove(package.Deprecation); + await _context.SaveChangesAsync(cancellationToken); } - private Task FindForUpdateAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) + return true; + } + + public async Task SetVulnerabilitiesAsync( + string id, + NuGetVersion version, + IReadOnlyList vulnerabilities, + CancellationToken cancellationToken) + { + if (vulnerabilities == null) throw new ArgumentNullException(nameof(vulnerabilities)); + + var package = await FindForUpdateAsync(id, version, cancellationToken); + if (package == null) { - return _context.Packages - .Include(p => p.Deprecation) - .Include(p => p.Vulnerabilities) - .AsSplitQuery() - .Where(p => p.Id == id) - .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) - .FirstOrDefaultAsync(cancellationToken); + return false; } - private async Task TryUpdatePackageAsync( - string id, - NuGetVersion version, - Action action, - CancellationToken cancellationToken) - { - var package = await _context.Packages - .Where(p => p.Id == id) - .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) - .FirstOrDefaultAsync(); + // The list replaces whatever the version had, so an empty list clears it. + _context.PackageVulnerabilities.RemoveRange(package.Vulnerabilities); + package.Vulnerabilities = vulnerabilities.ToList(); + await _context.SaveChangesAsync(cancellationToken); - if (package != null) - { - action(package); - await _context.SaveChangesAsync(cancellationToken); + return true; + } - return true; - } + public async Task> GetAllVulnerabilitiesAsync( + CancellationToken cancellationToken) + { + return await _context.PackageVulnerabilities + .Include(v => v.Package) + .Where(v => v.Package != null) + .AsNoTracking() + .ToListAsync(cancellationToken); + } - return false; + private Task FindForUpdateAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + return _context.Packages + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .AsSplitQuery() + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) + .FirstOrDefaultAsync(cancellationToken); + } + + private async Task TryUpdatePackageAsync( + string id, + NuGetVersion version, + Action action, + CancellationToken cancellationToken) + { + var package = await _context.Packages + .Where(p => p.Id == id) + .Where(p => p.NormalizedVersionString == version.ToNormalizedString()) + .FirstOrDefaultAsync(); + + if (package != null) + { + action(package); + await _context.SaveChangesAsync(cancellationToken); + + return true; } + + return false; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/PackageService.cs b/src/BaGet.Core/PackageService.cs index 1f1763461..b4e1689ac 100644 --- a/src/BaGet.Core/PackageService.cs +++ b/src/BaGet.Core/PackageService.cs @@ -6,144 +6,143 @@ using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageService : IPackageService { - public class PackageService : IPackageService + private readonly IPackageDatabase _db; + private readonly IUpstreamClient _upstream; + private readonly IPackageIndexingService _indexer; + private readonly ILogger _logger; + + public PackageService( + IPackageDatabase db, + IUpstreamClient upstream, + IPackageIndexingService indexer, + ILogger logger) { - private readonly IPackageDatabase _db; - private readonly IUpstreamClient _upstream; - private readonly IPackageIndexingService _indexer; - private readonly ILogger _logger; - - public PackageService( - IPackageDatabase db, - IUpstreamClient upstream, - IPackageIndexingService indexer, - ILogger logger) - { - _db = db ?? throw new ArgumentNullException(nameof(db)); - _upstream = upstream ?? throw new ArgumentNullException(nameof(upstream)); - _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + _db = db ?? throw new ArgumentNullException(nameof(db)); + _upstream = upstream ?? throw new ArgumentNullException(nameof(upstream)); + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task> FindPackageVersionsAsync( - string id, - CancellationToken cancellationToken) - { - var upstreamVersions = await _upstream.ListPackageVersionsAsync(id, cancellationToken); + public async Task> FindPackageVersionsAsync( + string id, + CancellationToken cancellationToken) + { + var upstreamVersions = await _upstream.ListPackageVersionsAsync(id, cancellationToken); - // Merge the local package versions into the upstream package versions. - var localPackages = await _db.FindAsync(id, includeUnlisted: true, cancellationToken); - var localVersions = localPackages.Select(p => p.Version); + // Merge the local package versions into the upstream package versions. + var localPackages = await _db.FindAsync(id, includeUnlisted: true, cancellationToken); + var localVersions = localPackages.Select(p => p.Version); - if (!upstreamVersions.Any()) return localVersions.ToList(); - if (!localPackages.Any()) return upstreamVersions; + if (!upstreamVersions.Any()) return localVersions.ToList(); + if (!localPackages.Any()) return upstreamVersions; - return upstreamVersions.Concat(localVersions).Distinct().ToList(); - } - - public async Task> FindPackagesAsync(string id, CancellationToken cancellationToken) - { - var upstreamPackages = await _upstream.ListPackagesAsync(id, cancellationToken); - var localPackages = await _db.FindAsync(id, includeUnlisted: true, cancellationToken); + return upstreamVersions.Concat(localVersions).Distinct().ToList(); + } - if (!upstreamPackages.Any()) return localPackages; - if (!localPackages.Any()) return upstreamPackages; + public async Task> FindPackagesAsync(string id, CancellationToken cancellationToken) + { + var upstreamPackages = await _upstream.ListPackagesAsync(id, cancellationToken); + var localPackages = await _db.FindAsync(id, includeUnlisted: true, cancellationToken); - // Merge the local packages into the upstream packages. - var result = upstreamPackages.ToDictionary(p => p.Version); - var local = localPackages.ToDictionary(p => p.Version); + if (!upstreamPackages.Any()) return localPackages; + if (!localPackages.Any()) return upstreamPackages; - foreach (var localPackage in local) - { - result[localPackage.Key] = localPackage.Value; - } + // Merge the local packages into the upstream packages. + var result = upstreamPackages.ToDictionary(p => p.Version); + var local = localPackages.ToDictionary(p => p.Version); - return result.Values.ToList(); - } - - public async Task FindPackageOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) + foreach (var localPackage in local) { - if (!await MirrorAsync(id, version, cancellationToken)) - { - return null; - } - - return await _db.FindOrNullAsync(id, version, includeUnlisted: true, cancellationToken); + result[localPackage.Key] = localPackage.Value; } - public async Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await MirrorAsync(id, version, cancellationToken); - } + return result.Values.ToList(); + } - public async Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken) + public async Task FindPackageOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + if (!await MirrorAsync(id, version, cancellationToken)) { - await _db.AddDownloadAsync(packageId, version, cancellationToken); + return null; } - /// - /// Index the package from an upstream if it does not exist locally. - /// - /// The package ID to index from an upstream. - /// The package version to index from an upstream. - /// - /// True if the package exists locally or was indexed from an upstream source. - private async Task MirrorAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + return await _db.FindOrNullAsync(id, version, includeUnlisted: true, cancellationToken); + } + + public async Task ExistsAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await MirrorAsync(id, version, cancellationToken); + } + + public async Task AddDownloadAsync(string packageId, NuGetVersion version, CancellationToken cancellationToken) + { + await _db.AddDownloadAsync(packageId, version, cancellationToken); + } + + /// + /// Index the package from an upstream if it does not exist locally. + /// + /// The package ID to index from an upstream. + /// The package version to index from an upstream. + /// + /// True if the package exists locally or was indexed from an upstream source. + private async Task MirrorAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + if (await _db.ExistsAsync(id, version, cancellationToken)) { - if (await _db.ExistsAsync(id, version, cancellationToken)) - { - return true; - } + return true; + } - _logger.LogInformation( - "Package {PackageId} {PackageVersion} does not exist locally. Checking upstream feed...", - id, - version); + _logger.LogInformation( + "Package {PackageId} {PackageVersion} does not exist locally. Checking upstream feed...", + id, + version); - try + try + { + using (var packageStream = await _upstream.DownloadPackageOrNullAsync(id, version, cancellationToken)) { - using (var packageStream = await _upstream.DownloadPackageOrNullAsync(id, version, cancellationToken)) + if (packageStream == null) { - if (packageStream == null) - { - _logger.LogWarning( - "Upstream feed does not have package {PackageId} {PackageVersion}", - id, - version); - return false; - } - - _logger.LogInformation( - "Downloaded package {PackageId} {PackageVersion}, indexing...", + _logger.LogWarning( + "Upstream feed does not have package {PackageId} {PackageVersion}", id, version); + return false; + } - var result = await _indexer.IndexAsync(packageStream, cancellationToken); + _logger.LogInformation( + "Downloaded package {PackageId} {PackageVersion}, indexing...", + id, + version); - _logger.LogInformation( - "Finished indexing package {PackageId} {PackageVersion} from upstream feed with result {Result}", - id, - version, - result); + var result = await _indexer.IndexAsync(packageStream, cancellationToken); - return result == PackageIndexingResult.Success; - } - } - catch (Exception e) - { - _logger.LogError( - e, - "Failed to index package {PackageId} {PackageVersion} from upstream", + _logger.LogInformation( + "Finished indexing package {PackageId} {PackageVersion} from upstream feed with result {Result}", id, - version); + version, + result); - return false; + return result == PackageIndexingResult.Success; } } + catch (Exception e) + { + _logger.LogError( + e, + "Failed to index package {PackageId} {PackageVersion} from upstream", + id, + version); + + return false; + } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/AutocompleteRequest.cs b/src/BaGet.Core/Search/AutocompleteRequest.cs index ef5b0b976..f21ecccba 100644 --- a/src/BaGet.Core/Search/AutocompleteRequest.cs +++ b/src/BaGet.Core/Search/AutocompleteRequest.cs @@ -1,39 +1,38 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The NuGet V3 search request. +/// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#request-parameters +/// +public class AutocompleteRequest { /// - /// The NuGet V3 search request. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#request-parameters + /// The number of results to skip, for pagination. /// - public class AutocompleteRequest - { - /// - /// The number of results to skip, for pagination. - /// - public int Skip { get; set; } + public int Skip { get; set; } - /// - /// The number of results to return, for pagination. - /// - public int Take { get; set; } + /// + /// The number of results to return, for pagination. + /// + public int Take { get; set; } - /// - /// Whether to include pre-release packages. - /// - public bool IncludePrerelease { get; set; } + /// + /// Whether to include pre-release packages. + /// + public bool IncludePrerelease { get; set; } - /// - /// Whether to include SemVer 2.0.0 compatible packages. - /// - public bool IncludeSemVer2 { get; set; } + /// + /// Whether to include SemVer 2.0.0 compatible packages. + /// + public bool IncludeSemVer2 { get; set; } - /// - /// Filter results to a package type. If null, no filter is applied. - /// - public string PackageType { get; set; } + /// + /// Filter results to a package type. If null, no filter is applied. + /// + public string PackageType { get; set; } - /// - /// The search query. - /// - public string Query { get; set; } - } -} + /// + /// The search query. + /// + public string Query { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/DatabaseSearchService.cs b/src/BaGet.Core/Search/DatabaseSearchService.cs index 95353dec2..21d111662 100644 --- a/src/BaGet.Core/Search/DatabaseSearchService.cs +++ b/src/BaGet.Core/Search/DatabaseSearchService.cs @@ -6,254 +6,253 @@ using BaGet.Protocol.Models; using Microsoft.EntityFrameworkCore; -namespace BaGet.Core +namespace BaGet.Core; + +public class DatabaseSearchService : ISearchService { - public class DatabaseSearchService : ISearchService + private readonly IContext _context; + private readonly IFrameworkCompatibilityService _frameworks; + private readonly ISearchResponseBuilder _searchBuilder; + + public DatabaseSearchService( + IContext context, + IFrameworkCompatibilityService frameworks, + ISearchResponseBuilder searchBuilder) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); + _searchBuilder = searchBuilder ?? throw new ArgumentNullException(nameof(searchBuilder)); + } + + public async Task SearchAsync(SearchRequest request, CancellationToken cancellationToken) { - private readonly IContext _context; - private readonly IFrameworkCompatibilityService _frameworks; - private readonly ISearchResponseBuilder _searchBuilder; - - public DatabaseSearchService( - IContext context, - IFrameworkCompatibilityService frameworks, - ISearchResponseBuilder searchBuilder) + var frameworks = GetCompatibleFrameworksOrNull(request.Framework); + + IQueryable search = _context.Packages; + search = ApplySearchQuery(search, request.Query); + search = ApplySearchFilters( + search, + request.IncludePrerelease, + request.IncludeSemVer2, + request.PackageType, + frameworks); + + // "TotalHits" is the number of matches disregarding skip and take. A page of results is + // drawn from the distinct package ids that match the filters, so the total must count + // those distinct ids - not the matching rows, of which there is one per package version. + var totalHits = await CountDistinctPackageIdsAsync(search, cancellationToken); + + var packageIds = search + .Select(p => p.Id) + .Distinct() + .OrderBy(id => id) + .Skip(request.Skip) + .Take(request.Take); + + // This query MUST fetch all versions for each package that matches the search, + // otherwise the results for a package's latest version may be incorrect. + // If possible, we'll find all these packages in a single query by matching + // the package IDs in a subquery. Otherwise, run two queries: + // 1. Find the package IDs that match the search + // 2. Find all package versions for these package IDs + if (_context.SupportsLimitInSubqueries) { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); - _searchBuilder = searchBuilder ?? throw new ArgumentNullException(nameof(searchBuilder)); + search = _context.Packages.Where(p => packageIds.Contains(p.Id)); } - - public async Task SearchAsync(SearchRequest request, CancellationToken cancellationToken) + else { - var frameworks = GetCompatibleFrameworksOrNull(request.Framework); - - IQueryable search = _context.Packages; - search = ApplySearchQuery(search, request.Query); - search = ApplySearchFilters( - search, - request.IncludePrerelease, - request.IncludeSemVer2, - request.PackageType, - frameworks); - - // "TotalHits" is the number of matches disregarding skip and take. A page of results is - // drawn from the distinct package ids that match the filters, so the total must count - // those distinct ids - not the matching rows, of which there is one per package version. - var totalHits = await CountDistinctPackageIdsAsync(search, cancellationToken); - - var packageIds = search - .Select(p => p.Id) - .Distinct() - .OrderBy(id => id) - .Skip(request.Skip) - .Take(request.Take); - - // This query MUST fetch all versions for each package that matches the search, - // otherwise the results for a package's latest version may be incorrect. - // If possible, we'll find all these packages in a single query by matching - // the package IDs in a subquery. Otherwise, run two queries: - // 1. Find the package IDs that match the search - // 2. Find all package versions for these package IDs - if (_context.SupportsLimitInSubqueries) - { - search = _context.Packages.Where(p => packageIds.Contains(p.Id)); - } - else - { - var packageIdResults = await packageIds.ToListAsync(cancellationToken); + var packageIdResults = await packageIds.ToListAsync(cancellationToken); - search = _context.Packages.Where(p => packageIdResults.Contains(p.Id)); - } + search = _context.Packages.Where(p => packageIdResults.Contains(p.Id)); + } - search = ApplySearchFilters( - search, - request.IncludePrerelease, - request.IncludeSemVer2, - request.PackageType, - frameworks); + search = ApplySearchFilters( + search, + request.IncludePrerelease, + request.IncludeSemVer2, + request.PackageType, + frameworks); - var results = await search - .Include(p => p.Deprecation) - .Include(p => p.Vulnerabilities) - .ToListAsync(cancellationToken); - var groupedResults = results - .GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase) - .Select(group => new PackageRegistration(group.Key, group.ToList())) - .ToList(); + var results = await search + .Include(p => p.Deprecation) + .Include(p => p.Vulnerabilities) + .ToListAsync(cancellationToken); + var groupedResults = results + .GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase) + .Select(group => new PackageRegistration(group.Key, group.ToList())) + .ToList(); - var response = _searchBuilder.BuildSearch(groupedResults, totalHits); + var response = _searchBuilder.BuildSearch(groupedResults, totalHits); - await AddOwnersAsync(response, cancellationToken); + await AddOwnersAsync(response, cancellationToken); - return response; - } + return response; + } + + /// + /// Report each result's owners. A package pushed before accounts existed has none, + /// and then neither field is reported. + /// + private async Task AddOwnersAsync(SearchResponse response, CancellationToken cancellationToken) + { + if (response.Data.Count == 0) return; - /// - /// Report each result's owners. A package pushed before accounts existed has none, - /// and then neither field is reported. - /// - private async Task AddOwnersAsync(SearchResponse response, CancellationToken cancellationToken) + var ids = response.Data.Select(r => r.PackageId.ToLower()).ToList(); + var owners = await _context.PackageOwners + .AsNoTracking() + .Where(o => ids.Contains(o.PackageId.ToLower())) + .ToListAsync(cancellationToken); + + var byId = owners.ToLookup(o => o.PackageId, StringComparer.OrdinalIgnoreCase); + foreach (var result in response.Data) { - if (response.Data.Count == 0) return; + var resultOwners = byId[result.PackageId].ToList(); + if (resultOwners.Count == 0) continue; + + result.Owners = resultOwners.Select(o => o.OwnerName).OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList(); + result.Verified = resultOwners.Any(o => o.IsVerified); + } + } + + public async Task AutocompleteAsync( + AutocompleteRequest request, + CancellationToken cancellationToken) + { + IQueryable search = _context.Packages; + + search = ApplySearchQuery(search, request.Query); + search = ApplySearchFilters( + search, + request.IncludePrerelease, + request.IncludeSemVer2, + request.PackageType, + frameworks: null); + + // See the comment in "SearchAsync": the total disregards skip and take and counts + // distinct package ids, which is what the page below is drawn from. + var totalHits = await CountDistinctPackageIdsAsync(search, cancellationToken); + + // Group by package ID so that the column the results are ordered by is part of + // the query's projection. Ordering before a "Distinct" over a narrower projection + // is silently dropped, and SQL Server rejects the resulting query outright: + // "ORDER BY items must appear in the select list if SELECT DISTINCT is specified." + var packageIds = await search + .GroupBy(p => p.Id) + .OrderByDescending(packages => packages.Sum(p => p.Downloads)) + .Select(packages => packages.Key) + .Skip(request.Skip) + .Take(request.Take) + .ToListAsync(cancellationToken); + + return _searchBuilder.BuildAutocomplete(packageIds, totalHits); + } - var ids = response.Data.Select(r => r.PackageId.ToLower()).ToList(); - var owners = await _context.PackageOwners - .AsNoTracking() - .Where(o => ids.Contains(o.PackageId.ToLower())) - .ToListAsync(cancellationToken); + public async Task ListPackageVersionsAsync( + VersionsRequest request, + CancellationToken cancellationToken) + { + var packageId = request.PackageId.ToLower(); + var search = _context + .Packages + .Where(p => p.Id.ToLower().Equals(packageId)); + + search = ApplySearchFilters( + search, + request.IncludePrerelease, + request.IncludeSemVer2, + packageType: null, + frameworks: null); + + var packageVersions = await search + .Select(p => p.NormalizedVersionString) + .ToListAsync(cancellationToken); + + // Version enumeration is not paged, so every match is on the single page returned. + return _searchBuilder.BuildAutocomplete(packageVersions, packageVersions.Count); + } - var byId = owners.ToLookup(o => o.PackageId, StringComparer.OrdinalIgnoreCase); - foreach (var result in response.Data) + public async Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) + { + var dependents = await _context + .Packages + .Where(p => p.Listed) + .OrderByDescending(p => p.Downloads) + .Where(p => p.Dependencies.Any(d => d.Id == packageId)) + .Take(20) + .Select(r => new PackageDependent { - var resultOwners = byId[result.PackageId].ToList(); - if (resultOwners.Count == 0) continue; + Id = r.Id, + Description = r.Description, + TotalDownloads = r.Downloads + }) + .Distinct() + .ToListAsync(cancellationToken); + + return _searchBuilder.BuildDependents(dependents); + } - result.Owners = resultOwners.Select(o => o.OwnerName).OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList(); - result.Verified = resultOwners.Any(o => o.IsVerified); - } - } + /// + /// Count the packages matched by a filtered query, disregarding skip and take. + /// A single package is stored as one row per version, so the matching rows must be + /// reduced to their distinct package ids first. This mirrors the projection that the + /// paged queries use, so the total is always consistent with the page. + /// + private static Task CountDistinctPackageIdsAsync( + IQueryable search, + CancellationToken cancellationToken) + { + return search + .Select(p => p.Id) + .Distinct() + .CountAsync(cancellationToken); + } - public async Task AutocompleteAsync( - AutocompleteRequest request, - CancellationToken cancellationToken) + private IQueryable ApplySearchQuery(IQueryable query, string search) + { + if (string.IsNullOrEmpty(search)) { - IQueryable search = _context.Packages; - - search = ApplySearchQuery(search, request.Query); - search = ApplySearchFilters( - search, - request.IncludePrerelease, - request.IncludeSemVer2, - request.PackageType, - frameworks: null); - - // See the comment in "SearchAsync": the total disregards skip and take and counts - // distinct package ids, which is what the page below is drawn from. - var totalHits = await CountDistinctPackageIdsAsync(search, cancellationToken); - - // Group by package ID so that the column the results are ordered by is part of - // the query's projection. Ordering before a "Distinct" over a narrower projection - // is silently dropped, and SQL Server rejects the resulting query outright: - // "ORDER BY items must appear in the select list if SELECT DISTINCT is specified." - var packageIds = await search - .GroupBy(p => p.Id) - .OrderByDescending(packages => packages.Sum(p => p.Downloads)) - .Select(packages => packages.Key) - .Skip(request.Skip) - .Take(request.Take) - .ToListAsync(cancellationToken); - - return _searchBuilder.BuildAutocomplete(packageIds, totalHits); + return query; } - public async Task ListPackageVersionsAsync( - VersionsRequest request, - CancellationToken cancellationToken) - { - var packageId = request.PackageId.ToLower(); - var search = _context - .Packages - .Where(p => p.Id.ToLower().Equals(packageId)); - - search = ApplySearchFilters( - search, - request.IncludePrerelease, - request.IncludeSemVer2, - packageType: null, - frameworks: null); - - var packageVersions = await search - .Select(p => p.NormalizedVersionString) - .ToListAsync(cancellationToken); - - // Version enumeration is not paged, so every match is on the single page returned. - return _searchBuilder.BuildAutocomplete(packageVersions, packageVersions.Count); - } + search = search.ToLowerInvariant(); + + return query.Where(p => p.Id.ToLower().Contains(search)); + } - public async Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) + private IQueryable ApplySearchFilters( + IQueryable query, + bool includePrerelease, + bool includeSemVer2, + string packageType, + IReadOnlyList frameworks) + { + if (!includePrerelease) { - var dependents = await _context - .Packages - .Where(p => p.Listed) - .OrderByDescending(p => p.Downloads) - .Where(p => p.Dependencies.Any(d => d.Id == packageId)) - .Take(20) - .Select(r => new PackageDependent - { - Id = r.Id, - Description = r.Description, - TotalDownloads = r.Downloads - }) - .Distinct() - .ToListAsync(cancellationToken); - - return _searchBuilder.BuildDependents(dependents); + query = query.Where(p => !p.IsPrerelease); } - /// - /// Count the packages matched by a filtered query, disregarding skip and take. - /// A single package is stored as one row per version, so the matching rows must be - /// reduced to their distinct package ids first. This mirrors the projection that the - /// paged queries use, so the total is always consistent with the page. - /// - private static Task CountDistinctPackageIdsAsync( - IQueryable search, - CancellationToken cancellationToken) + if (!includeSemVer2) { - return search - .Select(p => p.Id) - .Distinct() - .CountAsync(cancellationToken); + query = query.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); } - private IQueryable ApplySearchQuery(IQueryable query, string search) + if (!string.IsNullOrEmpty(packageType)) { - if (string.IsNullOrEmpty(search)) - { - return query; - } - - search = search.ToLowerInvariant(); - - return query.Where(p => p.Id.ToLower().Contains(search)); + query = query.Where(p => p.PackageTypes.Any(t => t.Name == packageType)); } - private IQueryable ApplySearchFilters( - IQueryable query, - bool includePrerelease, - bool includeSemVer2, - string packageType, - IReadOnlyList frameworks) + if (frameworks != null) { - if (!includePrerelease) - { - query = query.Where(p => !p.IsPrerelease); - } - - if (!includeSemVer2) - { - query = query.Where(p => p.SemVerLevel != SemVerLevel.SemVer2); - } - - if (!string.IsNullOrEmpty(packageType)) - { - query = query.Where(p => p.PackageTypes.Any(t => t.Name == packageType)); - } - - if (frameworks != null) - { - query = query.Where(p => p.TargetFrameworks.Any(f => frameworks.Contains(f.Moniker))); - } - - return query.Where(p => p.Listed); + query = query.Where(p => p.TargetFrameworks.Any(f => frameworks.Contains(f.Moniker))); } - private IReadOnlyList GetCompatibleFrameworksOrNull(string framework) - { - if (framework == null) return null; + return query.Where(p => p.Listed); + } - return _frameworks.FindAllCompatibleFrameworks(framework); - } + private IReadOnlyList GetCompatibleFrameworksOrNull(string framework) + { + if (framework == null) return null; + + return _frameworks.FindAllCompatibleFrameworks(framework); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/DependentsResponse.cs b/src/BaGet.Core/Search/DependentsResponse.cs index 2d7970455..288fcb184 100644 --- a/src/BaGet.Core/Search/DependentsResponse.cs +++ b/src/BaGet.Core/Search/DependentsResponse.cs @@ -1,48 +1,47 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The package ids that depend on the queried package. +/// This is an unofficial API that isn't part of the NuGet protocol. +/// +public class DependentsResponse { /// - /// The package ids that depend on the queried package. - /// This is an unofficial API that isn't part of the NuGet protocol. + /// The total number of matches, disregarding skip and take. /// - public class DependentsResponse - { - /// - /// The total number of matches, disregarding skip and take. - /// - [JsonPropertyName("totalHits")] - public long TotalHits { get; set; } + [JsonPropertyName("totalHits")] + public long TotalHits { get; set; } - /// - /// The package IDs matched by the dependent query. - /// - [JsonPropertyName("data")] - public IReadOnlyList Data { get; set; } - } + /// + /// The package IDs matched by the dependent query. + /// + [JsonPropertyName("data")] + public IReadOnlyList Data { get; set; } +} +/// +/// A package that depends on the queried package. +/// +public class PackageDependent +{ /// - /// A package that depends on the queried package. + /// The dependent package id. /// - public class PackageDependent - { - /// - /// The dependent package id. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } - /// - /// The description of the dependent package. - /// - [JsonPropertyName("description")] - public string Description { get; set; } + /// + /// The description of the dependent package. + /// + [JsonPropertyName("description")] + public string Description { get; set; } - /// - /// The total downloads for the dependent package. - /// - [JsonPropertyName("totalDownloads")] - public long TotalDownloads { get; set; } - } -} + /// + /// The total downloads for the dependent package. + /// + [JsonPropertyName("totalDownloads")] + public long TotalDownloads { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/ISearchIndexer.cs b/src/BaGet.Core/Search/ISearchIndexer.cs index dd2ff4064..4a9c9e203 100644 --- a/src/BaGet.Core/Search/ISearchIndexer.cs +++ b/src/BaGet.Core/Search/ISearchIndexer.cs @@ -1,16 +1,15 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public interface ISearchIndexer { - public interface ISearchIndexer - { - /// - /// Add a package to the search index. - /// - /// The package to add. - /// A token to cancel the task. - /// A task that completes once the package has been added. - Task IndexAsync(Package package, CancellationToken cancellationToken); - } -} + /// + /// Add a package to the search index. + /// + /// The package to add. + /// A token to cancel the task. + /// A task that completes once the package has been added. + Task IndexAsync(Package package, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/ISearchResponseBuilder.cs b/src/BaGet.Core/Search/ISearchResponseBuilder.cs index 63770030a..445a3dc01 100644 --- a/src/BaGet.Core/Search/ISearchResponseBuilder.cs +++ b/src/BaGet.Core/Search/ISearchResponseBuilder.cs @@ -1,32 +1,31 @@ using System.Collections.Generic; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +public interface ISearchResponseBuilder { - public interface ISearchResponseBuilder - { - /// - /// Build a search response. - /// - /// The page of package registrations that should be returned. - /// - /// The total number of packages that matched the search, disregarding skip and take. - /// This is reported as , so it must count every - /// match and not merely the ones on the current page. - /// - SearchResponse BuildSearch(IReadOnlyList results, long totalHits); + /// + /// Build a search response. + /// + /// The page of package registrations that should be returned. + /// + /// The total number of packages that matched the search, disregarding skip and take. + /// This is reported as , so it must count every + /// match and not merely the ones on the current page. + /// + SearchResponse BuildSearch(IReadOnlyList results, long totalHits); - /// - /// Build an autocomplete response. - /// - /// The page of results that should be returned. - /// - /// The total number of results that matched the query, disregarding skip and take. - /// This is reported as , so it must count - /// every match and not merely the ones on the current page. - /// - AutocompleteResponse BuildAutocomplete(IReadOnlyList data, long totalHits); + /// + /// Build an autocomplete response. + /// + /// The page of results that should be returned. + /// + /// The total number of results that matched the query, disregarding skip and take. + /// This is reported as , so it must count + /// every match and not merely the ones on the current page. + /// + AutocompleteResponse BuildAutocomplete(IReadOnlyList data, long totalHits); - DependentsResponse BuildDependents(IReadOnlyList results); - } -} + DependentsResponse BuildDependents(IReadOnlyList results); +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/ISearchService.cs b/src/BaGet.Core/Search/ISearchService.cs index 0aeb9f928..b02f108a1 100644 --- a/src/BaGet.Core/Search/ISearchService.cs +++ b/src/BaGet.Core/Search/ISearchService.cs @@ -2,50 +2,49 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The service used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource +/// +public interface ISearchService { /// - /// The service used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// Perform a search query. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages /// - public interface ISearchService - { - /// - /// Perform a search query. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages - /// - /// The search request. - /// A token to cancel the task. - /// The search response. - Task SearchAsync(SearchRequest request, CancellationToken cancellationToken); + /// The search request. + /// A token to cancel the task. + /// The search response. + Task SearchAsync(SearchRequest request, CancellationToken cancellationToken); - /// - /// Perform an autocomplete query. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids - /// - /// The autocomplete request. - /// A token to cancel the task. - /// The autocomplete response. - Task AutocompleteAsync(AutocompleteRequest request, CancellationToken cancellationToken); + /// + /// Perform an autocomplete query. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids + /// + /// The autocomplete request. + /// A token to cancel the task. + /// The autocomplete response. + Task AutocompleteAsync(AutocompleteRequest request, CancellationToken cancellationToken); - /// - /// Enumerate listed package versions. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#enumerate-package-versions - /// - /// The autocomplete request. - /// A token to cancel the task. - /// The package versions that matched the request. - Task ListPackageVersionsAsync(VersionsRequest request, CancellationToken cancellationToken); + /// + /// Enumerate listed package versions. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#enumerate-package-versions + /// + /// The autocomplete request. + /// A token to cancel the task. + /// The package versions that matched the request. + Task ListPackageVersionsAsync(VersionsRequest request, CancellationToken cancellationToken); - /// - /// Find the packages that depend on a given package. - /// - /// The package whose dependents should be found. - /// A token to cancel the task. - /// The dependents response. - Task FindDependentsAsync( - string packageId, - CancellationToken cancellationToken); - } -} + /// + /// Find the packages that depend on a given package. + /// + /// The package whose dependents should be found. + /// A token to cancel the task. + /// The dependents response. + Task FindDependentsAsync( + string packageId, + CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/NullSearchIndexer.cs b/src/BaGet.Core/Search/NullSearchIndexer.cs index 0dd1c5ce8..1a85bf412 100644 --- a/src/BaGet.Core/Search/NullSearchIndexer.cs +++ b/src/BaGet.Core/Search/NullSearchIndexer.cs @@ -1,16 +1,15 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A no-op indexer, used when search does not need to index packages. +/// +public class NullSearchIndexer : ISearchIndexer { - /// - /// A no-op indexer, used when search does not need to index packages. - /// - public class NullSearchIndexer : ISearchIndexer + public Task IndexAsync(Package package, CancellationToken cancellationToken = default) { - public Task IndexAsync(Package package, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/NullSearchService.cs b/src/BaGet.Core/Search/NullSearchService.cs index e137183bd..a8c6bf44a 100644 --- a/src/BaGet.Core/Search/NullSearchService.cs +++ b/src/BaGet.Core/Search/NullSearchService.cs @@ -3,64 +3,63 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Core -{ - /// - /// A minimal search service implementation, used for advanced scenarios. - /// - public class NullSearchService : ISearchService - { - private static readonly IReadOnlyList EmptyStringList = new List(); - - // This service never matches anything, so zero is the total number of matches - // disregarding skip and take, not merely the size of the page returned. - - private static readonly Task EmptyAutocompleteResponseTask = - Task.FromResult(new AutocompleteResponse - { - TotalHits = 0, - Data = EmptyStringList, - Context = AutocompleteContext.Default - }); +namespace BaGet.Core; - private static readonly Task EmptyDependentsResponseTask = - Task.FromResult(new DependentsResponse - { - TotalHits = 0, - Data = new List() - }); +/// +/// A minimal search service implementation, used for advanced scenarios. +/// +public class NullSearchService : ISearchService +{ + private static readonly IReadOnlyList EmptyStringList = new List(); - private static readonly Task EmptySearchResponseTask = - Task.FromResult(new SearchResponse - { - TotalHits = 0, - Data = new List() - }); + // This service never matches anything, so zero is the total number of matches + // disregarding skip and take, not merely the size of the page returned. - public Task AutocompleteAsync( - AutocompleteRequest request, - CancellationToken cancellationToken) + private static readonly Task EmptyAutocompleteResponseTask = + Task.FromResult(new AutocompleteResponse { - return EmptyAutocompleteResponseTask; - } + TotalHits = 0, + Data = EmptyStringList, + Context = AutocompleteContext.Default + }); - public Task ListPackageVersionsAsync( - VersionsRequest request, - CancellationToken cancellationToken) + private static readonly Task EmptyDependentsResponseTask = + Task.FromResult(new DependentsResponse { - return EmptyAutocompleteResponseTask; - } + TotalHits = 0, + Data = new List() + }); - public Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) + private static readonly Task EmptySearchResponseTask = + Task.FromResult(new SearchResponse { - return EmptyDependentsResponseTask; - } + TotalHits = 0, + Data = new List() + }); - public Task SearchAsync( - SearchRequest request, - CancellationToken cancellationToken) - { - return EmptySearchResponseTask; - } + public Task AutocompleteAsync( + AutocompleteRequest request, + CancellationToken cancellationToken) + { + return EmptyAutocompleteResponseTask; + } + + public Task ListPackageVersionsAsync( + VersionsRequest request, + CancellationToken cancellationToken) + { + return EmptyAutocompleteResponseTask; + } + + public Task FindDependentsAsync(string packageId, CancellationToken cancellationToken) + { + return EmptyDependentsResponseTask; + } + + public Task SearchAsync( + SearchRequest request, + CancellationToken cancellationToken) + { + return EmptySearchResponseTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/SearchRequest.cs b/src/BaGet.Core/Search/SearchRequest.cs index fd81250b0..9057ed960 100644 --- a/src/BaGet.Core/Search/SearchRequest.cs +++ b/src/BaGet.Core/Search/SearchRequest.cs @@ -1,44 +1,43 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The NuGet V3 search request. +/// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#request-parameters +/// +public class SearchRequest { /// - /// The NuGet V3 search request. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#request-parameters + /// The number of results to skip, for pagination. /// - public class SearchRequest - { - /// - /// The number of results to skip, for pagination. - /// - public int Skip { get; set; } + public int Skip { get; set; } - /// - /// The number of results to return, for pagination. - /// - public int Take { get; set; } + /// + /// The number of results to return, for pagination. + /// + public int Take { get; set; } - /// - /// Whether to include pre-release packages. - /// - public bool IncludePrerelease { get; set; } + /// + /// Whether to include pre-release packages. + /// + public bool IncludePrerelease { get; set; } - /// - /// Whether to include SemVer 2.0.0 compatible packages. - /// - public bool IncludeSemVer2 { get; set; } + /// + /// Whether to include SemVer 2.0.0 compatible packages. + /// + public bool IncludeSemVer2 { get; set; } - /// - /// Filter results to a package type. If null, no filter is applied. - /// - public string PackageType { get; set; } + /// + /// Filter results to a package type. If null, no filter is applied. + /// + public string PackageType { get; set; } - /// - /// Filters results to a target framework. If null, no filter is applied. - /// - public string Framework { get; set; } + /// + /// Filters results to a target framework. If null, no filter is applied. + /// + public string Framework { get; set; } - /// - /// The search query. - /// - public string Query { get; set; } - } -} + /// + /// The search query. + /// + public string Query { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/SearchResponseBuilder.cs b/src/BaGet.Core/Search/SearchResponseBuilder.cs index 3a78083a3..3b41b967e 100644 --- a/src/BaGet.Core/Search/SearchResponseBuilder.cs +++ b/src/BaGet.Core/Search/SearchResponseBuilder.cs @@ -3,81 +3,80 @@ using System.Linq; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +public class SearchResponseBuilder : ISearchResponseBuilder { - public class SearchResponseBuilder : ISearchResponseBuilder + private readonly IUrlGenerator _url; + + public SearchResponseBuilder(IUrlGenerator url) { - private readonly IUrlGenerator _url; + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - public SearchResponseBuilder(IUrlGenerator url) - { - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public SearchResponse BuildSearch(IReadOnlyList packageRegistrations, long totalHits) + { + var result = new List(); - public SearchResponse BuildSearch(IReadOnlyList packageRegistrations, long totalHits) + foreach (var packageRegistration in packageRegistrations) { - var result = new List(); + var versions = packageRegistration.Packages.OrderByDescending(p => p.Version).ToList(); + var latest = versions.First(); + var iconUrl = latest.HasEmbeddedIcon + ? _url.GetPackageIconDownloadUrl(latest.Id, latest.Version) + : latest.IconUrlString; - foreach (var packageRegistration in packageRegistrations) + result.Add(new SearchResult { - var versions = packageRegistration.Packages.OrderByDescending(p => p.Version).ToList(); - var latest = versions.First(); - var iconUrl = latest.HasEmbeddedIcon - ? _url.GetPackageIconDownloadUrl(latest.Id, latest.Version) - : latest.IconUrlString; - - result.Add(new SearchResult - { - PackageId = latest.Id, - Version = latest.Version.ToFullString(), - Description = latest.Description, - Authors = latest.Authors, - IconUrl = iconUrl, - LicenseUrl = latest.LicenseUrlString, - ProjectUrl = latest.ProjectUrlString, - RegistrationIndexUrl = _url.GetRegistrationIndexUrl(latest.Id), - Summary = latest.Summary, - Tags = latest.Tags, - Title = latest.Title, - TotalDownloads = versions.Sum(p => p.Downloads), - Versions = versions - .Select(p => new SearchResultVersion - { - RegistrationLeafUrl = _url.GetRegistrationLeafUrl(p.Id, p.Version), - Version = p.Version.ToFullString(), - Downloads = p.Downloads, - }) - .ToList(), - Deprecation = RegistrationBuilder.ToDeprecation(latest.Deprecation), - Vulnerabilities = RegistrationBuilder.ToVulnerabilities(latest.Vulnerabilities), - }); - } - - return new SearchResponse - { - TotalHits = totalHits, - Data = result, - Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl()), - }; + PackageId = latest.Id, + Version = latest.Version.ToFullString(), + Description = latest.Description, + Authors = latest.Authors, + IconUrl = iconUrl, + LicenseUrl = latest.LicenseUrlString, + ProjectUrl = latest.ProjectUrlString, + RegistrationIndexUrl = _url.GetRegistrationIndexUrl(latest.Id), + Summary = latest.Summary, + Tags = latest.Tags, + Title = latest.Title, + TotalDownloads = versions.Sum(p => p.Downloads), + Versions = versions + .Select(p => new SearchResultVersion + { + RegistrationLeafUrl = _url.GetRegistrationLeafUrl(p.Id, p.Version), + Version = p.Version.ToFullString(), + Downloads = p.Downloads, + }) + .ToList(), + Deprecation = RegistrationBuilder.ToDeprecation(latest.Deprecation), + Vulnerabilities = RegistrationBuilder.ToVulnerabilities(latest.Vulnerabilities), + }); } - public AutocompleteResponse BuildAutocomplete(IReadOnlyList data, long totalHits) + return new SearchResponse { - return new AutocompleteResponse - { - TotalHits = totalHits, - Data = data, - Context = AutocompleteContext.Default - }; - } + TotalHits = totalHits, + Data = result, + Context = SearchContext.Default(_url.GetPackageMetadataResourceUrl()), + }; + } - public DependentsResponse BuildDependents(IReadOnlyList packages) + public AutocompleteResponse BuildAutocomplete(IReadOnlyList data, long totalHits) + { + return new AutocompleteResponse { - return new DependentsResponse - { - TotalHits = packages.Count, - Data = packages, - }; - } + TotalHits = totalHits, + Data = data, + Context = AutocompleteContext.Default + }; + } + + public DependentsResponse BuildDependents(IReadOnlyList packages) + { + return new DependentsResponse + { + TotalHits = packages.Count, + Data = packages, + }; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Search/VersionsRequest.cs b/src/BaGet.Core/Search/VersionsRequest.cs index 974fc5d90..5ca2f32a6 100644 --- a/src/BaGet.Core/Search/VersionsRequest.cs +++ b/src/BaGet.Core/Search/VersionsRequest.cs @@ -1,24 +1,23 @@ -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The NuGet V3 enumerate package versions request. +/// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#request-parameters-1 +/// +public class VersionsRequest { /// - /// The NuGet V3 enumerate package versions request. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#request-parameters-1 + /// Whether to include pre-release packages. /// - public class VersionsRequest - { - /// - /// Whether to include pre-release packages. - /// - public bool IncludePrerelease { get; set; } + public bool IncludePrerelease { get; set; } - /// - /// Whether to include SemVer 2.0.0 compatible packages. - /// - public bool IncludeSemVer2 { get; set; } + /// + /// Whether to include SemVer 2.0.0 compatible packages. + /// + public bool IncludeSemVer2 { get; set; } - /// - /// The package ID whose versions should be fetched. - /// - public string PackageId { get; set; } - } -} + /// + /// The package ID whose versions should be fetched. + /// + public string PackageId { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Core/ServiceIndex/BaGetServiceIndex.cs b/src/BaGet.Core/ServiceIndex/BaGetServiceIndex.cs index 22a685705..c858e05be 100644 --- a/src/BaGet.Core/ServiceIndex/BaGetServiceIndex.cs +++ b/src/BaGet.Core/ServiceIndex/BaGetServiceIndex.cs @@ -5,64 +5,63 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +public class BaGetServiceIndex : IServiceIndexService { - public class BaGetServiceIndex : IServiceIndexService + private readonly IUrlGenerator _url; + private readonly IReadOnlyList _providers; + + public BaGetServiceIndex(IUrlGenerator url) + : this(url, Array.Empty()) { - private readonly IUrlGenerator _url; - private readonly IReadOnlyList _providers; + } - public BaGetServiceIndex(IUrlGenerator url) - : this(url, Array.Empty()) - { - } + public BaGetServiceIndex(IUrlGenerator url, IEnumerable providers) + { + _url = url ?? throw new ArgumentNullException(nameof(url)); + _providers = providers?.ToList() ?? throw new ArgumentNullException(nameof(providers)); + } - public BaGetServiceIndex(IUrlGenerator url, IEnumerable providers) + private IEnumerable BuildResource(string name, string url, params string[] versions) + { + foreach (var version in versions) { - _url = url ?? throw new ArgumentNullException(nameof(url)); - _providers = providers?.ToList() ?? throw new ArgumentNullException(nameof(providers)); - } + var type = string.IsNullOrEmpty(version) ? name : $"{name}/{version}"; - private IEnumerable BuildResource(string name, string url, params string[] versions) - { - foreach (var version in versions) + yield return new ServiceIndexItem { - var type = string.IsNullOrEmpty(version) ? name : $"{name}/{version}"; - - yield return new ServiceIndexItem - { - ResourceUrl = url, - Type = type, - }; - } + ResourceUrl = url, + Type = type, + }; } + } - public Task GetAsync(CancellationToken cancellationToken = default) - { - var resources = new List(); + public Task GetAsync(CancellationToken cancellationToken = default) + { + var resources = new List(); - resources.AddRange(BuildResource("PackagePublish", _url.GetPackagePublishResourceUrl(), "2.0.0")); - resources.AddRange(BuildResource("SymbolPackagePublish", _url.GetSymbolPublishResourceUrl(), "4.9.0")); - resources.AddRange(BuildResource("SearchQueryService", _url.GetSearchResourceUrl(), "", "3.0.0-beta", "3.0.0-rc")); - resources.AddRange(BuildResource("RegistrationsBaseUrl", _url.GetPackageMetadataResourceUrl(), "", "3.0.0-rc", "3.0.0-beta")); - resources.AddRange(BuildResource("PackageBaseAddress", _url.GetPackageContentResourceUrl(), "3.0.0")); - resources.AddRange(BuildResource("SearchAutocompleteService", _url.GetAutocompleteResourceUrl(), "", "3.0.0-rc", "3.0.0-beta")); - resources.AddRange(BuildResource("PackageDetailsUriTemplate", _url.GetPackageDetailsUriTemplate(), "5.1.0")); - resources.AddRange(BuildResource("ReportAbuseUriTemplate", _url.GetReportAbuseUriTemplate(), "3.0.0-beta", "3.0.0-rc")); - resources.AddRange(BuildResource("VulnerabilityInfo", _url.GetVulnerabilityIndexUrl(), "6.7.0")); + resources.AddRange(BuildResource("PackagePublish", _url.GetPackagePublishResourceUrl(), "2.0.0")); + resources.AddRange(BuildResource("SymbolPackagePublish", _url.GetSymbolPublishResourceUrl(), "4.9.0")); + resources.AddRange(BuildResource("SearchQueryService", _url.GetSearchResourceUrl(), "", "3.0.0-beta", "3.0.0-rc")); + resources.AddRange(BuildResource("RegistrationsBaseUrl", _url.GetPackageMetadataResourceUrl(), "", "3.0.0-rc", "3.0.0-beta")); + resources.AddRange(BuildResource("PackageBaseAddress", _url.GetPackageContentResourceUrl(), "3.0.0")); + resources.AddRange(BuildResource("SearchAutocompleteService", _url.GetAutocompleteResourceUrl(), "", "3.0.0-rc", "3.0.0-beta")); + resources.AddRange(BuildResource("PackageDetailsUriTemplate", _url.GetPackageDetailsUriTemplate(), "5.1.0")); + resources.AddRange(BuildResource("ReportAbuseUriTemplate", _url.GetReportAbuseUriTemplate(), "3.0.0-beta", "3.0.0-rc")); + resources.AddRange(BuildResource("VulnerabilityInfo", _url.GetVulnerabilityIndexUrl(), "6.7.0")); - foreach (var provider in _providers) - { - resources.AddRange(provider.GetResources()); - } + foreach (var provider in _providers) + { + resources.AddRange(provider.GetResources()); + } - var result = new ServiceIndexResponse - { - Version = "3.0.0", - Resources = resources, - }; + var result = new ServiceIndexResponse + { + Version = "3.0.0", + Resources = resources, + }; - return Task.FromResult(result); - } + return Task.FromResult(result); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/ServiceIndex/IServiceIndexResourceProvider.cs b/src/BaGet.Core/ServiceIndex/IServiceIndexResourceProvider.cs index 1c5892929..1d5d59c1f 100644 --- a/src/BaGet.Core/ServiceIndex/IServiceIndexResourceProvider.cs +++ b/src/BaGet.Core/ServiceIndex/IServiceIndexResourceProvider.cs @@ -1,13 +1,12 @@ using System.Collections.Generic; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Adds resources to the service index, for features that live outside BaGet.Core. +/// +public interface IServiceIndexResourceProvider { - /// - /// Adds resources to the service index, for features that live outside BaGet.Core. - /// - public interface IServiceIndexResourceProvider - { - IEnumerable GetResources(); - } -} + IEnumerable GetResources(); +} \ No newline at end of file diff --git a/src/BaGet.Core/ServiceIndex/IServiceIndexService.cs b/src/BaGet.Core/ServiceIndex/IServiceIndexService.cs index 67bf9a8b0..b7687b0d8 100644 --- a/src/BaGet.Core/ServiceIndex/IServiceIndexService.cs +++ b/src/BaGet.Core/ServiceIndex/IServiceIndexService.cs @@ -2,20 +2,19 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The NuGet Service Index service, used to discover other resources. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/service-index +/// +public interface IServiceIndexService { /// - /// The NuGet Service Index service, used to discover other resources. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index + /// Get the resources available on this package feed. + /// See: https://docs.microsoft.com/en-us/nuget/api/service-index#resources /// - public interface IServiceIndexService - { - /// - /// Get the resources available on this package feed. - /// See: https://docs.microsoft.com/en-us/nuget/api/service-index#resources - /// - /// The resources available on this package feed. - Task GetAsync(CancellationToken cancellationToken = default); - } -} + /// The resources available on this package feed. + Task GetAsync(CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Core/Staging/IPackageStagingService.cs b/src/BaGet.Core/Staging/IPackageStagingService.cs index 165227d07..0195c2c30 100644 --- a/src/BaGet.Core/Staging/IPackageStagingService.cs +++ b/src/BaGet.Core/Staging/IPackageStagingService.cs @@ -3,45 +3,44 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Holds a package between the two requests of a browser upload: the first stages it and +/// shows what it contains, the second confirms it. The upload is stored, not held in the +/// request, so the two requests may land on different instances. +/// +public interface IPackageStagingService { /// - /// Holds a package between the two requests of a browser upload: the first stages it and - /// shows what it contains, the second confirms it. The upload is stored, not held in the - /// request, so the two requests may land on different instances. + /// Stage an upload for . /// - public interface IPackageStagingService - { - /// - /// Stage an upload for . - /// - /// An opaque token identifying the staged upload. - Task StageAsync(Stream package, string ownerId, CancellationToken cancellationToken = default); + /// An opaque token identifying the staged upload. + Task StageAsync(Stream package, string ownerId, CancellationToken cancellationToken = default); - /// - /// The staged package, or null if the token is unknown, incomplete, or was staged by - /// a different user. - /// - Task OpenAsync(string token, string ownerId, CancellationToken cancellationToken = default); + /// + /// The staged package, or null if the token is unknown, incomplete, or was staged by + /// a different user. + /// + Task OpenAsync(string token, string ownerId, CancellationToken cancellationToken = default); - /// - /// Forget a staged upload, whether it was confirmed or cancelled. The owner is - /// checked exactly as checks it: the token is the only handle - /// on an upload, so without this anyone who learned one could discard someone else's - /// pending upload. An unknown token is not an error. - /// - /// - /// Whether an upload was removed. False when the token is unknown or belongs to a - /// different user, which are deliberately indistinguishable. - /// - Task RemoveAsync(string token, string ownerId, CancellationToken cancellationToken = default); + /// + /// Forget a staged upload, whether it was confirmed or cancelled. The owner is + /// checked exactly as checks it: the token is the only handle + /// on an upload, so without this anyone who learned one could discard someone else's + /// pending upload. An unknown token is not an error. + /// + /// + /// Whether an upload was removed. False when the token is unknown or belongs to a + /// different user, which are deliberately indistinguishable. + /// + Task RemoveAsync(string token, string ownerId, CancellationToken cancellationToken = default); - /// - /// Remove every upload staged before . An upload that - /// is never confirmed nor cancelled - a closed browser tab - is only collected here, - /// so without this staging grows without bound. - /// - /// How many staged uploads were removed. - Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default); - } -} + /// + /// Remove every upload staged before . An upload that + /// is never confirmed nor cancelled - a closed browser tab - is only collected here, + /// so without this staging grows without bound. + /// + /// How many staged uploads were removed. + Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Core/Staging/StoragePackageStagingService.cs b/src/BaGet.Core/Staging/StoragePackageStagingService.cs index fc423dee1..b4409759c 100644 --- a/src/BaGet.Core/Staging/StoragePackageStagingService.cs +++ b/src/BaGet.Core/Staging/StoragePackageStagingService.cs @@ -8,371 +8,370 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Stages uploads in under a prefix of their own, so that +/// the two requests of a browser upload may land on different instances and so that +/// every storage provider works, exactly as the validation pipeline stages pushed +/// packages under "validation/". +/// +/// +/// Nothing serves the staging prefix: no route turns a request into a storage path, so a +/// staged upload is reachable only through , which is where the +/// owner is checked. +/// +public class StoragePackageStagingService : IPackageStagingService { /// - /// Stages uploads in under a prefix of their own, so that - /// the two requests of a browser upload may land on different instances and so that - /// every storage provider works, exactly as the validation pipeline stages pushed - /// packages under "validation/". + /// The prefix every staged upload lives under. A token never becomes anything else. /// - /// - /// Nothing serves the staging prefix: no route turns a request into a storage path, so a - /// staged upload is reachable only through , which is where the - /// owner is checked. - /// - public class StoragePackageStagingService : IPackageStagingService + internal const string StagingPathPrefix = "staging"; + + /// + /// 128 bits from a cryptographic generator, hex encoded. The token is the only thing + /// naming a staged upload, so guessing one must not be feasible. + /// + private const int TokenBytes = 16; + + private const int TokenLength = TokenBytes * 2; + + private readonly IStorageService _storage; + private readonly SystemTime _time; + private readonly ILogger _logger; + + public StoragePackageStagingService( + IStorageService storage, + SystemTime time, + ILogger logger) { - /// - /// The prefix every staged upload lives under. A token never becomes anything else. - /// - internal const string StagingPathPrefix = "staging"; + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - /// - /// 128 bits from a cryptographic generator, hex encoded. The token is the only thing - /// naming a staged upload, so guessing one must not be feasible. - /// - private const int TokenBytes = 16; + internal static string StagedPath(string token) => $"{StagingPathPrefix}/{token}.nupkg"; - private const int TokenLength = TokenBytes * 2; + internal static string MetadataPath(string token) => $"{StagingPathPrefix}/{token}.json"; - private readonly IStorageService _storage; - private readonly SystemTime _time; - private readonly ILogger _logger; + public async Task StageAsync(Stream package, string ownerId, CancellationToken cancellationToken = default) + { + if (package == null) throw new ArgumentNullException(nameof(package)); + + var token = CreateToken(); + var metadata = new StagedUpload + { + OwnerId = Owner(ownerId), + StagedAtUtc = _time.UtcNow, + }; + + // The metadata is written before the package because the sweep finds abandoned + // uploads through the metadata: a package whose metadata never arrived would be + // collected by nothing. + using (var json = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(metadata))) + { + await StoreAsync(MetadataPath(token), json, "application/json", cancellationToken); + } - public StoragePackageStagingService( - IStorageService storage, - SystemTime time, - ILogger logger) + try + { + await StoreAsync(StagedPath(token), package, "application/octet-stream", cancellationToken); + } + catch { - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _time = time ?? throw new ArgumentNullException(nameof(time)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + // Half a staged upload can never be confirmed, so it is removed now rather + // than left for the sweep. + await ForgetAsync(token, CancellationToken.None); + throw; } - internal static string StagedPath(string token) => $"{StagingPathPrefix}/{token}.nupkg"; + // The token itself only ever reaches Debug. It is the whole capability over a + // staged upload, and a log at Information is on by default and usually shipped + // to a store read by far more people than the uploader; the correlation id is + // enough to follow one upload through the log without handing it over. + _logger.LogDebug("Staged an upload as {Token}", token); + _logger.LogInformation("Staged an upload, correlation {Correlation}", Correlation(token)); + + return token; + } + + public async Task OpenAsync(string token, string ownerId, CancellationToken cancellationToken = default) + { + if (!IsToken(token)) return null; - internal static string MetadataPath(string token) => $"{StagingPathPrefix}/{token}.json"; + var read = await ReadMetadataAsync(token, cancellationToken); + if (read.Metadata == null) return null; - public async Task StageAsync(Stream package, string ownerId, CancellationToken cancellationToken = default) + // The real authorization: the prefix being unreachable over HTTP is a property of + // the route table, not an access check, and two users share one store. + if (!IsOwner(read.Metadata, ownerId)) { - if (package == null) throw new ArgumentNullException(nameof(package)); - - var token = CreateToken(); - var metadata = new StagedUpload - { - OwnerId = Owner(ownerId), - StagedAtUtc = _time.UtcNow, - }; - - // The metadata is written before the package because the sweep finds abandoned - // uploads through the metadata: a package whose metadata never arrived would be - // collected by nothing. - using (var json = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(metadata))) - { - await StoreAsync(MetadataPath(token), json, "application/json", cancellationToken); - } - - try - { - await StoreAsync(StagedPath(token), package, "application/octet-stream", cancellationToken); - } - catch - { - // Half a staged upload can never be confirmed, so it is removed now rather - // than left for the sweep. - await ForgetAsync(token, CancellationToken.None); - throw; - } - - // The token itself only ever reaches Debug. It is the whole capability over a - // staged upload, and a log at Information is on by default and usually shipped - // to a store read by far more people than the uploader; the correlation id is - // enough to follow one upload through the log without handing it over. - _logger.LogDebug("Staged an upload as {Token}", token); - _logger.LogInformation("Staged an upload, correlation {Correlation}", Correlation(token)); - - return token; + _logger.LogWarning( + "Refusing staged upload {Correlation}: it was staged by a different user", + Correlation(token)); + + return null; } - public async Task OpenAsync(string token, string ownerId, CancellationToken cancellationToken = default) + return await OpenOrNullAsync(StagedPath(token), cancellationToken); + } + + public async Task RemoveAsync(string token, string ownerId, CancellationToken cancellationToken = default) + { + if (!IsToken(token)) return false; + + // The same owner check makes. Removal is not a read, but + // it destroys an upload its owner may be about to confirm, so a token someone + // else learned must not be enough to discard it. + var read = await ReadMetadataAsync(token, cancellationToken); + if (read.Metadata == null || !IsOwner(read.Metadata, ownerId)) { - if (!IsToken(token)) return null; + return false; + } - var read = await ReadMetadataAsync(token, cancellationToken); - if (read.Metadata == null) return null; + await ForgetAsync(token, cancellationToken); - // The real authorization: the prefix being unreachable over HTTP is a property of - // the route table, not an access check, and two users share one store. - if (!IsOwner(read.Metadata, ownerId)) - { - _logger.LogWarning( - "Refusing staged upload {Correlation}: it was staged by a different user", - Correlation(token)); + return true; + } - return null; - } + public async Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default) + { + if (!(_storage is IListableStorageService listable)) + { + // Said out loud: silence here would mean staged uploads accumulating + // unnoticed on a store that cannot be swept. + _logger.LogWarning( + "Cannot sweep abandoned staged uploads: {Storage} cannot list what it holds", + _storage.GetType().Name); - return await OpenOrNullAsync(StagedPath(token), cancellationToken); + return 0; } - public async Task RemoveAsync(string token, string ownerId, CancellationToken cancellationToken = default) + var paths = await listable.ListAsync(StagingPathPrefix, cancellationToken); + var stored = new HashSet(paths, StringComparer.Ordinal); + + var tokens = new HashSet(StringComparer.Ordinal); + foreach (var path in paths) { - if (!IsToken(token)) return false; - - // The same owner check makes. Removal is not a read, but - // it destroys an upload its owner may be about to confirm, so a token someone - // else learned must not be enough to discard it. - var read = await ReadMetadataAsync(token, cancellationToken); - if (read.Metadata == null || !IsOwner(read.Metadata, ownerId)) - { - return false; - } + var token = TokenOrNull(path); + if (token != null) tokens.Add(token); + } - await ForgetAsync(token, cancellationToken); + var swept = 0; + foreach (var token in tokens) + { + if (!await IsCollectableAsync(token, stagedBefore, stored, cancellationToken)) continue; - return true; + await ForgetAsync(token, cancellationToken); + swept++; } - public async Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default) + if (swept > 0) { - if (!(_storage is IListableStorageService listable)) - { - // Said out loud: silence here would mean staged uploads accumulating - // unnoticed on a store that cannot be swept. - _logger.LogWarning( - "Cannot sweep abandoned staged uploads: {Storage} cannot list what it holds", - _storage.GetType().Name); + _logger.LogInformation("Swept {Count} staged uploads abandoned before {Cutoff}", swept, stagedBefore); + } - return 0; - } + return swept; + } - var paths = await listable.ListAsync(StagingPathPrefix, cancellationToken); - var stored = new HashSet(paths, StringComparer.Ordinal); + /// + /// Whether the sweep may discard an upload. An upload is collected when it is older + /// than the cutoff, when its metadata is gone - nobody can open it then, since the + /// owner it belonged to is unknowable - or when its metadata will never parse. It is + /// kept when the metadata is there but could not be read this time: a store that is + /// briefly unreachable, or a file a backup or a scanner is holding, says nothing + /// about whether the upload was abandoned, and collecting it then would discard an + /// upload staged a minute ago whose preview is still open. + /// + private async Task IsCollectableAsync( + string token, + DateTime stagedBefore, + HashSet stored, + CancellationToken cancellationToken) + { + var read = await ReadMetadataAsync(token, cancellationToken); - var tokens = new HashSet(StringComparer.Ordinal); - foreach (var path in paths) - { - var token = TokenOrNull(path); - if (token != null) tokens.Add(token); - } + switch (read.Status) + { + case StagedMetadataStatus.Readable: + return read.Metadata.StagedAtUtc < stagedBefore; - var swept = 0; - foreach (var token in tokens) - { - if (!await IsCollectableAsync(token, stagedBefore, stored, cancellationToken)) continue; + case StagedMetadataStatus.Unreadable: + return true; - await ForgetAsync(token, cancellationToken); - swept++; - } + default: + if (!stored.Contains(MetadataPath(token))) return true; - if (swept > 0) - { - _logger.LogInformation("Swept {Count} staged uploads abandoned before {Cutoff}", swept, stagedBefore); - } + _logger.LogWarning( + "Keeping staged upload {Correlation}: its metadata could not be read this time", + Correlation(token)); - return swept; + return false; } + } - /// - /// Whether the sweep may discard an upload. An upload is collected when it is older - /// than the cutoff, when its metadata is gone - nobody can open it then, since the - /// owner it belonged to is unknowable - or when its metadata will never parse. It is - /// kept when the metadata is there but could not be read this time: a store that is - /// briefly unreachable, or a file a backup or a scanner is holding, says nothing - /// about whether the upload was abandoned, and collecting it then would discard an - /// upload staged a minute ago whose preview is still open. - /// - private async Task IsCollectableAsync( - string token, - DateTime stagedBefore, - HashSet stored, - CancellationToken cancellationToken) - { - var read = await ReadMetadataAsync(token, cancellationToken); + private async Task StoreAsync(string path, Stream content, string contentType, CancellationToken cancellationToken) + { + var result = await _storage.PutAsync(path, content, contentType, cancellationToken); - switch (read.Status) - { - case StagedMetadataStatus.Readable: - return read.Metadata.StagedAtUtc < stagedBefore; + if (result == StoragePutResult.Conflict) + { + throw new InvalidOperationException($"Could not stage an upload at '{path}'; the path is already in use"); + } + } - case StagedMetadataStatus.Unreadable: - return true; + /// + /// Remove both of an upload's blobs, whoever owns it. Every caller that reaches here + /// has already decided it may. + /// + private async Task ForgetAsync(string token, CancellationToken cancellationToken) + { + await DeleteAsync(StagedPath(token), cancellationToken); + await DeleteAsync(MetadataPath(token), cancellationToken); + } - default: - if (!stored.Contains(MetadataPath(token))) return true; + private async Task ReadMetadataAsync(string token, CancellationToken cancellationToken) + { + using var stream = await OpenOrNullAsync(MetadataPath(token), cancellationToken); + if (stream == null) return new StagedMetadataRead(StagedMetadataStatus.Unavailable, null); - _logger.LogWarning( - "Keeping staged upload {Correlation}: its metadata could not be read this time", - Correlation(token)); + try + { + var metadata = await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); - return false; - } + return metadata == null + ? new StagedMetadataRead(StagedMetadataStatus.Unreadable, null) + : new StagedMetadataRead(StagedMetadataStatus.Readable, metadata); } - - private async Task StoreAsync(string path, Stream content, string contentType, CancellationToken cancellationToken) + catch (JsonException e) { - var result = await _storage.PutAsync(path, content, contentType, cancellationToken); + // Content that does not parse will not parse on the next pass either, unlike + // a file that could not be opened this time. + _logger.LogWarning(e, "Staged upload {Correlation} has unreadable metadata", Correlation(token)); - if (result == StoragePutResult.Conflict) - { - throw new InvalidOperationException($"Could not stage an upload at '{path}'; the path is already in use"); - } + return new StagedMetadataRead(StagedMetadataStatus.Unreadable, null); } + } - /// - /// Remove both of an upload's blobs, whoever owns it. Every caller that reaches here - /// has already decided it may. - /// - private async Task ForgetAsync(string token, CancellationToken cancellationToken) + private async Task OpenOrNullAsync(string path, CancellationToken cancellationToken) + { + try { - await DeleteAsync(StagedPath(token), cancellationToken); - await DeleteAsync(MetadataPath(token), cancellationToken); + // IStorageService is documented to answer a missing path with null, but no + // implementation does: the file store throws, each cloud store throws its + // own type, and the null store really does return null. An upload that + // cannot be read back is an unknown token either way. + return await _storage.GetAsync(path, cancellationToken); } - - private async Task ReadMetadataAsync(string token, CancellationToken cancellationToken) + catch (Exception e) when (!(e is OperationCanceledException)) { - using var stream = await OpenOrNullAsync(MetadataPath(token), cancellationToken); - if (stream == null) return new StagedMetadataRead(StagedMetadataStatus.Unavailable, null); - - try - { - var metadata = await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); - - return metadata == null - ? new StagedMetadataRead(StagedMetadataStatus.Unreadable, null) - : new StagedMetadataRead(StagedMetadataStatus.Readable, metadata); - } - catch (JsonException e) - { - // Content that does not parse will not parse on the next pass either, unlike - // a file that could not be opened this time. - _logger.LogWarning(e, "Staged upload {Correlation} has unreadable metadata", Correlation(token)); - - return new StagedMetadataRead(StagedMetadataStatus.Unreadable, null); - } + _logger.LogDebug(e, "Nothing staged at {Path}", path); + return null; } + } - private async Task OpenOrNullAsync(string path, CancellationToken cancellationToken) + private async Task DeleteAsync(string path, CancellationToken cancellationToken) + { + try { - try - { - // IStorageService is documented to answer a missing path with null, but no - // implementation does: the file store throws, each cloud store throws its - // own type, and the null store really does return null. An upload that - // cannot be read back is an unknown token either way. - return await _storage.GetAsync(path, cancellationToken); - } - catch (Exception e) when (!(e is OperationCanceledException)) - { - _logger.LogDebug(e, "Nothing staged at {Path}", path); - return null; - } + await _storage.DeleteAsync(path, cancellationToken); } - - private async Task DeleteAsync(string path, CancellationToken cancellationToken) + catch (Exception e) when (!(e is OperationCanceledException)) { - try - { - await _storage.DeleteAsync(path, cancellationToken); - } - catch (Exception e) when (!(e is OperationCanceledException)) - { - // Left for the next sweep rather than failing a confirmed upload. - _logger.LogWarning(e, "Could not remove staged content under {Prefix}", StagingPathPrefix); - } + // Left for the next sweep rather than failing a confirmed upload. + _logger.LogWarning(e, "Could not remove staged content under {Prefix}", StagingPathPrefix); } + } - private static string CreateToken() - => Convert.ToHexString(RandomNumberGenerator.GetBytes(TokenBytes)).ToLowerInvariant(); + private static string CreateToken() + => Convert.ToHexString(RandomNumberGenerator.GetBytes(TokenBytes)).ToLowerInvariant(); - /// - /// A short, non-reversible name for an upload, so a log can follow one upload without - /// carrying the token that would let its reader act on it. - /// - private static string Correlation(string token) - => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)), 0, 4).ToLowerInvariant(); + /// + /// A short, non-reversible name for an upload, so a log can follow one upload without + /// carrying the token that would let its reader act on it. + /// + private static string Correlation(string token) + => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)), 0, 4).ToLowerInvariant(); - private static bool IsOwner(StagedUpload metadata, string ownerId) - => string.Equals(metadata.OwnerId, Owner(ownerId), StringComparison.Ordinal); + private static bool IsOwner(StagedUpload metadata, string ownerId) + => string.Equals(metadata.OwnerId, Owner(ownerId), StringComparison.Ordinal); - /// - /// A token becomes a storage path, so anything that is not one is refused before it - /// gets there - a caller-supplied "../packages/..." must never be opened or deleted. - /// - private static bool IsToken(string token) + /// + /// A token becomes a storage path, so anything that is not one is refused before it + /// gets there - a caller-supplied "../packages/..." must never be opened or deleted. + /// + private static bool IsToken(string token) + { + if (token == null || token.Length != TokenLength) return false; + + foreach (var character in token) { - if (token == null || token.Length != TokenLength) return false; + var isHex = (character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'); + if (!isHex) return false; + } - foreach (var character in token) - { - var isHex = (character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'); - if (!isHex) return false; - } + return true; + } - return true; - } + /// + /// The token a staged path belongs to, or null if the path is not one of ours. + /// + private static string TokenOrNull(string path) + { + if (path == null) return null; + if (!path.StartsWith(StagingPathPrefix + "/", StringComparison.Ordinal)) return null; - /// - /// The token a staged path belongs to, or null if the path is not one of ours. - /// - private static string TokenOrNull(string path) - { - if (path == null) return null; - if (!path.StartsWith(StagingPathPrefix + "/", StringComparison.Ordinal)) return null; + var extension = Path.GetExtension(path); + if (extension != ".json" && extension != ".nupkg") return null; - var extension = Path.GetExtension(path); - if (extension != ".json" && extension != ".nupkg") return null; + var token = Path.GetFileNameWithoutExtension(path); - var token = Path.GetFileNameWithoutExtension(path); + return IsToken(token) ? token : null; + } - return IsToken(token) ? token : null; - } + /// + /// With accounts disabled there is no user to own an upload, so every upload shares + /// the one empty owner - the same identity the API key path has there. + /// + private static string Owner(string ownerId) => ownerId ?? string.Empty; + + /// + /// Why a metadata read did not produce metadata. "Not there" and "not readable right + /// now" are different facts, and the sweep must not treat the second as the first. + /// + private enum StagedMetadataStatus + { + Readable, /// - /// With accounts disabled there is no user to own an upload, so every upload shares - /// the one empty owner - the same identity the API key path has there. + /// The metadata could not be opened. It may be absent, or the store may be + /// unreachable or the file held open by something else. /// - private static string Owner(string ownerId) => ownerId ?? string.Empty; + Unavailable, /// - /// Why a metadata read did not produce metadata. "Not there" and "not readable right - /// now" are different facts, and the sweep must not treat the second as the first. + /// The metadata was read and is not metadata, so it will never become readable. /// - private enum StagedMetadataStatus - { - Readable, - - /// - /// The metadata could not be opened. It may be absent, or the store may be - /// unreachable or the file held open by something else. - /// - Unavailable, - - /// - /// The metadata was read and is not metadata, so it will never become readable. - /// - Unreadable, - } + Unreadable, + } - private readonly struct StagedMetadataRead + private readonly struct StagedMetadataRead + { + public StagedMetadataRead(StagedMetadataStatus status, StagedUpload metadata) { - public StagedMetadataRead(StagedMetadataStatus status, StagedUpload metadata) - { - Status = status; - Metadata = metadata; - } + Status = status; + Metadata = metadata; + } - public StagedMetadataStatus Status { get; } + public StagedMetadataStatus Status { get; } - public StagedUpload Metadata { get; } - } + public StagedUpload Metadata { get; } + } - internal class StagedUpload - { - public string OwnerId { get; set; } + internal class StagedUpload + { + public string OwnerId { get; set; } - public DateTime StagedAtUtc { get; set; } - } + public DateTime StagedAtUtc { get; set; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Statistics/StatisticsService.cs b/src/BaGet.Core/Statistics/StatisticsService.cs index 59117d8a8..b626e1497 100644 --- a/src/BaGet.Core/Statistics/StatisticsService.cs +++ b/src/BaGet.Core/Statistics/StatisticsService.cs @@ -5,94 +5,93 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; -namespace BaGet.Core +namespace BaGet.Core; + +public class FeedStatistics { - public class FeedStatistics - { - public int PackageIds { get; set; } + public int PackageIds { get; set; } - public int PackageVersions { get; set; } + public int PackageVersions { get; set; } - public long Downloads { get; set; } + public long Downloads { get; set; } - /// - /// The most downloaded package IDs, all versions together. - /// - public IReadOnlyList TopPackages { get; set; } + /// + /// The most downloaded package IDs, all versions together. + /// + public IReadOnlyList TopPackages { get; set; } - /// - /// The most recently published versions. - /// - public IReadOnlyList RecentVersions { get; set; } - } + /// + /// The most recently published versions. + /// + public IReadOnlyList RecentVersions { get; set; } +} - public class PackageDownloads - { - public string Id { get; set; } +public class PackageDownloads +{ + public string Id { get; set; } - /// - /// Null when the downloads are a whole package ID's. - /// - public string Version { get; set; } + /// + /// Null when the downloads are a whole package ID's. + /// + public string Version { get; set; } - public long Downloads { get; set; } + public long Downloads { get; set; } - public DateTime? Published { get; set; } - } + public DateTime? Published { get; set; } +} - /// - /// Feed-wide download statistics, from the per-version counts the database keeps. - /// There is no per-day history: a count only ever goes up. - /// - public class StatisticsService - { - private const int ListSize = 10; +/// +/// Feed-wide download statistics, from the per-version counts the database keeps. +/// There is no per-day history: a count only ever goes up. +/// +public class StatisticsService +{ + private const int ListSize = 10; - private readonly IContext _context; + private readonly IContext _context; - public StatisticsService(IContext context) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - } + public StatisticsService(IContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } - /// - /// False when the database cannot be queried for aggregates, such as Azure Table storage. - /// - public bool IsSupported => !(_context is NullContext); + /// + /// False when the database cannot be queried for aggregates, such as Azure Table storage. + /// + public bool IsSupported => !(_context is NullContext); - public async Task GetAsync(CancellationToken cancellationToken) - { - var listed = _context.Packages.AsNoTracking().Where(p => p.Listed); - - var top = await listed - .GroupBy(p => p.Id) - .Select(g => new PackageDownloads { Id = g.Key, Downloads = g.Sum(p => p.Downloads) }) - .OrderByDescending(p => p.Downloads) - .ThenBy(p => p.Id) - .Take(ListSize) - .ToListAsync(cancellationToken); - - var recent = await listed - .OrderByDescending(p => p.Published) - .ThenByDescending(p => p.Key) - .Take(ListSize) - .Select(p => new PackageDownloads - { - Id = p.Id, - Version = p.OriginalVersionString ?? p.NormalizedVersionString, - Downloads = p.Downloads, - Published = p.Published, - }) - .ToListAsync(cancellationToken); - - return new FeedStatistics + public async Task GetAsync(CancellationToken cancellationToken) + { + var listed = _context.Packages.AsNoTracking().Where(p => p.Listed); + + var top = await listed + .GroupBy(p => p.Id) + .Select(g => new PackageDownloads { Id = g.Key, Downloads = g.Sum(p => p.Downloads) }) + .OrderByDescending(p => p.Downloads) + .ThenBy(p => p.Id) + .Take(ListSize) + .ToListAsync(cancellationToken); + + var recent = await listed + .OrderByDescending(p => p.Published) + .ThenByDescending(p => p.Key) + .Take(ListSize) + .Select(p => new PackageDownloads { - PackageIds = await listed.Select(p => p.Id).Distinct().CountAsync(cancellationToken), - PackageVersions = await listed.CountAsync(cancellationToken), - Downloads = await listed.SumAsync(p => p.Downloads, cancellationToken), - TopPackages = top, - RecentVersions = recent, - }; - } + Id = p.Id, + Version = p.OriginalVersionString ?? p.NormalizedVersionString, + Downloads = p.Downloads, + Published = p.Published, + }) + .ToListAsync(cancellationToken); + + return new FeedStatistics + { + PackageIds = await listed.Select(p => p.Id).Distinct().CountAsync(cancellationToken), + PackageVersions = await listed.CountAsync(cancellationToken), + Downloads = await listed.SumAsync(p => p.Downloads, cancellationToken), + TopPackages = top, + RecentVersions = recent, + }; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/FileStorageService.cs b/src/BaGet.Core/Storage/FileStorageService.cs index fae809def..752d6f545 100644 --- a/src/BaGet.Core/Storage/FileStorageService.cs +++ b/src/BaGet.Core/Storage/FileStorageService.cs @@ -6,138 +6,137 @@ using System.Threading.Tasks; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Stores content on disk. +/// +public class FileStorageService : IStorageService, IListableStorageService { - /// - /// Stores content on disk. - /// - public class FileStorageService : IStorageService, IListableStorageService - { - // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 - private const int DefaultCopyBufferSize = 81920; + // See: https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Stream.cs#L35 + private const int DefaultCopyBufferSize = 81920; - private readonly string _storePath; + private readonly string _storePath; - public FileStorageService(IOptionsSnapshot options) - { - if (options == null) throw new ArgumentNullException(nameof(options)); + public FileStorageService(IOptionsSnapshot options) + { + if (options == null) throw new ArgumentNullException(nameof(options)); - // Resolve relative path components ('.'/'..') and ensure there is a trailing slash. - _storePath = Path.GetFullPath(options.Value.Path); - if (!_storePath.EndsWith(Path.DirectorySeparatorChar.ToString())) - _storePath += Path.DirectorySeparatorChar; - } + // Resolve relative path components ('.'/'..') and ensure there is a trailing slash. + _storePath = Path.GetFullPath(options.Value.Path); + if (!_storePath.EndsWith(Path.DirectorySeparatorChar.ToString())) + _storePath += Path.DirectorySeparatorChar; + } - public Task GetAsync(string path, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + public Task GetAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - path = GetFullPath(path); - var content = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); + path = GetFullPath(path); + var content = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - return Task.FromResult(content); - } + return Task.FromResult(content); + } - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - var result = new Uri(GetFullPath(path)); + var result = new Uri(GetFullPath(path)); - return Task.FromResult(result); - } + return Task.FromResult(result); + } - public async Task PutAsync( - string path, - Stream content, - string contentType, - CancellationToken cancellationToken = default) - { - if (content == null) throw new ArgumentNullException(nameof(content)); - if (string.IsNullOrEmpty(contentType)) throw new ArgumentException("Content type is required", nameof(contentType)); + public async Task PutAsync( + string path, + Stream content, + string contentType, + CancellationToken cancellationToken = default) + { + if (content == null) throw new ArgumentNullException(nameof(content)); + if (string.IsNullOrEmpty(contentType)) throw new ArgumentException("Content type is required", nameof(contentType)); - cancellationToken.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); - path = GetFullPath(path); + path = GetFullPath(path); - // Ensure that the path exists. - Directory.CreateDirectory(Path.GetDirectoryName(path)); + // Ensure that the path exists. + Directory.CreateDirectory(Path.GetDirectoryName(path)); - try + try + { + using (var fileStream = File.Open(path, FileMode.CreateNew)) { - using (var fileStream = File.Open(path, FileMode.CreateNew)) - { - await content.CopyToAsync(fileStream, DefaultCopyBufferSize, cancellationToken); - return StoragePutResult.Success; - } + await content.CopyToAsync(fileStream, DefaultCopyBufferSize, cancellationToken); + return StoragePutResult.Success; } - catch (IOException) when (File.Exists(path)) + } + catch (IOException) when (File.Exists(path)) + { + using (var targetStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { - using (var targetStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) - { - content.Position = 0; - return content.Matches(targetStream) - ? StoragePutResult.AlreadyExists - : StoragePutResult.Conflict; - } + content.Position = 0; + return content.Matches(targetStream) + ? StoragePutResult.AlreadyExists + : StoragePutResult.Conflict; } } + } + + public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + // GetFullPath keeps the prefix inside the store, exactly as for a read or write. + var fullPath = GetFullPath(pathPrefix); - public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + if (!Directory.Exists(fullPath)) { - cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult>(Array.Empty()); + } - // GetFullPath keeps the prefix inside the store, exactly as for a read or write. - var fullPath = GetFullPath(pathPrefix); + var paths = Directory + .EnumerateFiles(fullPath, "*", SearchOption.AllDirectories) + .Select(path => path + .Substring(_storePath.Length) + .Replace(Path.DirectorySeparatorChar, '/') + .Replace(Path.AltDirectorySeparatorChar, '/')) + .ToList(); - if (!Directory.Exists(fullPath)) - { - return Task.FromResult>(Array.Empty()); - } + return Task.FromResult>(paths); + } - var paths = Directory - .EnumerateFiles(fullPath, "*", SearchOption.AllDirectories) - .Select(path => path - .Substring(_storePath.Length) - .Replace(Path.DirectorySeparatorChar, '/') - .Replace(Path.AltDirectorySeparatorChar, '/')) - .ToList(); + public Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); - return Task.FromResult>(paths); + try + { + File.Delete(GetFullPath(path)); } - - public Task DeleteAsync(string path, CancellationToken cancellationToken = default) + catch (DirectoryNotFoundException) { - cancellationToken.ThrowIfCancellationRequested(); - - try - { - File.Delete(GetFullPath(path)); - } - catch (DirectoryNotFoundException) - { - } - - return Task.CompletedTask; } - private string GetFullPath(string path) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException("Path is required", nameof(path)); - } + return Task.CompletedTask; + } - var fullPath = Path.GetFullPath(Path.Combine(_storePath, path)); + private string GetFullPath(string path) + { + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("Path is required", nameof(path)); + } - // Verify path is under the _storePath. - if (!fullPath.StartsWith(_storePath, StringComparison.Ordinal) || - fullPath.Length == _storePath.Length) - { - throw new ArgumentException("Path resolves outside store path", nameof(path)); - } + var fullPath = Path.GetFullPath(Path.Combine(_storePath, path)); - return fullPath; + // Verify path is under the _storePath. + if (!fullPath.StartsWith(_storePath, StringComparison.Ordinal) || + fullPath.Length == _storePath.Length) + { + throw new ArgumentException("Path resolves outside store path", nameof(path)); } + + return fullPath; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/IListableStorageService.cs b/src/BaGet.Core/Storage/IListableStorageService.cs index 06afd289b..be44553e0 100644 --- a/src/BaGet.Core/Storage/IListableStorageService.cs +++ b/src/BaGet.Core/Storage/IListableStorageService.cs @@ -2,29 +2,28 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// An optional capability of an : list what it holds under a +/// path prefix. Content that is only ever read back through the path that stored it does +/// not need this; collecting content whose paths nobody remembers - abandoned staged +/// uploads, for one - does. +/// +/// +/// A store that does not implement this cannot be swept, so a caller must degrade +/// rather than cast and assume. +/// +public interface IListableStorageService { - /// - /// An optional capability of an : list what it holds under a - /// path prefix. Content that is only ever read back through the path that stored it does - /// not need this; collecting content whose paths nobody remembers - abandoned staged - /// uploads, for one - does. - /// - /// - /// A store that does not implement this cannot be swept, so a caller must degrade - /// rather than cast and assume. - /// - public interface IListableStorageService - { - /// - /// The prefix to list, as a path of one or more segments ("staging"). - /// - /// A token to cancel the task. - /// - /// The path of every item under the prefix, relative to the store's root and - /// separated with "/", so each can be passed straight back to - /// . Empty if the prefix holds nothing. - /// - Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default); - } -} + /// + /// The prefix to list, as a path of one or more segments ("staging"). + /// + /// A token to cancel the task. + /// + /// The path of every item under the prefix, relative to the store's root and + /// separated with "/", so each can be passed straight back to + /// . Empty if the prefix holds nothing. + /// + Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/IPackageStorageService.cs b/src/BaGet.Core/Storage/IPackageStorageService.cs index 1542d9058..c8e5b5fc8 100644 --- a/src/BaGet.Core/Storage/IPackageStorageService.cs +++ b/src/BaGet.Core/Storage/IPackageStorageService.cs @@ -3,87 +3,86 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Stores packages' content. Packages' state are stored by the +/// . +/// +public interface IPackageStorageService { /// - /// Stores packages' content. Packages' state are stored by the - /// . + /// Persist a package's content to storage. This operation MUST NOT store the content if a + /// package with the same id/version but different content has already been stored. /// - public interface IPackageStorageService - { - /// - /// Persist a package's content to storage. This operation MUST NOT store the content if a - /// package with the same id/version but different content has already been stored. - /// - /// The package's metadata. - /// The package's nupkg stream. - /// The package's nuspec stream. - /// The package's readme stream, or null if none. - /// The package's icon stream, or null if none. - /// - /// The result of the attempted save operation. - Task SavePackageContentAsync( - Package package, - Stream packageStream, - Stream nuspecStream, - Stream readmeStream, - Stream iconStream, - CancellationToken cancellationToken); + /// The package's metadata. + /// The package's nupkg stream. + /// The package's nuspec stream. + /// The package's readme stream, or null if none. + /// The package's icon stream, or null if none. + /// + /// The result of the attempted save operation. + Task SavePackageContentAsync( + Package package, + Stream packageStream, + Stream nuspecStream, + Stream readmeStream, + Stream iconStream, + CancellationToken cancellationToken); - /// - /// Retrieve a package's nupkg stream. - /// - /// The package's id. - /// The package's version. - /// - /// The package's nupkg stream. - Task GetPackageStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Retrieve a package's nupkg stream. + /// + /// The package's id. + /// The package's version. + /// + /// The package's nupkg stream. + Task GetPackageStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Retrieve a package's nuspec stream. - /// - /// The package's id. - /// The package's version. - /// - /// The package's nuspec stream. - Task GetNuspecStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Retrieve a package's nuspec stream. + /// + /// The package's id. + /// The package's version. + /// + /// The package's nuspec stream. + Task GetNuspecStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Retrieve a package's readme stream. - /// - /// The package's id. - /// The package's version. - /// - /// The package's readme stream. - Task GetReadmeStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + /// + /// Retrieve a package's readme stream. + /// + /// The package's id. + /// The package's version. + /// + /// The package's readme stream. + Task GetReadmeStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - Task GetIconStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); + Task GetIconStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - /// - /// Remove a package's content from storage. This operation SHOULD succeed - /// even if the package does not exist. - /// - /// The package's id. - /// The package's version. - /// - /// - Task DeleteAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - } + /// + /// Remove a package's content from storage. This operation SHOULD succeed + /// even if the package does not exist. + /// + /// The package's id. + /// The package's version. + /// + /// + Task DeleteAsync(string id, NuGetVersion version, CancellationToken cancellationToken); +} +/// +/// The result of a operation. +/// +public enum PackageSaveResult +{ /// - /// The result of a operation. + /// Content for this package's id/version has already been stored and does not + /// match the content that was submitted. Nothing further was stored. /// - public enum PackageSaveResult - { - /// - /// Content for this package's id/version has already been stored and does not - /// match the content that was submitted. Nothing further was stored. - /// - Conflict, + Conflict, - /// - /// The package's content was stored, or the exact same content had already been stored. - /// - Success, - } -} + /// + /// The package's content was stored, or the exact same content had already been stored. + /// + Success, +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/IStorageService.cs b/src/BaGet.Core/Storage/IStorageService.cs index 50e122f1a..b322273fc 100644 --- a/src/BaGet.Core/Storage/IStorageService.cs +++ b/src/BaGet.Core/Storage/IStorageService.cs @@ -3,82 +3,81 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A low-level storage abstraction. +/// +/// +/// This is used to store: +/// +/// * Packages, through +/// * Symbols, through +/// +/// This storage abstraction has implementations for disk, +/// Azure Blob Storage, Amazon Web Services S3, and Google Cloud Storage. +/// +public interface IStorageService { /// - /// A low-level storage abstraction. + /// Get content from storage. /// - /// - /// This is used to store: - /// - /// * Packages, through - /// * Symbols, through - /// - /// This storage abstraction has implementations for disk, - /// Azure Blob Storage, Amazon Web Services S3, and Google Cloud Storage. - /// - public interface IStorageService - { - /// - /// Get content from storage. - /// - /// The content's path. - /// A token to cancel the task. - /// The path's content or null if the content does not exist. - Task GetAsync(string path, CancellationToken cancellationToken = default); + /// The content's path. + /// A token to cancel the task. + /// The path's content or null if the content does not exist. + Task GetAsync(string path, CancellationToken cancellationToken = default); - /// - /// Get a URI that can be used to download the content. - /// - /// The content's path. - /// A token to cancel the task. - /// - /// The content's URI. This may be a local file. Returns null if the content - /// does not exist or if a URI could not be created. - /// - Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default); + /// + /// Get a URI that can be used to download the content. + /// + /// The content's path. + /// A token to cancel the task. + /// + /// The content's URI. This may be a local file. Returns null if the content + /// does not exist or if a URI could not be created. + /// + Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default); - /// - /// Store content into storage. - /// - /// The path at which to store the content. - /// The content to store at the given path. - /// The type of content that is being stored. - /// A token to cancel the task. - /// The result of the put operation. - Task PutAsync( - string path, - Stream content, - string contentType, - CancellationToken cancellationToken = default); + /// + /// Store content into storage. + /// + /// The path at which to store the content. + /// The content to store at the given path. + /// The type of content that is being stored. + /// A token to cancel the task. + /// The result of the put operation. + Task PutAsync( + string path, + Stream content, + string contentType, + CancellationToken cancellationToken = default); - /// - /// Remove content from storage. - /// - /// The path to the content to delete. - /// A token to cancel the task. - /// A task that completes when the content has been deleted. - Task DeleteAsync(string path, CancellationToken cancellationToken = default); - } + /// + /// Remove content from storage. + /// + /// The path to the content to delete. + /// A token to cancel the task. + /// A task that completes when the content has been deleted. + Task DeleteAsync(string path, CancellationToken cancellationToken = default); +} +/// +/// The result of a operation. +/// +public enum StoragePutResult +{ /// - /// The result of a operation. + /// The given path is already used to store different content. /// - public enum StoragePutResult - { - /// - /// The given path is already used to store different content. - /// - Conflict, + Conflict, - /// - /// This content is already stored at the given path. - /// - AlreadyExists, + /// + /// This content is already stored at the given path. + /// + AlreadyExists, - /// - /// The content was sucessfully stored. - /// - Success, - } -} + /// + /// The content was sucessfully stored. + /// + Success, +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/ISymbolStorageService.cs b/src/BaGet.Core/Storage/ISymbolStorageService.cs index f8681ab6a..d3056ff07 100644 --- a/src/BaGet.Core/Storage/ISymbolStorageService.cs +++ b/src/BaGet.Core/Storage/ISymbolStorageService.cs @@ -2,34 +2,33 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Stores the content of symbols, also known as PDBs. +/// +public interface ISymbolStorageService { /// - /// Stores the content of symbols, also known as PDBs. + /// Persist a portable PDB's content to storage. This operation MUST fail if a PDB + /// with the same key but different content has already been stored. /// - public interface ISymbolStorageService - { - /// - /// Persist a portable PDB's content to storage. This operation MUST fail if a PDB - /// with the same key but different content has already been stored. - /// - /// The portable PDB's file name. - /// The portable PDB's Signature GUID followed by its age. - /// The PDB's content stream. - /// - /// - Task SavePortablePdbContentAsync( - string file, - string key, - Stream pdbStream, - CancellationToken cancellationToken); + /// The portable PDB's file name. + /// The portable PDB's Signature GUID followed by its age. + /// The PDB's content stream. + /// + /// + Task SavePortablePdbContentAsync( + string file, + string key, + Stream pdbStream, + CancellationToken cancellationToken); - /// - /// Retrieve a portable PDB's content stream. - /// - /// The portable PDB's file name. - /// The portable PDB's Signature GUID followed by its age. - /// The portable PDB's stream, or null if it does not exist. - Task GetPortablePdbContentStreamOrNullAsync(string file, string key); - } -} + /// + /// Retrieve a portable PDB's content stream. + /// + /// The portable PDB's file name. + /// The portable PDB's Signature GUID followed by its age. + /// The portable PDB's stream, or null if it does not exist. + Task GetPortablePdbContentStreamOrNullAsync(string file, string key); +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/NullStorageService.cs b/src/BaGet.Core/Storage/NullStorageService.cs index 1c4c86f58..02a286fd4 100644 --- a/src/BaGet.Core/Storage/NullStorageService.cs +++ b/src/BaGet.Core/Storage/NullStorageService.cs @@ -4,43 +4,42 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A minimal storage implementation, used for advanced scenarios. +/// +public class NullStorageService : IStorageService, IListableStorageService { + public Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + return Task.CompletedTask; + } + /// - /// A minimal storage implementation, used for advanced scenarios. + /// A store that holds nothing lists nothing, so a sweep over it has nothing to do. /// - public class NullStorageService : IStorageService, IListableStorageService + public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) { - public Task DeleteAsync(string path, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } - - /// - /// A store that holds nothing lists nothing, so a sweep over it has nothing to do. - /// - public Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) - { - return Task.FromResult>(Array.Empty()); - } + return Task.FromResult>(Array.Empty()); + } - public Task GetAsync(string path, CancellationToken cancellationToken = default) - { - return Task.FromResult(null); - } + public Task GetAsync(string path, CancellationToken cancellationToken = default) + { + return Task.FromResult(null); + } - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) - { - return Task.FromResult(null); - } + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + return Task.FromResult(null); + } - public Task PutAsync( - string path, - Stream content, - string contentType, - CancellationToken cancellationToken = default) - { - return Task.FromResult(StoragePutResult.Success); - } + public Task PutAsync( + string path, + Stream content, + string contentType, + CancellationToken cancellationToken = default) + { + return Task.FromResult(StoragePutResult.Success); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/PackageStorageService.cs b/src/BaGet.Core/Storage/PackageStorageService.cs index c5bd16cae..5f9eb4f3b 100644 --- a/src/BaGet.Core/Storage/PackageStorageService.cs +++ b/src/BaGet.Core/Storage/PackageStorageService.cs @@ -5,237 +5,236 @@ using Microsoft.Extensions.Logging; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +public class PackageStorageService : IPackageStorageService { - public class PackageStorageService : IPackageStorageService - { - private const string PackagesPathPrefix = "packages"; + private const string PackagesPathPrefix = "packages"; + + // See: https://github.com/NuGet/NuGetGallery/blob/73a5c54629056b25b3a59960373e8fef88abff36/src/NuGetGallery.Core/CoreConstants.cs#L19 + private const string PackageContentType = "binary/octet-stream"; + private const string NuspecContentType = "text/plain"; + private const string ReadmeContentType = "text/markdown"; + private const string IconContentType = "image/xyz"; - // See: https://github.com/NuGet/NuGetGallery/blob/73a5c54629056b25b3a59960373e8fef88abff36/src/NuGetGallery.Core/CoreConstants.cs#L19 - private const string PackageContentType = "binary/octet-stream"; - private const string NuspecContentType = "text/plain"; - private const string ReadmeContentType = "text/markdown"; - private const string IconContentType = "image/xyz"; + private readonly IStorageService _storage; + private readonly ILogger _logger; - private readonly IStorageService _storage; - private readonly ILogger _logger; + public PackageStorageService( + IStorageService storage, + ILogger logger) + { + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public PackageStorageService( - IStorageService storage, - ILogger logger) + public async Task SavePackageContentAsync( + Package package, + Stream packageStream, + Stream nuspecStream, + Stream readmeStream, + Stream iconStream, + CancellationToken cancellationToken = default) + { + package = package ?? throw new ArgumentNullException(nameof(package)); + packageStream = packageStream ?? throw new ArgumentNullException(nameof(packageStream)); + nuspecStream = nuspecStream ?? throw new ArgumentNullException(nameof(nuspecStream)); + + var lowercasedId = package.Id.ToLowerInvariant(); + var lowercasedNormalizedVersion = package.NormalizedVersionString.ToLowerInvariant(); + + var packagePath = PackagePath(lowercasedId, lowercasedNormalizedVersion); + var nuspecPath = NuspecPath(lowercasedId, lowercasedNormalizedVersion); + var readmePath = ReadmePath(lowercasedId, lowercasedNormalizedVersion); + var iconPath = IconPath(lowercasedId, lowercasedNormalizedVersion); + + _logger.LogInformation( + "Storing package {PackageId} {PackageVersion} at {Path}...", + lowercasedId, + lowercasedNormalizedVersion, + packagePath); + + // Store the package. + var result = await _storage.PutAsync(packagePath, packageStream, PackageContentType, cancellationToken); + if (result == StoragePutResult.Conflict) { - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _logger.LogInformation( + "Could not store package {PackageId} {PackageVersion} at {Path} due to conflict", + lowercasedId, + lowercasedNormalizedVersion, + packagePath); + + return PackageSaveResult.Conflict; } - public async Task SavePackageContentAsync( - Package package, - Stream packageStream, - Stream nuspecStream, - Stream readmeStream, - Stream iconStream, - CancellationToken cancellationToken = default) - { - package = package ?? throw new ArgumentNullException(nameof(package)); - packageStream = packageStream ?? throw new ArgumentNullException(nameof(packageStream)); - nuspecStream = nuspecStream ?? throw new ArgumentNullException(nameof(nuspecStream)); + // Store the package's nuspec. + _logger.LogInformation( + "Storing package {PackageId} {PackageVersion} nuspec at {Path}...", + lowercasedId, + lowercasedNormalizedVersion, + nuspecPath); - var lowercasedId = package.Id.ToLowerInvariant(); - var lowercasedNormalizedVersion = package.NormalizedVersionString.ToLowerInvariant(); + result = await _storage.PutAsync(nuspecPath, nuspecStream, NuspecContentType, cancellationToken); + if (result == StoragePutResult.Conflict) + { + _logger.LogInformation( + "Could not store package {PackageId} {PackageVersion} nuspec at {Path} due to conflict", + lowercasedId, + lowercasedNormalizedVersion, + nuspecPath); - var packagePath = PackagePath(lowercasedId, lowercasedNormalizedVersion); - var nuspecPath = NuspecPath(lowercasedId, lowercasedNormalizedVersion); - var readmePath = ReadmePath(lowercasedId, lowercasedNormalizedVersion); - var iconPath = IconPath(lowercasedId, lowercasedNormalizedVersion); + return PackageSaveResult.Conflict; + } + // Store the package's readme, if one exists. + if (readmeStream != null) + { _logger.LogInformation( - "Storing package {PackageId} {PackageVersion} at {Path}...", + "Storing package {PackageId} {PackageVersion} readme at {Path}...", lowercasedId, lowercasedNormalizedVersion, - packagePath); + readmePath); - // Store the package. - var result = await _storage.PutAsync(packagePath, packageStream, PackageContentType, cancellationToken); + result = await _storage.PutAsync(readmePath, readmeStream, ReadmeContentType, cancellationToken); if (result == StoragePutResult.Conflict) { _logger.LogInformation( - "Could not store package {PackageId} {PackageVersion} at {Path} due to conflict", + "Could not store package {PackageId} {PackageVersion} readme at {Path} due to conflict", lowercasedId, lowercasedNormalizedVersion, - packagePath); + readmePath); return PackageSaveResult.Conflict; } + } - // Store the package's nuspec. + // Store the package's icon, if one exists. + if (iconStream != null) + { _logger.LogInformation( - "Storing package {PackageId} {PackageVersion} nuspec at {Path}...", + "Storing package {PackageId} {PackageVersion} icon at {Path}...", lowercasedId, lowercasedNormalizedVersion, - nuspecPath); + iconPath); - result = await _storage.PutAsync(nuspecPath, nuspecStream, NuspecContentType, cancellationToken); + result = await _storage.PutAsync(iconPath, iconStream, IconContentType, cancellationToken); if (result == StoragePutResult.Conflict) { _logger.LogInformation( - "Could not store package {PackageId} {PackageVersion} nuspec at {Path} due to conflict", + "Could not store package {PackageId} {PackageVersion} icon at {Path} due to conflict", lowercasedId, lowercasedNormalizedVersion, - nuspecPath); + iconPath); return PackageSaveResult.Conflict; } + } - // Store the package's readme, if one exists. - if (readmeStream != null) - { - _logger.LogInformation( - "Storing package {PackageId} {PackageVersion} readme at {Path}...", - lowercasedId, - lowercasedNormalizedVersion, - readmePath); - - result = await _storage.PutAsync(readmePath, readmeStream, ReadmeContentType, cancellationToken); - if (result == StoragePutResult.Conflict) - { - _logger.LogInformation( - "Could not store package {PackageId} {PackageVersion} readme at {Path} due to conflict", - lowercasedId, - lowercasedNormalizedVersion, - readmePath); - - return PackageSaveResult.Conflict; - } - } + _logger.LogInformation( + "Finished storing package {PackageId} {PackageVersion}", + lowercasedId, + lowercasedNormalizedVersion); - // Store the package's icon, if one exists. - if (iconStream != null) - { - _logger.LogInformation( - "Storing package {PackageId} {PackageVersion} icon at {Path}...", - lowercasedId, - lowercasedNormalizedVersion, - iconPath); - - result = await _storage.PutAsync(iconPath, iconStream, IconContentType, cancellationToken); - if (result == StoragePutResult.Conflict) - { - _logger.LogInformation( - "Could not store package {PackageId} {PackageVersion} icon at {Path} due to conflict", - lowercasedId, - lowercasedNormalizedVersion, - iconPath); - - return PackageSaveResult.Conflict; - } - } + return PackageSaveResult.Success; + } - _logger.LogInformation( - "Finished storing package {PackageId} {PackageVersion}", - lowercasedId, - lowercasedNormalizedVersion); + public async Task GetPackageStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await GetStreamAsync(id, version, PackagePath, cancellationToken); + } - return PackageSaveResult.Success; - } + public async Task GetNuspecStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await GetStreamAsync(id, version, NuspecPath, cancellationToken); + } - public async Task GetPackageStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await GetStreamAsync(id, version, PackagePath, cancellationToken); - } + public async Task GetReadmeStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await GetStreamAsync(id, version, ReadmePath, cancellationToken); + } - public async Task GetNuspecStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await GetStreamAsync(id, version, NuspecPath, cancellationToken); - } + public async Task GetIconStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + return await GetStreamAsync(id, version, IconPath, cancellationToken); + } - public async Task GetReadmeStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await GetStreamAsync(id, version, ReadmePath, cancellationToken); - } + public async Task DeleteAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + { + var lowercasedId = id.ToLowerInvariant(); + var lowercasedNormalizedVersion = version.ToNormalizedString().ToLowerInvariant(); + + var packagePath = PackagePath(lowercasedId, lowercasedNormalizedVersion); + var nuspecPath = NuspecPath(lowercasedId, lowercasedNormalizedVersion); + var readmePath = ReadmePath(lowercasedId, lowercasedNormalizedVersion); + var iconPath = IconPath(lowercasedId, lowercasedNormalizedVersion); + + await _storage.DeleteAsync(packagePath, cancellationToken); + await _storage.DeleteAsync(nuspecPath, cancellationToken); + await _storage.DeleteAsync(readmePath, cancellationToken); + await _storage.DeleteAsync(iconPath, cancellationToken); + } - public async Task GetIconStreamAsync(string id, NuGetVersion version, CancellationToken cancellationToken) - { - return await GetStreamAsync(id, version, IconPath, cancellationToken); - } + private async Task GetStreamAsync( + string id, + NuGetVersion version, + Func pathFunc, + CancellationToken cancellationToken) + { + var lowercasedId = id.ToLowerInvariant(); + var lowercasedNormalizedVersion = version.ToNormalizedString().ToLowerInvariant(); + var path = pathFunc(lowercasedId, lowercasedNormalizedVersion); - public async Task DeleteAsync(string id, NuGetVersion version, CancellationToken cancellationToken) + try { - var lowercasedId = id.ToLowerInvariant(); - var lowercasedNormalizedVersion = version.ToNormalizedString().ToLowerInvariant(); - - var packagePath = PackagePath(lowercasedId, lowercasedNormalizedVersion); - var nuspecPath = NuspecPath(lowercasedId, lowercasedNormalizedVersion); - var readmePath = ReadmePath(lowercasedId, lowercasedNormalizedVersion); - var iconPath = IconPath(lowercasedId, lowercasedNormalizedVersion); - - await _storage.DeleteAsync(packagePath, cancellationToken); - await _storage.DeleteAsync(nuspecPath, cancellationToken); - await _storage.DeleteAsync(readmePath, cancellationToken); - await _storage.DeleteAsync(iconPath, cancellationToken); + return await _storage.GetAsync(path, cancellationToken); } - - private async Task GetStreamAsync( - string id, - NuGetVersion version, - Func pathFunc, - CancellationToken cancellationToken) + catch (DirectoryNotFoundException) { - var lowercasedId = id.ToLowerInvariant(); - var lowercasedNormalizedVersion = version.ToNormalizedString().ToLowerInvariant(); - var path = pathFunc(lowercasedId, lowercasedNormalizedVersion); - - try - { - return await _storage.GetAsync(path, cancellationToken); - } - catch (DirectoryNotFoundException) - { - // The "packages" prefix was lowercased, which was a breaking change - // on filesystems that are case sensitive. Handle this case to help - // users migrate to the latest version of BaGet. - // See https://github.com/loic-sharma/BaGet/issues/298 - _logger.LogError( - $"Unable to find the '{PackagesPathPrefix}' folder. " + - "If you've recently upgraded BaGet, please make sure this folder starts with a lowercased letter. " + - "For more information, please see https://github.com/loic-sharma/BaGet/issues/298"); - throw; - } + // The "packages" prefix was lowercased, which was a breaking change + // on filesystems that are case sensitive. Handle this case to help + // users migrate to the latest version of BaGet. + // See https://github.com/loic-sharma/BaGet/issues/298 + _logger.LogError( + $"Unable to find the '{PackagesPathPrefix}' folder. " + + "If you've recently upgraded BaGet, please make sure this folder starts with a lowercased letter. " + + "For more information, please see https://github.com/loic-sharma/BaGet/issues/298"); + throw; } + } - private string PackagePath(string lowercasedId, string lowercasedNormalizedVersion) - { - return Path.Combine( - PackagesPathPrefix, - lowercasedId, - lowercasedNormalizedVersion, - $"{lowercasedId}.{lowercasedNormalizedVersion}.nupkg"); - } + private string PackagePath(string lowercasedId, string lowercasedNormalizedVersion) + { + return Path.Combine( + PackagesPathPrefix, + lowercasedId, + lowercasedNormalizedVersion, + $"{lowercasedId}.{lowercasedNormalizedVersion}.nupkg"); + } - private string NuspecPath(string lowercasedId, string lowercasedNormalizedVersion) - { - return Path.Combine( - PackagesPathPrefix, - lowercasedId, - lowercasedNormalizedVersion, - $"{lowercasedId}.nuspec"); - } + private string NuspecPath(string lowercasedId, string lowercasedNormalizedVersion) + { + return Path.Combine( + PackagesPathPrefix, + lowercasedId, + lowercasedNormalizedVersion, + $"{lowercasedId}.nuspec"); + } - private string ReadmePath(string lowercasedId, string lowercasedNormalizedVersion) - { - return Path.Combine( - PackagesPathPrefix, - lowercasedId, - lowercasedNormalizedVersion, - "readme"); - } + private string ReadmePath(string lowercasedId, string lowercasedNormalizedVersion) + { + return Path.Combine( + PackagesPathPrefix, + lowercasedId, + lowercasedNormalizedVersion, + "readme"); + } - private string IconPath(string lowercasedId, string lowercasedNormalizedVersion) - { - return Path.Combine( - PackagesPathPrefix, - lowercasedId, - lowercasedNormalizedVersion, - "icon"); - } + private string IconPath(string lowercasedId, string lowercasedNormalizedVersion) + { + return Path.Combine( + PackagesPathPrefix, + lowercasedId, + lowercasedNormalizedVersion, + "icon"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Storage/SymbolStorageService.cs b/src/BaGet.Core/Storage/SymbolStorageService.cs index 4792481f8..fb97b2edc 100644 --- a/src/BaGet.Core/Storage/SymbolStorageService.cs +++ b/src/BaGet.Core/Storage/SymbolStorageService.cs @@ -4,75 +4,74 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public class SymbolStorageService : ISymbolStorageService { - public class SymbolStorageService : ISymbolStorageService + private const string SymbolsPathPrefix = "symbols"; + private const string PdbContentType = "binary/octet-stream"; + + private readonly IStorageService _storage; + + public SymbolStorageService(IStorageService storage) { - private const string SymbolsPathPrefix = "symbols"; - private const string PdbContentType = "binary/octet-stream"; + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + } - private readonly IStorageService _storage; + public async Task SavePortablePdbContentAsync( + string filename, + string key, + Stream pdbStream, + CancellationToken cancellationToken) + { + var path = GetPathForKey(filename, key); + var result = await _storage.PutAsync(path, pdbStream, PdbContentType, cancellationToken); - public SymbolStorageService(IStorageService storage) + if (result == StoragePutResult.Conflict) { - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + throw new InvalidOperationException($"Could not save PDB {filename} {key} due to conflict"); } + } - public async Task SavePortablePdbContentAsync( - string filename, - string key, - Stream pdbStream, - CancellationToken cancellationToken) - { - var path = GetPathForKey(filename, key); - var result = await _storage.PutAsync(path, pdbStream, PdbContentType, cancellationToken); + public async Task GetPortablePdbContentStreamOrNullAsync(string filename, string key) + { + var path = GetPathForKey(filename, key); - if (result == StoragePutResult.Conflict) - { - throw new InvalidOperationException($"Could not save PDB {filename} {key} due to conflict"); - } + try + { + return await _storage.GetAsync(path); } - - public async Task GetPortablePdbContentStreamOrNullAsync(string filename, string key) + catch { - var path = GetPathForKey(filename, key); - - try - { - return await _storage.GetAsync(path); - } - catch - { - return null; - } + return null; } + } - private string GetPathForKey(string filename, string key) - { - // Ensure the filename doesn't try to escape out of the current directory. - var tempPath = Path.GetDirectoryName(Path.GetTempPath()); - var expandedPath = Path.GetDirectoryName(Path.Combine(tempPath, filename)); + private string GetPathForKey(string filename, string key) + { + // Ensure the filename doesn't try to escape out of the current directory. + var tempPath = Path.GetDirectoryName(Path.GetTempPath()); + var expandedPath = Path.GetDirectoryName(Path.Combine(tempPath, filename)); - if (expandedPath != tempPath) - { - throw new ArgumentException(nameof(filename)); - } + if (expandedPath != tempPath) + { + throw new ArgumentException(nameof(filename)); + } - if (!key.All(char.IsLetterOrDigit)) - { - throw new ArgumentException(nameof(key)); - } + if (!key.All(char.IsLetterOrDigit)) + { + throw new ArgumentException(nameof(key)); + } - // The key's first 32 characters are the GUID, the remaining characters are the age. - // See: https://github.com/dotnet/symstore/blob/98717c63ec8342acf8a07aa5c909b88bd0c664cc/docs/specs/SSQP_Key_Conventions.md#portable-pdb-signature - // Debuggers should always use the age "ffffffff", however Visual Studio 2019 - // users have reported other age values. We will ignore the age. - key = key.Substring(0, 32) + "ffffffff"; + // The key's first 32 characters are the GUID, the remaining characters are the age. + // See: https://github.com/dotnet/symstore/blob/98717c63ec8342acf8a07aa5c909b88bd0c664cc/docs/specs/SSQP_Key_Conventions.md#portable-pdb-signature + // Debuggers should always use the age "ffffffff", however Visual Studio 2019 + // users have reported other age values. We will ignore the age. + key = key.Substring(0, 32) + "ffffffff"; - return Path.Combine( - SymbolsPathPrefix, - filename.ToLowerInvariant(), - key.ToLowerInvariant()); - } + return Path.Combine( + SymbolsPathPrefix, + filename.ToLowerInvariant(), + key.ToLowerInvariant()); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/Clients/DisabledUpstreamClient.cs b/src/BaGet.Core/Upstream/Clients/DisabledUpstreamClient.cs index 482c46a69..194a5b90e 100644 --- a/src/BaGet.Core/Upstream/Clients/DisabledUpstreamClient.cs +++ b/src/BaGet.Core/Upstream/Clients/DisabledUpstreamClient.cs @@ -4,32 +4,31 @@ using System.Threading.Tasks; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The client used when there are no upstream package sources. +/// +public class DisabledUpstreamClient : IUpstreamClient { - /// - /// The client used when there are no upstream package sources. - /// - public class DisabledUpstreamClient : IUpstreamClient - { - private readonly IReadOnlyList _emptyVersionList = new List(); - private readonly IReadOnlyList _emptyPackageList = new List(); + private readonly IReadOnlyList _emptyVersionList = new List(); + private readonly IReadOnlyList _emptyPackageList = new List(); - public Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) - { - return Task.FromResult(_emptyVersionList); - } + public Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) + { + return Task.FromResult(_emptyVersionList); + } - public Task> ListPackagesAsync(string id, CancellationToken cancellationToken) - { - return Task.FromResult(_emptyPackageList); - } + public Task> ListPackagesAsync(string id, CancellationToken cancellationToken) + { + return Task.FromResult(_emptyPackageList); + } - public Task DownloadPackageOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) - { - return Task.FromResult(null); - } + public Task DownloadPackageOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + return Task.FromResult(null); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/Clients/V2UpstreamClient.cs b/src/BaGet.Core/Upstream/Clients/V2UpstreamClient.cs index 763aed6cb..ec8f32fe9 100644 --- a/src/BaGet.Core/Upstream/Clients/V2UpstreamClient.cs +++ b/src/BaGet.Core/Upstream/Clients/V2UpstreamClient.cs @@ -13,193 +13,192 @@ using NuGet.Protocol.Core.Types; using NuGet.Versioning; -namespace BaGet.Core -{ - using ILogger = Microsoft.Extensions.Logging.ILogger; - using INuGetLogger = NuGet.Common.ILogger; +namespace BaGet.Core; + +using ILogger = Microsoft.Extensions.Logging.ILogger; +using INuGetLogger = NuGet.Common.ILogger; - /// - /// The client to upstream a NuGet server that uses the V2 protocol. - /// - public class V2UpstreamClient : IUpstreamClient, IDisposable +/// +/// The client to upstream a NuGet server that uses the V2 protocol. +/// +public class V2UpstreamClient : IUpstreamClient, IDisposable +{ + private readonly SourceCacheContext _cache; + private readonly SourceRepository _repository; + private readonly INuGetLogger _ngLogger; + private readonly ILogger _logger; + + public V2UpstreamClient( + IOptionsSnapshot options, + ILogger logger) { - private readonly SourceCacheContext _cache; - private readonly SourceRepository _repository; - private readonly INuGetLogger _ngLogger; - private readonly ILogger _logger; - - public V2UpstreamClient( - IOptionsSnapshot options, - ILogger logger) + if (options is null) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + throw new ArgumentNullException(nameof(options)); + } - if (options.Value?.PackageSource?.AbsolutePath == null) - { - throw new ArgumentException("No mirror package source has been set."); - } + if (options.Value?.PackageSource?.AbsolutePath == null) + { + throw new ArgumentException("No mirror package source has been set."); + } - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - _ngLogger = NullLogger.Instance; - _cache = new SourceCacheContext(); - _repository = Repository.Factory.GetCoreV2(new PackageSource(options.Value.PackageSource.AbsoluteUri)); - } + _ngLogger = NullLogger.Instance; + _cache = new SourceCacheContext(); + _repository = Repository.Factory.GetCoreV2(new PackageSource(options.Value.PackageSource.AbsoluteUri)); + } - public async Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) + public async Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken) + { + try { - try - { - var resource = await _repository.GetResourceAsync(cancellationToken); - var versions = await resource.GetAllVersionsAsync(id, _cache, _ngLogger, cancellationToken); + var resource = await _repository.GetResourceAsync(cancellationToken); + var versions = await resource.GetAllVersionsAsync(id, _cache, _ngLogger, cancellationToken); - return versions.ToList(); - } - catch (Exception e) - { - _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); - return new List(); - } + return versions.ToList(); } - - public async Task> ListPackagesAsync( - string id, - CancellationToken cancellationToken) + catch (Exception e) { - try - { - var resource = await _repository.GetResourceAsync(cancellationToken); - var packages = await resource.GetMetadataAsync( - id, - includePrerelease: true, - includeUnlisted: true, - _cache, - _ngLogger, - cancellationToken); - - return packages.Select(ToPackage).ToList(); - } - catch (Exception e) - { - _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); - return new List(); - } + _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); + return new List(); } + } - public async Task DownloadPackageOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) + public async Task> ListPackagesAsync( + string id, + CancellationToken cancellationToken) + { + try { - var packageStream = new MemoryStream(); - - try - { - var resource = await _repository.GetResourceAsync(cancellationToken); - var success = await resource.CopyNupkgToStreamAsync( - id, version, packageStream, _cache, _ngLogger, - cancellationToken); + var resource = await _repository.GetResourceAsync(cancellationToken); + var packages = await resource.GetMetadataAsync( + id, + includePrerelease: true, + includeUnlisted: true, + _cache, + _ngLogger, + cancellationToken); + + return packages.Select(ToPackage).ToList(); + } + catch (Exception e) + { + _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); + return new List(); + } + } - if (!success) - { - packageStream.Dispose(); - return null; - } + public async Task DownloadPackageOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + var packageStream = new MemoryStream(); - packageStream.Position = 0; + try + { + var resource = await _repository.GetResourceAsync(cancellationToken); + var success = await resource.CopyNupkgToStreamAsync( + id, version, packageStream, _cache, _ngLogger, + cancellationToken); - return packageStream; - } - catch (Exception e) + if (!success) { - _logger.LogError( - e, - "Failed to index package {Id} {Version} from upstream", - id, - version); - packageStream.Dispose(); return null; } - } - public void Dispose() => _cache.Dispose(); + packageStream.Position = 0; - private Package ToPackage(IPackageSearchMetadata package) + return packageStream; + } + catch (Exception e) { - return new Package - { - Id = package.Identity.Id, - Version = package.Identity.Version, - Authors = ParseAuthors(package.Authors), - Description = package.Description, - Downloads = 0, - HasReadme = false, - Language = null, - Listed = package.IsListed, - MinClientVersion = null, - Published = package.Published?.UtcDateTime ?? DateTime.MinValue, - RequireLicenseAcceptance = package.RequireLicenseAcceptance, - Summary = package.Summary, - Title = package.Title, - IconUrl = package.IconUrl, - LicenseUrl = package.LicenseUrl, - ProjectUrl = package.ProjectUrl, - PackageTypes = new List(), - RepositoryUrl = null, - RepositoryType = null, - Tags = package.Tags?.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries), - - Dependencies = ToDependencies(package) - }; + _logger.LogError( + e, + "Failed to index package {Id} {Version} from upstream", + id, + version); + + packageStream.Dispose(); + return null; } + } - private string[] ParseAuthors(string authors) + public void Dispose() => _cache.Dispose(); + + private Package ToPackage(IPackageSearchMetadata package) + { + return new Package { - if (string.IsNullOrEmpty(authors)) return Array.Empty(); + Id = package.Identity.Id, + Version = package.Identity.Version, + Authors = ParseAuthors(package.Authors), + Description = package.Description, + Downloads = 0, + HasReadme = false, + Language = null, + Listed = package.IsListed, + MinClientVersion = null, + Published = package.Published?.UtcDateTime ?? DateTime.MinValue, + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + Summary = package.Summary, + Title = package.Title, + IconUrl = package.IconUrl, + LicenseUrl = package.LicenseUrl, + ProjectUrl = package.ProjectUrl, + PackageTypes = new List(), + RepositoryUrl = null, + RepositoryType = null, + Tags = package.Tags?.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries), + + Dependencies = ToDependencies(package) + }; + } - return authors - .Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) - .Select(a => a.Trim()) - .ToArray(); - } + private string[] ParseAuthors(string authors) + { + if (string.IsNullOrEmpty(authors)) return Array.Empty(); - private List ToDependencies(IPackageSearchMetadata package) - { - return package - .DependencySets - .SelectMany(ToDependencies) - .ToList(); - } + return authors + .Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) + .Select(a => a.Trim()) + .ToArray(); + } - private IEnumerable ToDependencies(PackageDependencyGroup group) - { - var framework = group.TargetFramework.GetShortFolderName(); + private List ToDependencies(IPackageSearchMetadata package) + { + return package + .DependencySets + .SelectMany(ToDependencies) + .ToList(); + } - // BaGet stores a dependency group with no dependencies as a package dependency - // with no package id nor package version. - if ((group.Packages?.Count() ?? 0) == 0) - { - return new[] - { - new PackageDependency - { - Id = null, - VersionRange = null, - TargetFramework = framework, - } - }; - } + private IEnumerable ToDependencies(PackageDependencyGroup group) + { + var framework = group.TargetFramework.GetShortFolderName(); - return group.Packages.Select(d => new PackageDependency + // BaGet stores a dependency group with no dependencies as a package dependency + // with no package id nor package version. + if ((group.Packages?.Count() ?? 0) == 0) + { + return new[] { - Id = d.Id, - VersionRange = d.VersionRange?.ToString(), - TargetFramework = framework, - }); + new PackageDependency + { + Id = null, + VersionRange = null, + TargetFramework = framework, + } + }; } + + return group.Packages.Select(d => new PackageDependency + { + Id = d.Id, + VersionRange = d.VersionRange?.ToString(), + TargetFramework = framework, + }); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/Clients/V3UpstreamClient.cs b/src/BaGet.Core/Upstream/Clients/V3UpstreamClient.cs index bb8855ff9..cbabdebf8 100644 --- a/src/BaGet.Core/Upstream/Clients/V3UpstreamClient.cs +++ b/src/BaGet.Core/Upstream/Clients/V3UpstreamClient.cs @@ -9,171 +9,170 @@ using NuGet.Versioning; using Microsoft.Extensions.Logging; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// The mirroring client for a NuGet server that uses the V3 protocol. +/// +public class V3UpstreamClient : IUpstreamClient { - /// - /// The mirroring client for a NuGet server that uses the V3 protocol. - /// - public class V3UpstreamClient : IUpstreamClient - { - private readonly NuGetClient _client; - private readonly ILogger _logger; + private readonly NuGetClient _client; + private readonly ILogger _logger; - public V3UpstreamClient(NuGetClient client, ILogger logger) - { - _client = client ?? throw new ArgumentNullException(nameof(client)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public V3UpstreamClient(NuGetClient client, ILogger logger) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task DownloadPackageOrNullAsync( - string id, - NuGetVersion version, - CancellationToken cancellationToken) + public async Task DownloadPackageOrNullAsync( + string id, + NuGetVersion version, + CancellationToken cancellationToken) + { + try { - try - { - using (var downloadStream = await _client.DownloadPackageAsync(id, version, cancellationToken)) - { - return await downloadStream.AsTemporaryFileStreamAsync(cancellationToken); - } - } - catch (PackageNotFoundException) - { - return null; - } - catch (Exception e) + using (var downloadStream = await _client.DownloadPackageAsync(id, version, cancellationToken)) { - _logger.LogError( - e, - "Failed to download {PackageId} {PackageVersion} from upstream", - id, - version); - return null; + return await downloadStream.AsTemporaryFileStreamAsync(cancellationToken); } } + catch (PackageNotFoundException) + { + return null; + } + catch (Exception e) + { + _logger.LogError( + e, + "Failed to download {PackageId} {PackageVersion} from upstream", + id, + version); + return null; + } + } - public async Task> ListPackagesAsync( - string id, - CancellationToken cancellationToken) + public async Task> ListPackagesAsync( + string id, + CancellationToken cancellationToken) + { + try { - try - { - var packages = await _client.GetPackageMetadataAsync(id, cancellationToken); + var packages = await _client.GetPackageMetadataAsync(id, cancellationToken); - return packages.Select(ToPackage).ToList(); - } - catch (Exception e) - { - _logger.LogError(e, "Failed to mirror {PackageId}'s upstream metadata", id); - return new List(); - } + return packages.Select(ToPackage).ToList(); } - - public async Task> ListPackageVersionsAsync( - string id, - CancellationToken cancellationToken) + catch (Exception e) { - try - { - return await _client.ListPackageVersionsAsync(id, includeUnlisted: true, cancellationToken); - } - catch (Exception e) - { - _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); - return new List(); - } + _logger.LogError(e, "Failed to mirror {PackageId}'s upstream metadata", id); + return new List(); } + } - private Package ToPackage(PackageMetadata metadata) + public async Task> ListPackageVersionsAsync( + string id, + CancellationToken cancellationToken) + { + try { - var version = metadata.ParseVersion(); - - return new Package - { - Id = metadata.PackageId, - Version = version, - Authors = ParseAuthors(metadata.Authors), - Description = metadata.Description, - Downloads = 0, - HasReadme = false, - IsPrerelease = version.IsPrerelease, - Language = metadata.Language, - Listed = metadata.IsListed(), - MinClientVersion = metadata.MinClientVersion, - Published = metadata.Published.UtcDateTime, - RequireLicenseAcceptance = metadata.RequireLicenseAcceptance, - Summary = metadata.Summary, - Title = metadata.Title, - IconUrl = ParseUri(metadata.IconUrl), - LicenseUrl = ParseUri(metadata.LicenseUrl), - ProjectUrl = ParseUri(metadata.ProjectUrl), - PackageTypes = new List(), - RepositoryUrl = null, - RepositoryType = null, - SemVerLevel = version.IsSemVer2 ? SemVerLevel.SemVer2 : SemVerLevel.Unknown, - Tags = metadata.Tags?.ToArray() ?? Array.Empty(), - - Dependencies = ToDependencies(metadata) - }; + return await _client.ListPackageVersionsAsync(id, includeUnlisted: true, cancellationToken); + } + catch (Exception e) + { + _logger.LogError(e, "Failed to mirror {PackageId}'s upstream versions", id); + return new List(); } + } - private Uri ParseUri(string uriString) + private Package ToPackage(PackageMetadata metadata) + { + var version = metadata.ParseVersion(); + + return new Package { - if (uriString == null) return null; + Id = metadata.PackageId, + Version = version, + Authors = ParseAuthors(metadata.Authors), + Description = metadata.Description, + Downloads = 0, + HasReadme = false, + IsPrerelease = version.IsPrerelease, + Language = metadata.Language, + Listed = metadata.IsListed(), + MinClientVersion = metadata.MinClientVersion, + Published = metadata.Published.UtcDateTime, + RequireLicenseAcceptance = metadata.RequireLicenseAcceptance, + Summary = metadata.Summary, + Title = metadata.Title, + IconUrl = ParseUri(metadata.IconUrl), + LicenseUrl = ParseUri(metadata.LicenseUrl), + ProjectUrl = ParseUri(metadata.ProjectUrl), + PackageTypes = new List(), + RepositoryUrl = null, + RepositoryType = null, + SemVerLevel = version.IsSemVer2 ? SemVerLevel.SemVer2 : SemVerLevel.Unknown, + Tags = metadata.Tags?.ToArray() ?? Array.Empty(), + + Dependencies = ToDependencies(metadata) + }; + } - if (!Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) - { - return null; - } + private Uri ParseUri(string uriString) + { + if (uriString == null) return null; - return uri; + if (!Uri.TryCreate(uriString, UriKind.Absolute, out var uri)) + { + return null; } - private string[] ParseAuthors(string authors) - { - if (string.IsNullOrEmpty(authors)) return Array.Empty(); + return uri; + } - return authors - .Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) - .Select(a => a.Trim()) - .ToArray(); - } + private string[] ParseAuthors(string authors) + { + if (string.IsNullOrEmpty(authors)) return Array.Empty(); - private List ToDependencies(PackageMetadata package) - { - if ((package.DependencyGroups?.Count ?? 0) == 0) - { - return new List(); - } + return authors + .Split(new[] { ',', ';', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) + .Select(a => a.Trim()) + .ToArray(); + } - return package.DependencyGroups - .SelectMany(ToDependencies) - .ToList(); + private List ToDependencies(PackageMetadata package) + { + if ((package.DependencyGroups?.Count ?? 0) == 0) + { + return new List(); } - private IEnumerable ToDependencies(DependencyGroupItem group) + return package.DependencyGroups + .SelectMany(ToDependencies) + .ToList(); + } + + private IEnumerable ToDependencies(DependencyGroupItem group) + { + // BaGet stores a dependency group with no dependencies as a package dependency + // with no package id nor package version. + if ((group.Dependencies?.Count ?? 0) == 0) { - // BaGet stores a dependency group with no dependencies as a package dependency - // with no package id nor package version. - if ((group.Dependencies?.Count ?? 0) == 0) + return new[] { - return new[] + new PackageDependency { - new PackageDependency - { - Id = null, - VersionRange = null, - TargetFramework = group.TargetFramework, - } - }; - } - - return group.Dependencies.Select(d => new PackageDependency - { - Id = d.Id, - VersionRange = d.Range, - TargetFramework = group.TargetFramework, - }); + Id = null, + VersionRange = null, + TargetFramework = group.TargetFramework, + } + }; } + + return group.Dependencies.Select(d => new PackageDependency + { + Id = d.Id, + VersionRange = d.Range, + TargetFramework = group.TargetFramework, + }); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/DownloadsImporter.cs b/src/BaGet.Core/Upstream/DownloadsImporter.cs index 120b71460..494d65f57 100644 --- a/src/BaGet.Core/Upstream/DownloadsImporter.cs +++ b/src/BaGet.Core/Upstream/DownloadsImporter.cs @@ -6,61 +6,60 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; -namespace BaGet.Core +namespace BaGet.Core; + +public class DownloadsImporter { - public class DownloadsImporter - { - private const int BatchSize = 200; + private const int BatchSize = 200; - private readonly IContext _context; - private readonly IPackageDownloadsSource _downloadsSource; - private readonly ILogger _logger; + private readonly IContext _context; + private readonly IPackageDownloadsSource _downloadsSource; + private readonly ILogger _logger; - public DownloadsImporter( - IContext context, - IPackageDownloadsSource downloadsSource, - ILogger logger) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _downloadsSource = downloadsSource ?? throw new ArgumentNullException(nameof(downloadsSource)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public DownloadsImporter( + IContext context, + IPackageDownloadsSource downloadsSource, + ILogger logger) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _downloadsSource = downloadsSource ?? throw new ArgumentNullException(nameof(downloadsSource)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task ImportAsync(CancellationToken cancellationToken) + { + var packageDownloads = await _downloadsSource.GetPackageDownloadsAsync(); + var packages = await _context.Packages.CountAsync(); + var batches = (packages / BatchSize) + 1; - public async Task ImportAsync(CancellationToken cancellationToken) + for (var batch = 0; batch < batches; batch++) { - var packageDownloads = await _downloadsSource.GetPackageDownloadsAsync(); - var packages = await _context.Packages.CountAsync(); - var batches = (packages / BatchSize) + 1; + _logger.LogInformation("Importing batch {Batch}...", batch); - for (var batch = 0; batch < batches; batch++) + foreach (var package in await GetBatchAsync(batch, cancellationToken)) { - _logger.LogInformation("Importing batch {Batch}...", batch); + var packageId = package.Id.ToLowerInvariant(); + var packageVersion = package.NormalizedVersionString.ToLowerInvariant(); - foreach (var package in await GetBatchAsync(batch, cancellationToken)) + if (!packageDownloads.ContainsKey(packageId) || + !packageDownloads[packageId].ContainsKey(packageVersion)) { - var packageId = package.Id.ToLowerInvariant(); - var packageVersion = package.NormalizedVersionString.ToLowerInvariant(); - - if (!packageDownloads.ContainsKey(packageId) || - !packageDownloads[packageId].ContainsKey(packageVersion)) - { - continue; - } - - package.Downloads = packageDownloads[packageId][packageVersion]; + continue; } - await _context.SaveChangesAsync(cancellationToken); - - _logger.LogInformation("Imported batch {Batch}", batch); + package.Downloads = packageDownloads[packageId][packageVersion]; } - } - private Task> GetBatchAsync(int batch, CancellationToken cancellationToken) - => _context.Packages - .OrderBy(p => p.Key) - .Skip(batch * BatchSize) - .Take(BatchSize) - .ToListAsync(cancellationToken); + await _context.SaveChangesAsync(cancellationToken); + + _logger.LogInformation("Imported batch {Batch}", batch); + } } -} + + private Task> GetBatchAsync(int batch, CancellationToken cancellationToken) + => _context.Packages + .OrderBy(p => p.Key) + .Skip(batch * BatchSize) + .Take(BatchSize) + .ToListAsync(cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/IPackageDownloadsSource.cs b/src/BaGet.Core/Upstream/IPackageDownloadsSource.cs index 706e9638f..23af0909c 100644 --- a/src/BaGet.Core/Upstream/IPackageDownloadsSource.cs +++ b/src/BaGet.Core/Upstream/IPackageDownloadsSource.cs @@ -1,10 +1,9 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +public interface IPackageDownloadsSource { - public interface IPackageDownloadsSource - { - Task>> GetPackageDownloadsAsync(); - } -} + Task>> GetPackageDownloadsAsync(); +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/IUpstreamClient.cs b/src/BaGet.Core/Upstream/IUpstreamClient.cs index 648d0c429..bc61351e2 100644 --- a/src/BaGet.Core/Upstream/IUpstreamClient.cs +++ b/src/BaGet.Core/Upstream/IUpstreamClient.cs @@ -5,47 +5,46 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A client to interact with an upstream package source. +/// +public interface IUpstreamClient { /// - /// A client to interact with an upstream package source. + /// Try to get all versions of a package from the upstream package source. Returns empty + /// if the package could not be found. /// - public interface IUpstreamClient - { - /// - /// Try to get all versions of a package from the upstream package source. Returns empty - /// if the package could not be found. - /// - /// The package ID to lookup - /// - /// - /// All versions of a package, including unlisted packages. - /// Returns an empty list if the package could not be found. - /// - Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken); + /// The package ID to lookup + /// + /// + /// All versions of a package, including unlisted packages. + /// Returns an empty list if the package could not be found. + /// + Task> ListPackageVersionsAsync(string id, CancellationToken cancellationToken); - /// - /// Try to get the metadata for all versions of a package from the upstream package source. Returns empty - /// if the package could not be found. - /// - /// The package ID to lookup - /// - /// - /// The metadata for all versions of a package, including unlisted versions. - /// Returns an empty list if the package could not be found. - /// - Task> ListPackagesAsync(string id, CancellationToken cancellationToken); + /// + /// Try to get the metadata for all versions of a package from the upstream package source. Returns empty + /// if the package could not be found. + /// + /// The package ID to lookup + /// + /// + /// The metadata for all versions of a package, including unlisted versions. + /// Returns an empty list if the package could not be found. + /// + Task> ListPackagesAsync(string id, CancellationToken cancellationToken); - /// - /// Download a package from the upstream package source. Returns null if the package does not exist. - /// - /// The package ID to download. - /// The package version to download. - /// - /// - /// The package stream or null if the package cannot be found. - /// The stream is guaranteed to be seekable if not not null. - /// - Task DownloadPackageOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken); - } -} + /// + /// Download a package from the upstream package source. Returns null if the package does not exist. + /// + /// The package ID to download. + /// The package version to download. + /// + /// + /// The package stream or null if the package cannot be found. + /// The stream is guaranteed to be seekable if not not null. + /// + Task DownloadPackageOrNullAsync(string id, NuGetVersion version, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Core/Upstream/PackageDownloadsJsonSource.cs b/src/BaGet.Core/Upstream/PackageDownloadsJsonSource.cs index 5f0c6dd04..c77fd349b 100644 --- a/src/BaGet.Core/Upstream/PackageDownloadsJsonSource.cs +++ b/src/BaGet.Core/Upstream/PackageDownloadsJsonSource.cs @@ -9,104 +9,103 @@ using Newtonsoft.Json.Linq; using NuGet.Versioning; -namespace BaGet.Core +namespace BaGet.Core; + +// See https://github.com/NuGet/NuGet.Services.Metadata/blob/master/src/NuGet.Indexing/Downloads.cs +public class PackageDownloadsJsonSource : IPackageDownloadsSource { - // See https://github.com/NuGet/NuGet.Services.Metadata/blob/master/src/NuGet.Indexing/Downloads.cs - public class PackageDownloadsJsonSource : IPackageDownloadsSource + public const string PackageDownloadsV1Url = "https://nugetprod0.blob.core.windows.net/ng-search-data/downloads.v1.json"; + + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public PackageDownloadsJsonSource(HttpClient httpClient, ILogger logger) { - public const string PackageDownloadsV1Url = "https://nugetprod0.blob.core.windows.net/ng-search-data/downloads.v1.json"; + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - private readonly HttpClient _httpClient; - private readonly ILogger _logger; + public async Task>> GetPackageDownloadsAsync() + { + _logger.LogInformation("Fetching package downloads..."); - public PackageDownloadsJsonSource(HttpClient httpClient, ILogger logger) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + var results = new Dictionary>(); - public async Task>> GetPackageDownloadsAsync() + using (var downloadsStream = await GetDownloadsStreamAsync()) + using (var downloadStreamReader = new StreamReader(downloadsStream)) + using (var jsonReader = new JsonTextReader(downloadStreamReader)) { - _logger.LogInformation("Fetching package downloads..."); + _logger.LogInformation("Parsing package downloads..."); - var results = new Dictionary>(); + jsonReader.Read(); - using (var downloadsStream = await GetDownloadsStreamAsync()) - using (var downloadStreamReader = new StreamReader(downloadsStream)) - using (var jsonReader = new JsonTextReader(downloadStreamReader)) + while (jsonReader.Read()) { - _logger.LogInformation("Parsing package downloads..."); - - jsonReader.Read(); - - while (jsonReader.Read()) + try { - try + if (jsonReader.TokenType == JsonToken.StartArray) { - if (jsonReader.TokenType == JsonToken.StartArray) + // Reads this one record, not the document: the outer array's + // start token was consumed above, so the reader sits inside it. + // What dominates memory is the dictionary returned below, which + // holds every package and version by design. + var record = JToken.ReadFrom(jsonReader); + var id = string.Intern(record[0].ToString().ToLowerInvariant()); + + // The second entry in each record should be an array of versions, if not move on to next entry. + // This is a check to safe guard against invalid entries. + if (record.Count() == 2 && record[1].Type != JTokenType.Array) { - // Reads this one record, not the document: the outer array's - // start token was consumed above, so the reader sits inside it. - // What dominates memory is the dictionary returned below, which - // holds every package and version by design. - var record = JToken.ReadFrom(jsonReader); - var id = string.Intern(record[0].ToString().ToLowerInvariant()); - - // The second entry in each record should be an array of versions, if not move on to next entry. - // This is a check to safe guard against invalid entries. - if (record.Count() == 2 && record[1].Type != JTokenType.Array) - { - continue; - } + continue; + } - if (!results.ContainsKey(id)) - { - results.Add(id, new Dictionary()); - } + if (!results.ContainsKey(id)) + { + results.Add(id, new Dictionary()); + } - foreach (var token in record) + foreach (var token in record) + { + if (token != null && token.Count() == 2) { - if (token != null && token.Count() == 2) - { - var version = string.Intern(NuGetVersion.Parse(token[0].ToString()).ToNormalizedString().ToLowerInvariant()); - var downloads = token[1].ToObject(); + var version = string.Intern(NuGetVersion.Parse(token[0].ToString()).ToNormalizedString().ToLowerInvariant()); + var downloads = token[1].ToObject(); - results[id][version] = downloads; - } + results[id][version] = downloads; } } } - catch (JsonReaderException e) - { - _logger.LogError(e, "Invalid entry in downloads.v1.json"); - } } - - _logger.LogInformation("Parsed package downloads"); + catch (JsonReaderException e) + { + _logger.LogError(e, "Invalid entry in downloads.v1.json"); + } } - return results; + _logger.LogInformation("Parsed package downloads"); } - internal async Task GetDownloadsStreamAsync() - { - _logger.LogInformation("Downloading downloads.v1.json..."); + return results; + } - var response = await _httpClient.GetAsync(PackageDownloadsV1Url, HttpCompletionOption.ResponseHeadersRead); + internal async Task GetDownloadsStreamAsync() + { + _logger.LogInformation("Downloading downloads.v1.json..."); - response.EnsureSuccessStatusCode(); + var response = await _httpClient.GetAsync(PackageDownloadsV1Url, HttpCompletionOption.ResponseHeadersRead); - using (var networkStream = await response.Content.ReadAsStreamAsync()) - { - // Spooled to a temporary file rather than held in memory. This one deletes - // itself when the stream is disposed; the hand-rolled file this replaced was - // left behind in the temporary directory on every import. - var fileStream = await networkStream.AsTemporaryFileStreamAsync(); + response.EnsureSuccessStatusCode(); - _logger.LogInformation("Downloaded downloads.v1.json"); + using (var networkStream = await response.Content.ReadAsStreamAsync()) + { + // Spooled to a temporary file rather than held in memory. This one deletes + // itself when the stream is disposed; the hand-rolled file this replaced was + // left behind in the temporary directory on every import. + var fileStream = await networkStream.AsTemporaryFileStreamAsync(); - return fileStream; - } + _logger.LogInformation("Downloaded downloads.v1.json"); + + return fileStream; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Validation/RequiredIfAttribute.cs b/src/BaGet.Core/Validation/RequiredIfAttribute.cs index 56571a3d0..8165b8080 100644 --- a/src/BaGet.Core/Validation/RequiredIfAttribute.cs +++ b/src/BaGet.Core/Validation/RequiredIfAttribute.cs @@ -2,133 +2,132 @@ using System.ComponentModel.DataAnnotations; using System.Globalization; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Provides conditional validation based on related property value. +/// +/// Inspiration: https://stackoverflow.com/a/27666044 +/// +[AttributeUsage(AttributeTargets.Property)] +public sealed class RequiredIfAttribute : ValidationAttribute { + #region Properties + /// - /// Provides conditional validation based on related property value. - /// - /// Inspiration: https://stackoverflow.com/a/27666044 + /// Gets or sets the other property name that will be used during validation. /// - [AttributeUsage(AttributeTargets.Property)] - public sealed class RequiredIfAttribute : ValidationAttribute + /// + /// The other property name. + /// + public string OtherProperty { get; } + + /// + /// Gets or sets the display name of the other property. + /// + /// + /// The display name of the other property. + /// + public string OtherPropertyDisplayName { get; set; } + + /// + /// Gets or sets the other property value that will be relevant for validation. + /// + /// + /// The other property value. + /// + public object OtherPropertyValue { get; } + + /// + /// Gets or sets a value indicating whether other property's value should match or differ from provided other property's value (default is false). + /// + /// + /// true if other property's value validation should be inverted; otherwise, false. + /// + /// + /// How this works + /// - true: validated property is required when other property doesn't equal provided value + /// - false: validated property is required when other property matches provided value + /// + public bool IsInverted { get; set; } + + /// + /// Gets a value that indicates whether the attribute requires validation context. + /// + /// true if the attribute requires validation context; otherwise, false. + public override bool RequiresValidationContext => true; + + #endregion + + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + /// The other property. + /// The other property value. + public RequiredIfAttribute(string otherProperty, object otherPropertyValue) + : base("'{0}' is required because '{1}' has a value {3}'{2}'.") { - #region Properties - - /// - /// Gets or sets the other property name that will be used during validation. - /// - /// - /// The other property name. - /// - public string OtherProperty { get; } - - /// - /// Gets or sets the display name of the other property. - /// - /// - /// The display name of the other property. - /// - public string OtherPropertyDisplayName { get; set; } - - /// - /// Gets or sets the other property value that will be relevant for validation. - /// - /// - /// The other property value. - /// - public object OtherPropertyValue { get; } - - /// - /// Gets or sets a value indicating whether other property's value should match or differ from provided other property's value (default is false). - /// - /// - /// true if other property's value validation should be inverted; otherwise, false. - /// - /// - /// How this works - /// - true: validated property is required when other property doesn't equal provided value - /// - false: validated property is required when other property matches provided value - /// - public bool IsInverted { get; set; } - - /// - /// Gets a value that indicates whether the attribute requires validation context. - /// - /// true if the attribute requires validation context; otherwise, false. - public override bool RequiresValidationContext => true; - - #endregion - - #region Constructor - - /// - /// Initializes a new instance of the class. - /// - /// The other property. - /// The other property value. - public RequiredIfAttribute(string otherProperty, object otherPropertyValue) - : base("'{0}' is required because '{1}' has a value {3}'{2}'.") - { - OtherProperty = otherProperty; - OtherPropertyValue = otherPropertyValue; - IsInverted = false; - } + OtherProperty = otherProperty; + OtherPropertyValue = otherPropertyValue; + IsInverted = false; + } + + #endregion + + /// + /// Applies formatting to an error message, based on the data field where the error occurred. + /// + /// The name to include in the formatted message. + /// + /// An instance of the formatted error message. + /// + public override string FormatErrorMessage(string name) + { + return string.Format( + CultureInfo.CurrentCulture, + ErrorMessageString, + name, + OtherPropertyDisplayName ?? OtherProperty, + OtherPropertyValue, + IsInverted ? "other than " : "of "); + } - #endregion + /// + /// Validates the specified value with respect to the current validation attribute. + /// + /// The value to validate. + /// The context information about the validation operation. + /// + /// An instance of the class. + /// + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (validationContext == null) + throw new ArgumentNullException(nameof(validationContext)); - /// - /// Applies formatting to an error message, based on the data field where the error occurred. - /// - /// The name to include in the formatted message. - /// - /// An instance of the formatted error message. - /// - public override string FormatErrorMessage(string name) + var otherProperty = validationContext.ObjectType.GetProperty(OtherProperty); + if (otherProperty == null) { - return string.Format( - CultureInfo.CurrentCulture, - ErrorMessageString, - name, - OtherPropertyDisplayName ?? OtherProperty, - OtherPropertyValue, - IsInverted ? "other than " : "of "); + return new ValidationResult( + string.Format(CultureInfo.CurrentCulture, "Could not find a property named '{0}'.", OtherProperty)); } - /// - /// Validates the specified value with respect to the current validation attribute. - /// - /// The value to validate. - /// The context information about the validation operation. - /// - /// An instance of the class. - /// - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + var otherValue = otherProperty.GetValue(validationContext.ObjectInstance); + + // Check if this value is actually required and validate it. + if (!IsInverted && Equals(otherValue, OtherPropertyValue) || + IsInverted && !Equals(otherValue, OtherPropertyValue)) { - if (validationContext == null) - throw new ArgumentNullException(nameof(validationContext)); - - var otherProperty = validationContext.ObjectType.GetProperty(OtherProperty); - if (otherProperty == null) - { - return new ValidationResult( - string.Format(CultureInfo.CurrentCulture, "Could not find a property named '{0}'.", OtherProperty)); - } - - var otherValue = otherProperty.GetValue(validationContext.ObjectInstance); - - // Check if this value is actually required and validate it. - if (!IsInverted && Equals(otherValue, OtherPropertyValue) || - IsInverted && !Equals(otherValue, OtherPropertyValue)) - { - if (value == null) - return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); - - // Additional check for strings so they're not empty - if (value is string val && val.Trim().Length == 0) - return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); - } - - return ValidationResult.Success; + if (value == null) + return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); + + // Additional check for strings so they're not empty + if (value is string val && val.Trim().Length == 0) + return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } + + return ValidationResult.Success; } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Validation/ValidateBaGetOptions.cs b/src/BaGet.Core/Validation/ValidateBaGetOptions.cs index 3c20189dc..0f427389e 100644 --- a/src/BaGet.Core/Validation/ValidateBaGetOptions.cs +++ b/src/BaGet.Core/Validation/ValidateBaGetOptions.cs @@ -2,49 +2,48 @@ using System.ComponentModel.DataAnnotations; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// A configuration that validates options using data annotations. +/// +/// The type of options to validate. +public class ValidateBaGetOptions : IValidateOptions where TOptions : class { + private readonly string _optionsName; + /// - /// A configuration that validates options using data annotations. + /// Create a new validator. /// - /// The type of options to validate. - public class ValidateBaGetOptions : IValidateOptions where TOptions : class + /// + /// The option's key in the configuration or appsettings.json file, + /// or null if the options was created from the root configuration. + /// + public ValidateBaGetOptions(string optionsName) { - private readonly string _optionsName; + _optionsName = optionsName; + } - /// - /// Create a new validator. - /// - /// - /// The option's key in the configuration or appsettings.json file, - /// or null if the options was created from the root configuration. - /// - public ValidateBaGetOptions(string optionsName) + public ValidateOptionsResult Validate(string name, TOptions options) + { + // See: https://github.com/dotnet/runtime/blob/e3ffd343ad5bd3a999cb9515f59e6e7a777b2c34/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs + var context = new ValidationContext(options); + var validationResults = new List(); + if (Validator.TryValidateObject(options, context, validationResults, validateAllProperties: true)) { - _optionsName = optionsName; + return ValidateOptionsResult.Success; } - public ValidateOptionsResult Validate(string name, TOptions options) - { - // See: https://github.com/dotnet/runtime/blob/e3ffd343ad5bd3a999cb9515f59e6e7a777b2c34/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs - var context = new ValidationContext(options); - var validationResults = new List(); - if (Validator.TryValidateObject(options, context, validationResults, validateAllProperties: true)) - { - return ValidateOptionsResult.Success; - } + var errors = new List(); + var message = (_optionsName == null) + ? $"Invalid configs" + : $"Invalid '{_optionsName}' configs"; - var errors = new List(); - var message = (_optionsName == null) - ? $"Invalid configs" - : $"Invalid '{_optionsName}' configs"; - - foreach (var result in validationResults) - { - errors.Add($"{message}: {result}"); - } - - return ValidateOptionsResult.Fail(errors); + foreach (var result in validationResults) + { + errors.Add($"{message}: {result}"); } + + return ValidateOptionsResult.Fail(errors); } -} +} \ No newline at end of file diff --git a/src/BaGet.Core/Validation/ValidateStartupOptions.cs b/src/BaGet.Core/Validation/ValidateStartupOptions.cs index c662253a2..9fe4e3069 100644 --- a/src/BaGet.Core/Validation/ValidateStartupOptions.cs +++ b/src/BaGet.Core/Validation/ValidateStartupOptions.cs @@ -2,56 +2,55 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace BaGet.Core +namespace BaGet.Core; + +/// +/// Validates BaGet's options, used at startup. +/// +public class ValidateStartupOptions { - /// - /// Validates BaGet's options, used at startup. - /// - public class ValidateStartupOptions + private readonly IOptions _root; + private readonly IOptions _database; + private readonly IOptions _storage; + private readonly IOptions _mirror; + private readonly ILogger _logger; + + public ValidateStartupOptions( + IOptions root, + IOptions database, + IOptions storage, + IOptions mirror, + ILogger logger) { - private readonly IOptions _root; - private readonly IOptions _database; - private readonly IOptions _storage; - private readonly IOptions _mirror; - private readonly ILogger _logger; + _root = root ?? throw new ArgumentNullException(nameof(root)); + _database = database ?? throw new ArgumentNullException(nameof(database)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _mirror = mirror ?? throw new ArgumentNullException(nameof(mirror)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public ValidateStartupOptions( - IOptions root, - IOptions database, - IOptions storage, - IOptions mirror, - ILogger logger) + public bool Validate() + { + try { - _root = root ?? throw new ArgumentNullException(nameof(root)); - _database = database ?? throw new ArgumentNullException(nameof(database)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _mirror = mirror ?? throw new ArgumentNullException(nameof(mirror)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + // Access each option to force validations to run. + // Invalid options will trigger an "OptionsValidationException" exception. + _ = _root.Value; + _ = _database.Value; + _ = _storage.Value; + _ = _mirror.Value; - public bool Validate() + return true; + } + catch (OptionsValidationException e) { - try + foreach (var failure in e.Failures) { - // Access each option to force validations to run. - // Invalid options will trigger an "OptionsValidationException" exception. - _ = _root.Value; - _ = _database.Value; - _ = _storage.Value; - _ = _mirror.Value; - - return true; + _logger.LogError("{OptionsFailure}", failure); } - catch (OptionsValidationException e) - { - foreach (var failure in e.Failures) - { - _logger.LogError("{OptionsFailure}", failure); - } - _logger.LogError(e, "BaGet configuration is invalid."); - return false; - } + _logger.LogError(e, "BaGet configuration is invalid."); + return false; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs b/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs index 3b61d3226..52a25d2ba 100644 --- a/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs +++ b/src/BaGet.Database.MySql/MySqlApplicationExtensions.cs @@ -6,36 +6,35 @@ using Microsoft.Extensions.Options; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; -namespace BaGet +namespace BaGet; + +public static class MySqlApplicationExtensions { - public static class MySqlApplicationExtensions + public static BaGetApplication AddMySqlDatabase(this BaGetApplication app) { - public static BaGetApplication AddMySqlDatabase(this BaGetApplication app) + app.Services.AddBaGetDbContextProvider("MySql", (provider, options) => { - app.Services.AddBaGetDbContextProvider("MySql", (provider, options) => - { - var databaseOptions = provider.GetRequiredService>(); + var databaseOptions = provider.GetRequiredService>(); - // Detecting the version connects to the server, and these options are built - // whenever the contexts are enumerated - including by the design-time tools. - // Prefer the configured version so that building options stays offline. - var serverVersion = string.IsNullOrWhiteSpace(databaseOptions.Value.MySqlServerVersion) - ? ServerVersion.AutoDetect(databaseOptions.Value.ConnectionString) - : ServerVersion.Parse(databaseOptions.Value.MySqlServerVersion); + // Detecting the version connects to the server, and these options are built + // whenever the contexts are enumerated - including by the design-time tools. + // Prefer the configured version so that building options stays offline. + var serverVersion = string.IsNullOrWhiteSpace(databaseOptions.Value.MySqlServerVersion) + ? ServerVersion.AutoDetect(databaseOptions.Value.ConnectionString) + : ServerVersion.Parse(databaseOptions.Value.MySqlServerVersion); - options.UseMySql(databaseOptions.Value.ConnectionString, serverVersion); - }); + options.UseMySql(databaseOptions.Value.ConnectionString, serverVersion); + }); - return app; - } + return app; + } - public static BaGetApplication AddMySqlDatabase( - this BaGetApplication app, - Action configure) - { - app.AddMySqlDatabase(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddMySqlDatabase( + this BaGetApplication app, + Action configure) + { + app.AddMySqlDatabase(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.MySql/MySqlContext.cs b/src/BaGet.Database.MySql/MySqlContext.cs index be88665a6..a2ee6300e 100644 --- a/src/BaGet.Database.MySql/MySqlContext.cs +++ b/src/BaGet.Database.MySql/MySqlContext.cs @@ -2,57 +2,56 @@ using Microsoft.EntityFrameworkCore; using MySqlConnector; -namespace BaGet.Database.MySql +namespace BaGet.Database.MySql; + +public class MySqlContext : AbstractContext { - public class MySqlContext : AbstractContext + /// + /// The MySQL Server error code for when a unique constraint is violated. + /// + private const int UniqueConstraintViolationErrorCode = 1062; + + public MySqlContext(DbContextOptions options) : base(options) + { + } + + public override bool IsUniqueConstraintViolationException(DbUpdateException exception) { - /// - /// The MySQL Server error code for when a unique constraint is violated. - /// - private const int UniqueConstraintViolationErrorCode = 1062; - - public MySqlContext(DbContextOptions options) : base(options) - { - } - - public override bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - return exception.InnerException is MySqlException mysqlException && - mysqlException.Number == UniqueConstraintViolationErrorCode; - } - - /// - /// MySQL does not support LIMIT clauses in subqueries for certain subquery operators. - /// See: https://dev.mysql.com/doc/refman/8.0/en/subquery-restrictions.html - /// - public override bool SupportsLimitInSubqueries => false; - - /// - /// The long string columns are stored as "longtext" rather than the "varchar(4000)" - /// that a 4000 character maximum length would otherwise map to. - /// - /// - /// This is what the database has had since the schema was created, and it cannot be - /// changed: MySQL limits a row to 65535 bytes, and utf8mb4 needs up to four bytes a - /// character, so a single varchar(4000) column takes 16000 bytes and these eight - /// together are far beyond the limit. Declaring the type here keeps the model and - /// the database in agreement, so a migration for an unrelated change does not try to - /// convert them. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var package = builder.Entity(); - - package.Property(p => p.Authors).HasColumnType("longtext"); - package.Property(p => p.Description).HasColumnType("longtext"); - package.Property(p => p.IconUrl).HasColumnType("longtext"); - package.Property(p => p.LicenseUrl).HasColumnType("longtext"); - package.Property(p => p.ProjectUrl).HasColumnType("longtext"); - package.Property(p => p.RepositoryUrl).HasColumnType("longtext"); - package.Property(p => p.Summary).HasColumnType("longtext"); - package.Property(p => p.Tags).HasColumnType("longtext"); - } + return exception.InnerException is MySqlException mysqlException && + mysqlException.Number == UniqueConstraintViolationErrorCode; + } + + /// + /// MySQL does not support LIMIT clauses in subqueries for certain subquery operators. + /// See: https://dev.mysql.com/doc/refman/8.0/en/subquery-restrictions.html + /// + public override bool SupportsLimitInSubqueries => false; + + /// + /// The long string columns are stored as "longtext" rather than the "varchar(4000)" + /// that a 4000 character maximum length would otherwise map to. + /// + /// + /// This is what the database has had since the schema was created, and it cannot be + /// changed: MySQL limits a row to 65535 bytes, and utf8mb4 needs up to four bytes a + /// character, so a single varchar(4000) column takes 16000 bytes and these eight + /// together are far beyond the limit. Declaring the type here keeps the model and + /// the database in agreement, so a migration for an unrelated change does not try to + /// convert them. + /// + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + var package = builder.Entity(); + + package.Property(p => p.Authors).HasColumnType("longtext"); + package.Property(p => p.Description).HasColumnType("longtext"); + package.Property(p => p.IconUrl).HasColumnType("longtext"); + package.Property(p => p.LicenseUrl).HasColumnType("longtext"); + package.Property(p => p.ProjectUrl).HasColumnType("longtext"); + package.Property(p => p.RepositoryUrl).HasColumnType("longtext"); + package.Property(p => p.Summary).HasColumnType("longtext"); + package.Property(p => p.Tags).HasColumnType("longtext"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.MySql/MySqlContextFactory.cs b/src/BaGet.Database.MySql/MySqlContextFactory.cs index 071c95e87..1a80f8885 100644 --- a/src/BaGet.Database.MySql/MySqlContextFactory.cs +++ b/src/BaGet.Database.MySql/MySqlContextFactory.cs @@ -1,30 +1,29 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; -namespace BaGet.Database.MySql +namespace BaGet.Database.MySql; + +/// +/// Builds a context for the Entity Framework design-time tools. +/// +/// +/// Without this the tools build the application's service provider to find the contexts, +/// which configures every database provider that is registered - including ones whose +/// server is unreachable or whose driver does not match the installed Entity Framework +/// version. A factory keeps "dotnet ef" offline and independent of the other providers. +/// +public class MySqlContextFactory : IDesignTimeDbContextFactory { - /// - /// Builds a context for the Entity Framework design-time tools. - /// - /// - /// Without this the tools build the application's service provider to find the contexts, - /// which configures every database provider that is registered - including ones whose - /// server is unreachable or whose driver does not match the installed Entity Framework - /// version. A factory keeps "dotnet ef" offline and independent of the other providers. - /// - public class MySqlContextFactory : IDesignTimeDbContextFactory + public MySqlContext CreateDbContext(string[] args) { - public MySqlContext CreateDbContext(string[] args) - { - // Parse rather than detect: detecting the version connects to the server, which - // would put the design-time tools back off line. - var options = new DbContextOptionsBuilder() - .UseMySql( - "Server=localhost;Database=baget;User=baget", - ServerVersion.Parse("8.0.0-mysql")) - .Options; + // Parse rather than detect: detecting the version connects to the server, which + // would put the design-time tools back off line. + var options = new DbContextOptionsBuilder() + .UseMySql( + "Server=localhost;Database=baget;User=baget", + ServerVersion.Parse("8.0.0-mysql")) + .Options; - return new MySqlContext(options); - } + return new MySqlContext(options); } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.PostgreSql/PostgreSqlApplicationExtensions.cs b/src/BaGet.Database.PostgreSql/PostgreSqlApplicationExtensions.cs index 9268d3af6..f2098de0d 100644 --- a/src/BaGet.Database.PostgreSql/PostgreSqlApplicationExtensions.cs +++ b/src/BaGet.Database.PostgreSql/PostgreSqlApplicationExtensions.cs @@ -5,29 +5,28 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class PostgreSqlApplicationExtensions { - public static class PostgreSqlApplicationExtensions + public static BaGetApplication AddPostgreSqlDatabase(this BaGetApplication app) { - public static BaGetApplication AddPostgreSqlDatabase(this BaGetApplication app) + app.Services.AddBaGetDbContextProvider("PostgreSql", (provider, options) => { - app.Services.AddBaGetDbContextProvider("PostgreSql", (provider, options) => - { - var databaseOptions = provider.GetRequiredService>(); + var databaseOptions = provider.GetRequiredService>(); - options.UseNpgsql(databaseOptions.Value.ConnectionString); - }); + options.UseNpgsql(databaseOptions.Value.ConnectionString); + }); - return app; - } + return app; + } - public static BaGetApplication AddPostgreSqlDatabase( - this BaGetApplication app, - Action configure) - { - app.AddPostgreSqlDatabase(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddPostgreSqlDatabase( + this BaGetApplication app, + Action configure) + { + app.AddPostgreSqlDatabase(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.PostgreSql/PostgreSqlContext.cs b/src/BaGet.Database.PostgreSql/PostgreSqlContext.cs index c008e6cce..7ae9560d4 100644 --- a/src/BaGet.Database.PostgreSql/PostgreSqlContext.cs +++ b/src/BaGet.Database.PostgreSql/PostgreSqlContext.cs @@ -4,69 +4,68 @@ using Microsoft.EntityFrameworkCore; using Npgsql; -namespace BaGet.Database.PostgreSql +namespace BaGet.Database.PostgreSql; + +public class PostgreSqlContext : AbstractContext { - public class PostgreSqlContext : AbstractContext + /// + /// The PostgreSql error code for when a unique constraint is violated. + /// See: https://www.postgresql.org/docs/9.6/errcodes-appendix.html + /// + private const int UniqueConstraintViolationErrorCode = 23505; + + public PostgreSqlContext(DbContextOptions options) + : base(options) { - /// - /// The PostgreSql error code for when a unique constraint is violated. - /// See: https://www.postgresql.org/docs/9.6/errcodes-appendix.html - /// - private const int UniqueConstraintViolationErrorCode = 23505; + } - public PostgreSqlContext(DbContextOptions options) - : base(options) - { - } + public override bool IsUniqueConstraintViolationException(DbUpdateException exception) + { + return exception.InnerException is PostgresException postgresException && + int.TryParse(postgresException.SqlState, out var code) && + code == UniqueConstraintViolationErrorCode; + } - public override bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - return exception.InnerException is PostgresException postgresException && - int.TryParse(postgresException.SqlState, out var code) && - code == UniqueConstraintViolationErrorCode; - } + public override async Task RunMigrationsAsync(CancellationToken cancellationToken) + { + await base.RunMigrationsAsync(cancellationToken); - public override async Task RunMigrationsAsync(CancellationToken cancellationToken) + // Npgsql caches the database's type information on the initial connection. + // This causes issues when BaGet creates the database as it may add the citext + // extension to support case insensitive columns. + // See: https://github.com/loic-sharma/BaGet/issues/442 + // See: https://github.com/npgsql/efcore.pg/issues/170#issuecomment-303417225 + if (Database.GetDbConnection() is NpgsqlConnection connection) { - await base.RunMigrationsAsync(cancellationToken); - - // Npgsql caches the database's type information on the initial connection. - // This causes issues when BaGet creates the database as it may add the citext - // extension to support case insensitive columns. - // See: https://github.com/loic-sharma/BaGet/issues/442 - // See: https://github.com/npgsql/efcore.pg/issues/170#issuecomment-303417225 - if (Database.GetDbConnection() is NpgsqlConnection connection) - { - await connection.OpenAsync(cancellationToken); - connection.ReloadTypes(); - } + await connection.OpenAsync(cancellationToken); + connection.ReloadTypes(); } + } - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); - builder.HasPostgresExtension("citext"); + builder.HasPostgresExtension("citext"); - builder.Entity() - .Property(p => p.Id) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.Id) + .HasColumnType("citext"); - builder.Entity() - .Property(p => p.NormalizedVersionString) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.NormalizedVersionString) + .HasColumnType("citext"); - builder.Entity() - .Property(p => p.Id) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.Id) + .HasColumnType("citext"); - builder.Entity() - .Property(p => p.Name) - .HasColumnType("citext"); + builder.Entity() + .Property(p => p.Name) + .HasColumnType("citext"); - builder.Entity() - .Property(p => p.Moniker) - .HasColumnType("citext"); - } + builder.Entity() + .Property(p => p.Moniker) + .HasColumnType("citext"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.PostgreSql/PostgreSqlContextFactory.cs b/src/BaGet.Database.PostgreSql/PostgreSqlContextFactory.cs index c163ee66e..63d4c2341 100644 --- a/src/BaGet.Database.PostgreSql/PostgreSqlContextFactory.cs +++ b/src/BaGet.Database.PostgreSql/PostgreSqlContextFactory.cs @@ -1,26 +1,25 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; -namespace BaGet.Database.PostgreSql +namespace BaGet.Database.PostgreSql; + +/// +/// Builds a context for the Entity Framework design-time tools. +/// +/// +/// Without this the tools build the application's service provider to find the contexts, +/// which configures every database provider that is registered - including ones whose +/// server is unreachable or whose driver does not match the installed Entity Framework +/// version. A factory keeps "dotnet ef" offline and independent of the other providers. +/// +public class PostgreSqlContextFactory : IDesignTimeDbContextFactory { - /// - /// Builds a context for the Entity Framework design-time tools. - /// - /// - /// Without this the tools build the application's service provider to find the contexts, - /// which configures every database provider that is registered - including ones whose - /// server is unreachable or whose driver does not match the installed Entity Framework - /// version. A factory keeps "dotnet ef" offline and independent of the other providers. - /// - public class PostgreSqlContextFactory : IDesignTimeDbContextFactory + public PostgreSqlContext CreateDbContext(string[] args) { - public PostgreSqlContext CreateDbContext(string[] args) - { - var options = new DbContextOptionsBuilder() - .UseNpgsql("Host=localhost;Database=baget;Username=baget") - .Options; + var options = new DbContextOptionsBuilder() + .UseNpgsql("Host=localhost;Database=baget;Username=baget") + .Options; - return new PostgreSqlContext(options); - } + return new PostgreSqlContext(options); } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.SqlServer/SqlServerApplicationExtensions.cs b/src/BaGet.Database.SqlServer/SqlServerApplicationExtensions.cs index b2292e08e..4e0041948 100644 --- a/src/BaGet.Database.SqlServer/SqlServerApplicationExtensions.cs +++ b/src/BaGet.Database.SqlServer/SqlServerApplicationExtensions.cs @@ -5,29 +5,28 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class SqlServerApplicationExtensions { - public static class SqlServerApplicationExtensions + public static BaGetApplication AddSqlServerDatabase(this BaGetApplication app) { - public static BaGetApplication AddSqlServerDatabase(this BaGetApplication app) + app.Services.AddBaGetDbContextProvider("SqlServer", (provider, options) => { - app.Services.AddBaGetDbContextProvider("SqlServer", (provider, options) => - { - var databaseOptions = provider.GetRequiredService>(); + var databaseOptions = provider.GetRequiredService>(); - options.UseSqlServer(databaseOptions.Value.ConnectionString); - }); + options.UseSqlServer(databaseOptions.Value.ConnectionString); + }); - return app; - } + return app; + } - public static BaGetApplication AddSqlServerDatabase( - this BaGetApplication app, - Action configure) - { - app.AddSqlServerDatabase(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddSqlServerDatabase( + this BaGetApplication app, + Action configure) + { + app.AddSqlServerDatabase(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.SqlServer/SqlServerContext.cs b/src/BaGet.Database.SqlServer/SqlServerContext.cs index 3639b8cad..406881dc1 100644 --- a/src/BaGet.Database.SqlServer/SqlServerContext.cs +++ b/src/BaGet.Database.SqlServer/SqlServerContext.cs @@ -3,34 +3,33 @@ using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; -namespace BaGet.Database.SqlServer +namespace BaGet.Database.SqlServer; + +public class SqlServerContext : AbstractContext { - public class SqlServerContext : AbstractContext - { - /// - /// The SQL Server error code for when a unique contraint is violated. - /// - private const int UniqueConstraintViolationErrorCode = 2627; + /// + /// The SQL Server error code for when a unique contraint is violated. + /// + private const int UniqueConstraintViolationErrorCode = 2627; - public SqlServerContext(DbContextOptions options) - : base(options) - { } + public SqlServerContext(DbContextOptions options) + : base(options) + { } - /// - /// Check whether a is due to a SQL unique constraint violation. - /// - /// The exception to inspect. - /// Whether the exception was caused to SQL unique constraint violation. - public override bool IsUniqueConstraintViolationException(DbUpdateException exception) + /// + /// Check whether a is due to a SQL unique constraint violation. + /// + /// The exception to inspect. + /// Whether the exception was caused to SQL unique constraint violation. + public override bool IsUniqueConstraintViolationException(DbUpdateException exception) + { + if (exception.GetBaseException() is SqlException sqlException) { - if (exception.GetBaseException() is SqlException sqlException) - { - return sqlException.Errors - .OfType() - .Any(error => error.Number == UniqueConstraintViolationErrorCode); - } - - return false; + return sqlException.Errors + .OfType() + .Any(error => error.Number == UniqueConstraintViolationErrorCode); } + + return false; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.SqlServer/SqlServerContextFactory.cs b/src/BaGet.Database.SqlServer/SqlServerContextFactory.cs index 0a2cda462..13cf560b4 100644 --- a/src/BaGet.Database.SqlServer/SqlServerContextFactory.cs +++ b/src/BaGet.Database.SqlServer/SqlServerContextFactory.cs @@ -1,26 +1,25 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; -namespace BaGet.Database.SqlServer +namespace BaGet.Database.SqlServer; + +/// +/// Builds a context for the Entity Framework design-time tools. +/// +/// +/// Without this the tools build the application's service provider to find the contexts, +/// which configures every database provider that is registered - including ones whose +/// server is unreachable or whose driver does not match the installed Entity Framework +/// version. A factory keeps "dotnet ef" offline and independent of the other providers. +/// +public class SqlServerContextFactory : IDesignTimeDbContextFactory { - /// - /// Builds a context for the Entity Framework design-time tools. - /// - /// - /// Without this the tools build the application's service provider to find the contexts, - /// which configures every database provider that is registered - including ones whose - /// server is unreachable or whose driver does not match the installed Entity Framework - /// version. A factory keeps "dotnet ef" offline and independent of the other providers. - /// - public class SqlServerContextFactory : IDesignTimeDbContextFactory + public SqlServerContext CreateDbContext(string[] args) { - public SqlServerContext CreateDbContext(string[] args) - { - var options = new DbContextOptionsBuilder() - .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=BaGet") - .Options; + var options = new DbContextOptionsBuilder() + .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=BaGet") + .Options; - return new SqlServerContext(options); - } + return new SqlServerContext(options); } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.Sqlite/SqliteApplicationExtensions.cs b/src/BaGet.Database.Sqlite/SqliteApplicationExtensions.cs index 34e3a91e1..479681eac 100644 --- a/src/BaGet.Database.Sqlite/SqliteApplicationExtensions.cs +++ b/src/BaGet.Database.Sqlite/SqliteApplicationExtensions.cs @@ -5,29 +5,28 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public static class SqliteApplicationExtensions { - public static class SqliteApplicationExtensions + public static BaGetApplication AddSqliteDatabase(this BaGetApplication app) { - public static BaGetApplication AddSqliteDatabase(this BaGetApplication app) + app.Services.AddBaGetDbContextProvider("Sqlite", (provider, options) => { - app.Services.AddBaGetDbContextProvider("Sqlite", (provider, options) => - { - var databaseOptions = provider.GetRequiredService>(); + var databaseOptions = provider.GetRequiredService>(); - options.UseSqlite(databaseOptions.Value.ConnectionString); - }); + options.UseSqlite(databaseOptions.Value.ConnectionString); + }); - return app; - } + return app; + } - public static BaGetApplication AddSqliteDatabase( - this BaGetApplication app, - Action configure) - { - app.AddSqliteDatabase(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddSqliteDatabase( + this BaGetApplication app, + Action configure) + { + app.AddSqliteDatabase(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.Sqlite/SqliteContext.cs b/src/BaGet.Database.Sqlite/SqliteContext.cs index 974ae587b..bbc4a00d3 100644 --- a/src/BaGet.Database.Sqlite/SqliteContext.cs +++ b/src/BaGet.Database.Sqlite/SqliteContext.cs @@ -2,48 +2,47 @@ using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; -namespace BaGet.Database.Sqlite +namespace BaGet.Database.Sqlite; + +public class SqliteContext : AbstractContext { - public class SqliteContext : AbstractContext + /// + /// The Sqlite error code for when a unique constraint is violated. + /// + private const int SqliteUniqueConstraintViolationErrorCode = 19; + + public SqliteContext(DbContextOptions options) + : base(options) + { } + + public override bool IsUniqueConstraintViolationException(DbUpdateException exception) + { + return exception.InnerException is SqliteException sqliteException && + sqliteException.SqliteErrorCode == SqliteUniqueConstraintViolationErrorCode; + } + + protected override void OnModelCreating(ModelBuilder builder) { - /// - /// The Sqlite error code for when a unique constraint is violated. - /// - private const int SqliteUniqueConstraintViolationErrorCode = 19; - - public SqliteContext(DbContextOptions options) - : base(options) - { } - - public override bool IsUniqueConstraintViolationException(DbUpdateException exception) - { - return exception.InnerException is SqliteException sqliteException && - sqliteException.SqliteErrorCode == SqliteUniqueConstraintViolationErrorCode; - } - - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - builder.Entity() - .Property(p => p.Id) - .HasColumnType("TEXT COLLATE NOCASE"); - - builder.Entity() - .Property(p => p.NormalizedVersionString) - .HasColumnType("TEXT COLLATE NOCASE"); - - builder.Entity() - .Property(d => d.Id) - .HasColumnType("TEXT COLLATE NOCASE"); - - builder.Entity() - .Property(t => t.Name) - .HasColumnType("TEXT COLLATE NOCASE"); - - builder.Entity() - .Property(f => f.Moniker) - .HasColumnType("TEXT COLLATE NOCASE"); - } + base.OnModelCreating(builder); + + builder.Entity() + .Property(p => p.Id) + .HasColumnType("TEXT COLLATE NOCASE"); + + builder.Entity() + .Property(p => p.NormalizedVersionString) + .HasColumnType("TEXT COLLATE NOCASE"); + + builder.Entity() + .Property(d => d.Id) + .HasColumnType("TEXT COLLATE NOCASE"); + + builder.Entity() + .Property(t => t.Name) + .HasColumnType("TEXT COLLATE NOCASE"); + + builder.Entity() + .Property(f => f.Moniker) + .HasColumnType("TEXT COLLATE NOCASE"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Database.Sqlite/SqliteContextFactory.cs b/src/BaGet.Database.Sqlite/SqliteContextFactory.cs index 2ad0c7ec9..27624618c 100644 --- a/src/BaGet.Database.Sqlite/SqliteContextFactory.cs +++ b/src/BaGet.Database.Sqlite/SqliteContextFactory.cs @@ -1,26 +1,25 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; -namespace BaGet.Database.Sqlite +namespace BaGet.Database.Sqlite; + +/// +/// Builds a context for the Entity Framework design-time tools. +/// +/// +/// Without this the tools build the application's service provider to find the contexts, +/// which configures every database provider that is registered - including ones whose +/// server is unreachable or whose driver does not match the installed Entity Framework +/// version. A factory keeps "dotnet ef" offline and independent of the other providers. +/// +public class SqliteContextFactory : IDesignTimeDbContextFactory { - /// - /// Builds a context for the Entity Framework design-time tools. - /// - /// - /// Without this the tools build the application's service provider to find the contexts, - /// which configures every database provider that is registered - including ones whose - /// server is unreachable or whose driver does not match the installed Entity Framework - /// version. A factory keeps "dotnet ef" offline and independent of the other providers. - /// - public class SqliteContextFactory : IDesignTimeDbContextFactory + public SqliteContext CreateDbContext(string[] args) { - public SqliteContext CreateDbContext(string[] args) - { - var options = new DbContextOptionsBuilder() - .UseSqlite("Data Source=baget.db") - .Options; + var options = new DbContextOptionsBuilder() + .UseSqlite("Data Source=baget.db") + .Options; - return new SqliteContext(options); - } + return new SqliteContext(options); } -} +} \ No newline at end of file diff --git a/src/BaGet.Gcp/GoogleCloudApplicationExtensions.cs b/src/BaGet.Gcp/GoogleCloudApplicationExtensions.cs index 5dcb1bb8a..20ae72017 100644 --- a/src/BaGet.Gcp/GoogleCloudApplicationExtensions.cs +++ b/src/BaGet.Gcp/GoogleCloudApplicationExtensions.cs @@ -4,34 +4,33 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet +namespace BaGet; + +public static class GoogleCloudApplicationExtensions { - public static class GoogleCloudApplicationExtensions + public static BaGetApplication AddGoogleCloudStorage(this BaGetApplication app) { - public static BaGetApplication AddGoogleCloudStorage(this BaGetApplication app) - { - app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); - app.Services.AddTransient(); + app.Services.AddBaGetOptions(nameof(BaGetOptions.Storage)); + app.Services.AddTransient(); - app.Services.TryAddTransient(provider => provider.GetRequiredService()); + app.Services.TryAddTransient(provider => provider.GetRequiredService()); - app.Services.AddProvider((provider, config) => - { - if (!config.HasStorageType("GoogleCloud")) return null; + app.Services.AddProvider((provider, config) => + { + if (!config.HasStorageType("GoogleCloud")) return null; - return provider.GetRequiredService(); - }); + return provider.GetRequiredService(); + }); - return app; - } + return app; + } - public static BaGetApplication AddGoogleCloudStorage( - this BaGetApplication app, - Action configure) - { - app.AddGoogleCloudStorage(); - app.Services.Configure(configure); - return app; - } + public static BaGetApplication AddGoogleCloudStorage( + this BaGetApplication app, + Action configure) + { + app.AddGoogleCloudStorage(); + app.Services.Configure(configure); + return app; } -} +} \ No newline at end of file diff --git a/src/BaGet.Gcp/GoogleCloudStorageOptions.cs b/src/BaGet.Gcp/GoogleCloudStorageOptions.cs index 6b9a2ff42..9c847e234 100644 --- a/src/BaGet.Gcp/GoogleCloudStorageOptions.cs +++ b/src/BaGet.Gcp/GoogleCloudStorageOptions.cs @@ -1,11 +1,10 @@ using System.ComponentModel.DataAnnotations; using BaGet.Core; -namespace BaGet.Gcp +namespace BaGet.Gcp; + +public class GoogleCloudStorageOptions : StorageOptions { - public class GoogleCloudStorageOptions : StorageOptions - { - [Required] - public string BucketName { get; set; } - } -} + [Required] + public string BucketName { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Gcp/GoogleCloudStorageService.cs b/src/BaGet.Gcp/GoogleCloudStorageService.cs index afdc84ff3..577e7b7d1 100644 --- a/src/BaGet.Gcp/GoogleCloudStorageService.cs +++ b/src/BaGet.Gcp/GoogleCloudStorageService.cs @@ -11,114 +11,113 @@ using Google.Cloud.Storage.V1; using Microsoft.Extensions.Options; -namespace BaGet.Gcp +namespace BaGet.Gcp; + +public class GoogleCloudStorageService : IStorageService, IListableStorageService { - public class GoogleCloudStorageService : IStorageService, IListableStorageService - { - private readonly string _bucketName; + private readonly string _bucketName; - public GoogleCloudStorageService(IOptionsSnapshot options) - { - if (options == null) - throw new ArgumentNullException(nameof(options)); + public GoogleCloudStorageService(IOptionsSnapshot options) + { + if (options == null) + throw new ArgumentNullException(nameof(options)); - _bucketName = options.Value.BucketName; - } + _bucketName = options.Value.BucketName; + } - public async Task GetAsync(string path, CancellationToken cancellationToken = default) + public async Task GetAsync(string path, CancellationToken cancellationToken = default) + { + using (var storage = await StorageClient.CreateAsync()) { - using (var storage = await StorageClient.CreateAsync()) - { - var stream = new MemoryStream(); - await storage.DownloadObjectAsync(_bucketName, CoercePath(path), stream, cancellationToken: cancellationToken); - stream.Position = 0; - return stream; - } + var stream = new MemoryStream(); + await storage.DownloadObjectAsync(_bucketName, CoercePath(path), stream, cancellationToken: cancellationToken); + stream.Position = 0; + return stream; } + } - public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) - { - // returns an Authenticated Browser Download URL: https://cloud.google.com/storage/docs/request-endpoints#cookieauth - return Task.FromResult(new Uri($"https://storage.googleapis.com/{_bucketName}/{CoercePath(path).TrimStart('/')}")); - } + public Task GetDownloadUriAsync(string path, CancellationToken cancellationToken = default) + { + // returns an Authenticated Browser Download URL: https://cloud.google.com/storage/docs/request-endpoints#cookieauth + return Task.FromResult(new Uri($"https://storage.googleapis.com/{_bucketName}/{CoercePath(path).TrimStart('/')}")); + } - public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + public async Task PutAsync(string path, Stream content, string contentType, CancellationToken cancellationToken = default) + { + using (var storage = await StorageClient.CreateAsync()) + using (var seekableContent = new MemoryStream()) { - using (var storage = await StorageClient.CreateAsync()) - using (var seekableContent = new MemoryStream()) + await content.CopyToAsync(seekableContent, 65536, cancellationToken); + seekableContent.Position = 0; + + var objectName = CoercePath(path); + + try { - await content.CopyToAsync(seekableContent, 65536, cancellationToken); + // attempt to upload, succeeding only if the object doesn't exist + await storage.UploadObjectAsync(_bucketName, objectName, contentType, seekableContent, new UploadObjectOptions { IfGenerationMatch = 0 }, cancellationToken); + return StoragePutResult.Success; + } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.PreconditionFailed) + { + // the object already exists; get the hash of its content from its metadata + var existingObject = await storage.GetObjectAsync(_bucketName, objectName, cancellationToken: cancellationToken); + var existingHash = Convert.FromBase64String(existingObject.Md5Hash); + + // hash the content that was uploaded seekableContent.Position = 0; + byte[] contentHash; + using (var md5 = MD5.Create()) + contentHash = md5.ComputeHash(seekableContent); - var objectName = CoercePath(path); - - try - { - // attempt to upload, succeeding only if the object doesn't exist - await storage.UploadObjectAsync(_bucketName, objectName, contentType, seekableContent, new UploadObjectOptions { IfGenerationMatch = 0 }, cancellationToken); - return StoragePutResult.Success; - } - catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.PreconditionFailed) - { - // the object already exists; get the hash of its content from its metadata - var existingObject = await storage.GetObjectAsync(_bucketName, objectName, cancellationToken: cancellationToken); - var existingHash = Convert.FromBase64String(existingObject.Md5Hash); - - // hash the content that was uploaded - seekableContent.Position = 0; - byte[] contentHash; - using (var md5 = MD5.Create()) - contentHash = md5.ComputeHash(seekableContent); - - // conflict if the two hashes are different - return existingHash.SequenceEqual(contentHash) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict; - } + // conflict if the two hashes are different + return existingHash.SequenceEqual(contentHash) ? StoragePutResult.AlreadyExists : StoragePutResult.Conflict; } } + } - public async Task DeleteAsync(string path, CancellationToken cancellationToken = default) + public async Task DeleteAsync(string path, CancellationToken cancellationToken = default) + { + using (var storage = await StorageClient.CreateAsync()) { - using (var storage = await StorageClient.CreateAsync()) + try + { + var obj = await storage.GetObjectAsync(_bucketName, CoercePath(path), cancellationToken: cancellationToken); + await storage.DeleteObjectAsync(obj, cancellationToken: cancellationToken); + } + catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) { - try - { - var obj = await storage.GetObjectAsync(_bucketName, CoercePath(path), cancellationToken: cancellationToken); - await storage.DeleteObjectAsync(obj, cancellationToken: cancellationToken); - } - catch (GoogleApiException e) when (e.HttpStatusCode == HttpStatusCode.NotFound) - { - } } } + } - /// - /// Every object under a prefix. The sweep of abandoned staged uploads is the only - /// caller, and without this a bucket would keep them forever. - /// - public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) - { - // A prefix is a path segment, not a string prefix: "staging" must not also match - // "staging-archive/...". - var prefix = CoercePath(pathPrefix).TrimEnd('/') + "/"; - var paths = new List(); + /// + /// Every object under a prefix. The sweep of abandoned staged uploads is the only + /// caller, and without this a bucket would keep them forever. + /// + public async Task> ListAsync(string pathPrefix, CancellationToken cancellationToken = default) + { + // A prefix is a path segment, not a string prefix: "staging" must not also match + // "staging-archive/...". + var prefix = CoercePath(pathPrefix).TrimEnd('/') + "/"; + var paths = new List(); - using (var storage = await StorageClient.CreateAsync()) + using (var storage = await StorageClient.CreateAsync()) + { + // The object's name is already the path IStorageService takes. + await foreach (var item in storage.ListObjectsAsync(_bucketName, prefix).WithCancellation(cancellationToken)) { - // The object's name is already the path IStorageService takes. - await foreach (var item in storage.ListObjectsAsync(_bucketName, prefix).WithCancellation(cancellationToken)) - { - paths.Add(item.Name); - } + paths.Add(item.Name); } - - return paths; } - private static string CoercePath(string path) - { - // although Google Cloud Storage objects exist in a flat namespace, using forward slashes allows the objects to - // be exposed as nested subdirectories, e.g., when browsing via Google Cloud Console - return path.Replace('\\', '/'); - } + return paths; + } + + private static string CoercePath(string path) + { + // although Google Cloud Storage objects exist in a flat namespace, using forward slashes allows the objects to + // be exposed as nested subdirectories, e.g., when browsing via Google Cloud Console + return path.Replace('\\', '/'); } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/AccountAuthenticationService.cs b/src/BaGet.Identity/AccountAuthenticationService.cs index fbc7bacdb..5e044f770 100644 --- a/src/BaGet.Identity/AccountAuthenticationService.cs +++ b/src/BaGet.Identity/AccountAuthenticationService.cs @@ -5,59 +5,58 @@ using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; -namespace BaGet.Identity +namespace BaGet.Identity; + +/// +/// The global API key, as before, plus users' own keys. +/// +public class AccountAuthenticationService : Core.IAuthenticationService { - /// - /// The global API key, as before, plus users' own keys. - /// - public class AccountAuthenticationService : Core.IAuthenticationService + private readonly ApiKeyAuthenticationService _globalKey; + private readonly ApiKeyService _apiKeys; + private readonly UserManager _users; + private readonly IOptionsSnapshot _options; + + public AccountAuthenticationService( + ApiKeyAuthenticationService globalKey, + ApiKeyService apiKeys, + UserManager users, + IOptionsSnapshot options) { - private readonly ApiKeyAuthenticationService _globalKey; - private readonly ApiKeyService _apiKeys; - private readonly UserManager _users; - private readonly IOptionsSnapshot _options; - - public AccountAuthenticationService( - ApiKeyAuthenticationService globalKey, - ApiKeyService apiKeys, - UserManager users, - IOptionsSnapshot options) - { - _globalKey = globalKey ?? throw new ArgumentNullException(nameof(globalKey)); - _apiKeys = apiKeys ?? throw new ArgumentNullException(nameof(apiKeys)); - _users = users ?? throw new ArgumentNullException(nameof(users)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - } + _globalKey = globalKey ?? throw new ArgumentNullException(nameof(globalKey)); + _apiKeys = apiKeys ?? throw new ArgumentNullException(nameof(apiKeys)); + _users = users ?? throw new ArgumentNullException(nameof(users)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + } - public async Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken) - => await AuthenticatePrincipalAsync(apiKey, cancellationToken) != null; + public async Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken) + => await AuthenticatePrincipalAsync(apiKey, cancellationToken) != null; - public async Task AuthenticatePrincipalAsync(string apiKey, CancellationToken cancellationToken) + public async Task AuthenticatePrincipalAsync(string apiKey, CancellationToken cancellationToken) + { + // The global key is the superuser, as it always was - but only when one is + // configured. An empty ApiKey means "there is no global key", never "every + // caller is the superuser": enabling accounts is asking for ownership to decide + // who may push what, and a superuser principal skips ownership entirely, so + // treating the open-server default as a free pass would make the ownership gate + // bypassable by simply sending no key at all. + if (!string.IsNullOrEmpty(_options.Value.ApiKey) + && await _globalKey.AuthenticateAsync(apiKey, cancellationToken)) { - // The global key is the superuser, as it always was - but only when one is - // configured. An empty ApiKey means "there is no global key", never "every - // caller is the superuser": enabling accounts is asking for ownership to decide - // who may push what, and a superuser principal skips ownership entirely, so - // treating the open-server default as a free pass would make the ownership gate - // bypassable by simply sending no key at all. - if (!string.IsNullOrEmpty(_options.Value.ApiKey) - && await _globalKey.AuthenticateAsync(apiKey, cancellationToken)) - { - return BaGetPrincipal.Superuser; - } - - var key = await _apiKeys.FindValidOrNullAsync(apiKey, cancellationToken); - if (key == null) return null; - - var user = await _users.FindByIdAsync(key.UserId); - if (user == null) return null; - - return new BaGetPrincipal( - user.Id, - user.UserName, - isSuperuser: false, - key.Scopes, - key.PackageGlobPattern); + return BaGetPrincipal.Superuser; } + + var key = await _apiKeys.FindValidOrNullAsync(apiKey, cancellationToken); + if (key == null) return null; + + var user = await _users.FindByIdAsync(key.UserId); + if (user == null) return null; + + return new BaGetPrincipal( + user.Id, + user.UserName, + isSuperuser: false, + key.Scopes, + key.PackageGlobPattern); } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/AccountsServiceCollectionExtensions.cs b/src/BaGet.Identity/AccountsServiceCollectionExtensions.cs index fe4e65eaf..b2d46423c 100644 --- a/src/BaGet.Identity/AccountsServiceCollectionExtensions.cs +++ b/src/BaGet.Identity/AccountsServiceCollectionExtensions.cs @@ -6,72 +6,71 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet.Identity +namespace BaGet.Identity; + +public static class AccountsServiceCollectionExtensions { - public static class AccountsServiceCollectionExtensions + public const string OpenIdConnectScheme = "oidc"; + + /// + /// Add accounts if "Accounts:Enabled" is set. Otherwise only an empty authentication + /// setup is added, so the pipeline's authentication middleware has nothing to do. + /// + public static IServiceCollection AddBaGetAccounts(this IServiceCollection services, IConfiguration configuration) { - public const string OpenIdConnectScheme = "oidc"; + var options = configuration.GetSection(nameof(BaGetOptions.Accounts)).Get() + ?? new AccountsOptions(); - /// - /// Add accounts if "Accounts:Enabled" is set. Otherwise only an empty authentication - /// setup is added, so the pipeline's authentication middleware has nothing to do. - /// - public static IServiceCollection AddBaGetAccounts(this IServiceCollection services, IConfiguration configuration) + if (!options.Enabled) { - var options = configuration.GetSection(nameof(BaGetOptions.Accounts)).Get() - ?? new AccountsOptions(); - - if (!options.Enabled) - { - services.AddAuthentication(); - return services; - } - - services.TryAddScoped(); - services.TryAddScoped(); - services.TryAddScoped(); - services.TryAddTransient(); - services.Replace(ServiceDescriptor.Transient()); - services.Replace(ServiceDescriptor.Transient()); + services.AddAuthentication(); + return services; + } - // The context is chosen per database provider at runtime, so Identity's EF stores - // are given whichever one was resolved rather than a context type. - services.TryAddScoped>(provider => - new UserStore( - (DbContext)provider.GetRequiredService())); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddTransient(); + services.Replace(ServiceDescriptor.Transient()); + services.Replace(ServiceDescriptor.Transient()); - services - .AddIdentityCore(identity => - { - identity.User.RequireUniqueEmail = false; - identity.Lockout.AllowedForNewUsers = true; - }) - .AddSignInManager() - .AddDefaultTokenProviders(); + // The context is chosen per database provider at runtime, so Identity's EF stores + // are given whichever one was resolved rather than a context type. + services.TryAddScoped>(provider => + new UserStore( + (DbContext)provider.GetRequiredService())); - var authentication = services.AddAuthentication(IdentityConstants.ApplicationScheme); - authentication.AddIdentityCookies(cookies => cookies.ApplicationCookie.Configure(cookie => + services + .AddIdentityCore(identity => { - cookie.LoginPath = "/account/login"; - cookie.LogoutPath = "/account/logout"; - cookie.AccessDeniedPath = "/account/login"; - })); + identity.User.RequireUniqueEmail = false; + identity.Lockout.AllowedForNewUsers = true; + }) + .AddSignInManager() + .AddDefaultTokenProviders(); - if (options.OpenIdConnect.IsConfigured) - { - authentication.AddOpenIdConnect(OpenIdConnectScheme, options.OpenIdConnect.DisplayName, oidc => - { - oidc.SignInScheme = IdentityConstants.ExternalScheme; - oidc.Authority = options.OpenIdConnect.Authority; - oidc.ClientId = options.OpenIdConnect.ClientId; - oidc.ClientSecret = options.OpenIdConnect.ClientSecret; - oidc.ResponseType = "code"; - oidc.Scope.Add("profile"); - oidc.Scope.Add("email"); - }); - } + var authentication = services.AddAuthentication(IdentityConstants.ApplicationScheme); + authentication.AddIdentityCookies(cookies => cookies.ApplicationCookie.Configure(cookie => + { + cookie.LoginPath = "/account/login"; + cookie.LogoutPath = "/account/logout"; + cookie.AccessDeniedPath = "/account/login"; + })); - return services; + if (options.OpenIdConnect.IsConfigured) + { + authentication.AddOpenIdConnect(OpenIdConnectScheme, options.OpenIdConnect.DisplayName, oidc => + { + oidc.SignInScheme = IdentityConstants.ExternalScheme; + oidc.Authority = options.OpenIdConnect.Authority; + oidc.ClientId = options.OpenIdConnect.ClientId; + oidc.ClientSecret = options.OpenIdConnect.ClientSecret; + oidc.ResponseType = "code"; + oidc.Scope.Add("profile"); + oidc.Scope.Add("email"); + }); } + + return services; } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/ApiKeyService.cs b/src/BaGet.Identity/ApiKeyService.cs index e00d6786d..4b4df8c08 100644 --- a/src/BaGet.Identity/ApiKeyService.cs +++ b/src/BaGet.Identity/ApiKeyService.cs @@ -8,118 +8,117 @@ using BaGet.Core; using Microsoft.EntityFrameworkCore; -namespace BaGet.Identity +namespace BaGet.Identity; + +/// +/// Creates, lists and revokes users' API keys. A key is shown once, when it is created; +/// only its hash is stored. +/// +public class ApiKeyService { /// - /// Creates, lists and revokes users' API keys. A key is shown once, when it is created; - /// only its hash is stored. + /// Marks a BaGet key, so a leaked one is recognisable by secret scanners. /// - public class ApiKeyService + internal const string KeyPrefix = "bgt_"; + + private readonly IContext _context; + private readonly SystemTime _time; + + public ApiKeyService(IContext context, SystemTime time) { - /// - /// Marks a BaGet key, so a leaked one is recognisable by secret scanners. - /// - internal const string KeyPrefix = "bgt_"; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } - private readonly IContext _context; - private readonly SystemTime _time; + /// + /// Create a key and return it in plain text. It cannot be recovered afterwards. + /// + public async Task CreateAsync( + string userId, + string description, + IReadOnlyList scopes, + string packageGlobPattern, + DateTime? expires, + CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(userId)) throw new ArgumentException("A user is required.", nameof(userId)); - public ApiKeyService(IContext context, SystemTime time) + var unknown = scopes?.FirstOrDefault(s => !ApiKeyScopes.All.Contains(s, StringComparer.Ordinal)); + if (scopes == null || scopes.Count == 0 || unknown != null) { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _time = time ?? throw new ArgumentNullException(nameof(time)); + throw new ArgumentException($"Scopes must be some of: {string.Join(", ", ApiKeyScopes.All)}.", nameof(scopes)); } - /// - /// Create a key and return it in plain text. It cannot be recovered afterwards. - /// - public async Task CreateAsync( - string userId, - string description, - IReadOnlyList scopes, - string packageGlobPattern, - DateTime? expires, - CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(userId)) throw new ArgumentException("A user is required.", nameof(userId)); - - var unknown = scopes?.FirstOrDefault(s => !ApiKeyScopes.All.Contains(s, StringComparer.Ordinal)); - if (scopes == null || scopes.Count == 0 || unknown != null) - { - throw new ArgumentException($"Scopes must be some of: {string.Join(", ", ApiKeyScopes.All)}.", nameof(scopes)); - } - - var key = KeyPrefix + Base64Url(RandomNumberGenerator.GetBytes(32)); - - _context.ApiKeys.Add(new ApiKey - { - UserId = userId, - Description = description, - HashedKey = Hash(key), - Scopes = scopes.Distinct(StringComparer.Ordinal).ToArray(), - PackageGlobPattern = string.IsNullOrWhiteSpace(packageGlobPattern) ? "*" : packageGlobPattern.Trim(), - Created = _time.UtcNow, - Expires = expires?.ToUniversalTime(), - }); - - await _context.SaveChangesAsync(cancellationToken); - - return key; - } + var key = KeyPrefix + Base64Url(RandomNumberGenerator.GetBytes(32)); - public async Task> ListAsync(string userId, CancellationToken cancellationToken) + _context.ApiKeys.Add(new ApiKey { - return await _context.ApiKeys - .AsNoTracking() - .Where(k => k.UserId == userId) - .OrderBy(k => k.Key) - .ToListAsync(cancellationToken); - } + UserId = userId, + Description = description, + HashedKey = Hash(key), + Scopes = scopes.Distinct(StringComparer.Ordinal).ToArray(), + PackageGlobPattern = string.IsNullOrWhiteSpace(packageGlobPattern) ? "*" : packageGlobPattern.Trim(), + Created = _time.UtcNow, + Expires = expires?.ToUniversalTime(), + }); + + await _context.SaveChangesAsync(cancellationToken); + + return key; + } - /// - /// Revoke one of the user's keys. False if the user has no such key. - /// - public async Task RevokeAsync(string userId, int key, CancellationToken cancellationToken) - { - var apiKey = await _context.ApiKeys.FirstOrDefaultAsync(k => k.Key == key && k.UserId == userId, cancellationToken); - if (apiKey == null) return false; + public async Task> ListAsync(string userId, CancellationToken cancellationToken) + { + return await _context.ApiKeys + .AsNoTracking() + .Where(k => k.UserId == userId) + .OrderBy(k => k.Key) + .ToListAsync(cancellationToken); + } - _context.ApiKeys.Remove(apiKey); - await _context.SaveChangesAsync(cancellationToken); + /// + /// Revoke one of the user's keys. False if the user has no such key. + /// + public async Task RevokeAsync(string userId, int key, CancellationToken cancellationToken) + { + var apiKey = await _context.ApiKeys.FirstOrDefaultAsync(k => k.Key == key && k.UserId == userId, cancellationToken); + if (apiKey == null) return false; - return true; - } + _context.ApiKeys.Remove(apiKey); + await _context.SaveChangesAsync(cancellationToken); - /// - /// The stored key that matches, if it exists and has not expired. - /// - public async Task FindValidOrNullAsync(string key, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(key) || !key.StartsWith(KeyPrefix, StringComparison.Ordinal)) return null; + return true; + } - var hash = Hash(key); - var apiKey = await _context.ApiKeys - .AsNoTracking() - .FirstOrDefaultAsync(k => k.HashedKey == hash, cancellationToken); + /// + /// The stored key that matches, if it exists and has not expired. + /// + public async Task FindValidOrNullAsync(string key, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(key) || !key.StartsWith(KeyPrefix, StringComparison.Ordinal)) return null; - if (apiKey == null) return null; - if (apiKey.Expires.HasValue && DateTime.SpecifyKind(apiKey.Expires.Value, DateTimeKind.Utc) <= _time.UtcNow) return null; + var hash = Hash(key); + var apiKey = await _context.ApiKeys + .AsNoTracking() + .FirstOrDefaultAsync(k => k.HashedKey == hash, cancellationToken); - return apiKey; - } + if (apiKey == null) return null; + if (apiKey.Expires.HasValue && DateTime.SpecifyKind(apiKey.Expires.Value, DateTimeKind.Utc) <= _time.UtcNow) return null; - /// - /// A key is 256 random bits, so a fast unsalted hash is enough: there is nothing - /// to brute force, and the lookup by hash must be exact. - /// - internal static string Hash(string key) - { - var hash = SHA256.HashData(Encoding.UTF8.GetBytes(key)); + return apiKey; + } - return Convert.ToHexString(hash).ToLowerInvariant(); - } + /// + /// A key is 256 random bits, so a fast unsalted hash is enough: there is nothing + /// to brute force, and the lookup by hash must be exact. + /// + internal static string Hash(string key) + { + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(key)); - private static string Base64Url(byte[] bytes) - => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + return Convert.ToHexString(hash).ToLowerInvariant(); } -} + + private static string Base64Url(byte[] bytes) + => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); +} \ No newline at end of file diff --git a/src/BaGet.Identity/OwnershipAuthorizationService.cs b/src/BaGet.Identity/OwnershipAuthorizationService.cs index 02e5226f3..9150ca3d1 100644 --- a/src/BaGet.Identity/OwnershipAuthorizationService.cs +++ b/src/BaGet.Identity/OwnershipAuthorizationService.cs @@ -4,84 +4,83 @@ using BaGet.Core; using Microsoft.Extensions.Logging; -namespace BaGet.Identity +namespace BaGet.Identity; + +/// +/// Package ownership rules, as nuget.org applies them: +/// +/// The superuser may do anything. +/// A key acts only within its scopes and its package glob. +/// Pushing a new package ID needs , and makes the +/// pusher its owner. +/// Anything else needs the user to own the ID, directly or through an +/// organization. +/// An ID that already exists but has no owners predates accounts, and only the +/// superuser may change it, so nothing becomes inaccessible on upgrade. +/// +/// +public class OwnershipAuthorizationService : IPackageAuthorizationService { - /// - /// Package ownership rules, as nuget.org applies them: - /// - /// The superuser may do anything. - /// A key acts only within its scopes and its package glob. - /// Pushing a new package ID needs , and makes the - /// pusher its owner. - /// Anything else needs the user to own the ID, directly or through an - /// organization. - /// An ID that already exists but has no owners predates accounts, and only the - /// superuser may change it, so nothing becomes inaccessible on upgrade. - /// - /// - public class OwnershipAuthorizationService : IPackageAuthorizationService - { - private readonly PackageOwnershipService _ownership; - private readonly IPackageDatabase _packages; - private readonly ILogger _logger; + private readonly PackageOwnershipService _ownership; + private readonly IPackageDatabase _packages; + private readonly ILogger _logger; - public OwnershipAuthorizationService( - PackageOwnershipService ownership, - IPackageDatabase packages, - ILogger logger) - { - _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public OwnershipAuthorizationService( + PackageOwnershipService ownership, + IPackageDatabase packages, + ILogger logger) + { + _ownership = ownership ?? throw new ArgumentNullException(nameof(ownership)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task AuthorizeAsync( - BaGetPrincipal principal, - PackageAction action, - string packageId, - CancellationToken cancellationToken) - { - if (principal == null) return false; - if (principal.IsSuperuser) return true; - if (!principal.MatchesPackage(packageId)) return false; + public async Task AuthorizeAsync( + BaGetPrincipal principal, + PackageAction action, + string packageId, + CancellationToken cancellationToken) + { + if (principal == null) return false; + if (principal.IsSuperuser) return true; + if (!principal.MatchesPackage(packageId)) return false; - var isOwner = await _ownership.IsOwnerAsync(principal.UserId, principal.UserName, packageId, cancellationToken); + var isOwner = await _ownership.IsOwnerAsync(principal.UserId, principal.UserName, packageId, cancellationToken); - switch (action) - { - case PackageAction.Push: - if (isOwner) - { - return principal.HasScope(ApiKeyScopes.Push) || principal.HasScope(ApiKeyScopes.PushVersion); - } + switch (action) + { + case PackageAction.Push: + if (isOwner) + { + return principal.HasScope(ApiKeyScopes.Push) || principal.HasScope(ApiKeyScopes.PushVersion); + } - // A new ID may be claimed; an existing one without owners may not. - return principal.HasScope(ApiKeyScopes.Push) - && !await _ownership.HasOwnersAsync(packageId, cancellationToken) - && !await _packages.ExistsAsync(packageId, cancellationToken); + // A new ID may be claimed; an existing one without owners may not. + return principal.HasScope(ApiKeyScopes.Push) + && !await _ownership.HasOwnersAsync(packageId, cancellationToken) + && !await _packages.ExistsAsync(packageId, cancellationToken); - case PackageAction.Manage: - return isOwner && principal.HasScope(ApiKeyScopes.Unlist); + case PackageAction.Manage: + return isOwner && principal.HasScope(ApiKeyScopes.Unlist); - default: - return false; - } + default: + return false; } + } - public async Task OnPushedAsync(BaGetPrincipal principal, string packageId, CancellationToken cancellationToken) - { - if (principal == null || principal.IsSuperuser || packageId == null) return; - if (await _ownership.HasOwnersAsync(packageId, cancellationToken)) return; + public async Task OnPushedAsync(BaGetPrincipal principal, string packageId, CancellationToken cancellationToken) + { + if (principal == null || principal.IsSuperuser || packageId == null) return; + if (await _ownership.HasOwnersAsync(packageId, cancellationToken)) return; - // Two users pushing the same new ID at once may both become owners. That is - // safe, if surprising: each could only have done so with the push scope. - var result = await _ownership.AddOwnerAsync(packageId, principal.UserName, cancellationToken); + // Two users pushing the same new ID at once may both become owners. That is + // safe, if surprising: each could only have done so with the push scope. + var result = await _ownership.AddOwnerAsync(packageId, principal.UserName, cancellationToken); - _logger.LogInformation( - "{UserName} pushed new package {PackageId} and became its owner: {Result}", - principal.UserName, - packageId, - result); - } + _logger.LogInformation( + "{UserName} pushed new package {PackageId} and became its owner: {Result}", + principal.UserName, + packageId, + result); } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/PackageOwnershipService.cs b/src/BaGet.Identity/PackageOwnershipService.cs index e063e6d83..b0a499ed8 100644 --- a/src/BaGet.Identity/PackageOwnershipService.cs +++ b/src/BaGet.Identity/PackageOwnershipService.cs @@ -6,256 +6,255 @@ using BaGet.Core; using Microsoft.EntityFrameworkCore; -namespace BaGet.Identity +namespace BaGet.Identity; + +public enum OwnerChangeResult { - public enum OwnerChangeResult - { - Success, + Success, + + /// + /// No user or organization has that name. + /// + UnknownAccount, + + AlreadyOwner, + + NotOwner, + + /// + /// A package ID with owners must keep at least one. + /// + LastOwner, +} - /// - /// No user or organization has that name. - /// - UnknownAccount, +/// +/// Package owners, and the organizations users own packages through. +/// +public class PackageOwnershipService +{ + private readonly IContext _context; + private readonly SystemTime _time; - AlreadyOwner, + public PackageOwnershipService(IContext context, SystemTime time) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } - NotOwner, + public async Task> GetOwnersAsync(string packageId, CancellationToken cancellationToken) + { + var id = packageId.ToLowerInvariant(); - /// - /// A package ID with owners must keep at least one. - /// - LastOwner, + return await _context.PackageOwners + .AsNoTracking() + .Where(o => o.PackageId.ToLower() == id) + .OrderBy(o => o.OwnerName) + .ToListAsync(cancellationToken); } /// - /// Package owners, and the organizations users own packages through. + /// The account names a user acts as: their own and every organization they belong to. /// - public class PackageOwnershipService + public async Task> GetAccountNamesAsync(string userId, string userName, CancellationToken cancellationToken) { - private readonly IContext _context; - private readonly SystemTime _time; + var organizations = await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.UserId == userId && m.Organization != null) + .Select(m => m.Organization.Name) + .ToListAsync(cancellationToken); - public PackageOwnershipService(IContext context, SystemTime time) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _time = time ?? throw new ArgumentNullException(nameof(time)); - } - - public async Task> GetOwnersAsync(string packageId, CancellationToken cancellationToken) - { - var id = packageId.ToLowerInvariant(); + return new[] { userName }.Concat(organizations).ToList(); + } - return await _context.PackageOwners - .AsNoTracking() - .Where(o => o.PackageId.ToLower() == id) - .OrderBy(o => o.OwnerName) - .ToListAsync(cancellationToken); - } + public async Task IsOwnerAsync(string userId, string userName, string packageId, CancellationToken cancellationToken) + { + var names = (await GetAccountNamesAsync(userId, userName, cancellationToken)) + .Select(n => n.ToLowerInvariant()) + .ToList(); + var id = packageId.ToLowerInvariant(); - /// - /// The account names a user acts as: their own and every organization they belong to. - /// - public async Task> GetAccountNamesAsync(string userId, string userName, CancellationToken cancellationToken) - { - var organizations = await _context.OrganizationMembers - .AsNoTracking() - .Where(m => m.UserId == userId && m.Organization != null) - .Select(m => m.Organization.Name) - .ToListAsync(cancellationToken); + return await _context.PackageOwners + .AnyAsync(o => o.PackageId.ToLower() == id && names.Contains(o.OwnerName.ToLower()), cancellationToken); + } - return new[] { userName }.Concat(organizations).ToList(); - } + /// + /// The package IDs the user owns, directly or through an organization. + /// + public async Task> GetOwnedPackageIdsAsync(string userId, string userName, CancellationToken cancellationToken) + { + var names = (await GetAccountNamesAsync(userId, userName, cancellationToken)) + .Select(n => n.ToLowerInvariant()) + .ToList(); - public async Task IsOwnerAsync(string userId, string userName, string packageId, CancellationToken cancellationToken) - { - var names = (await GetAccountNamesAsync(userId, userName, cancellationToken)) - .Select(n => n.ToLowerInvariant()) - .ToList(); - var id = packageId.ToLowerInvariant(); + var ids = await _context.PackageOwners + .AsNoTracking() + .Where(o => names.Contains(o.OwnerName.ToLower())) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken); - return await _context.PackageOwners - .AnyAsync(o => o.PackageId.ToLower() == id && names.Contains(o.OwnerName.ToLower()), cancellationToken); - } + return ids.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(i => i, StringComparer.OrdinalIgnoreCase).ToList(); + } - /// - /// The package IDs the user owns, directly or through an organization. - /// - public async Task> GetOwnedPackageIdsAsync(string userId, string userName, CancellationToken cancellationToken) - { - var names = (await GetAccountNamesAsync(userId, userName, cancellationToken)) - .Select(n => n.ToLowerInvariant()) - .ToList(); + public async Task HasOwnersAsync(string packageId, CancellationToken cancellationToken) + { + var id = packageId.ToLowerInvariant(); - var ids = await _context.PackageOwners - .AsNoTracking() - .Where(o => names.Contains(o.OwnerName.ToLower())) - .Select(o => o.PackageId) - .ToListAsync(cancellationToken); + return await _context.PackageOwners.AnyAsync(o => o.PackageId.ToLower() == id, cancellationToken); + } - return ids.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(i => i, StringComparer.OrdinalIgnoreCase).ToList(); - } + public async Task AccountExistsAsync(string name, CancellationToken cancellationToken) + { + var normalized = name.ToUpperInvariant(); + var lower = name.ToLowerInvariant(); - public async Task HasOwnersAsync(string packageId, CancellationToken cancellationToken) - { - var id = packageId.ToLowerInvariant(); + return await _context.Users.AnyAsync(u => u.NormalizedUserName == normalized, cancellationToken) + || await _context.Organizations.AnyAsync(o => o.Name.ToLower() == lower, cancellationToken); + } - return await _context.PackageOwners.AnyAsync(o => o.PackageId.ToLower() == id, cancellationToken); - } + public async Task AddOwnerAsync(string packageId, string ownerName, CancellationToken cancellationToken) + { + if (!await AccountExistsAsync(ownerName, cancellationToken)) return OwnerChangeResult.UnknownAccount; - public async Task AccountExistsAsync(string name, CancellationToken cancellationToken) + var owners = await GetOwnersAsync(packageId, cancellationToken); + if (owners.Any(o => string.Equals(o.OwnerName, ownerName, StringComparison.OrdinalIgnoreCase))) { - var normalized = name.ToUpperInvariant(); - var lower = name.ToLowerInvariant(); - - return await _context.Users.AnyAsync(u => u.NormalizedUserName == normalized, cancellationToken) - || await _context.Organizations.AnyAsync(o => o.Name.ToLower() == lower, cancellationToken); + return OwnerChangeResult.AlreadyOwner; } - public async Task AddOwnerAsync(string packageId, string ownerName, CancellationToken cancellationToken) - { - if (!await AccountExistsAsync(ownerName, cancellationToken)) return OwnerChangeResult.UnknownAccount; + _context.PackageOwners.Add(new PackageOwner { PackageId = packageId, OwnerName = ownerName }); + await _context.SaveChangesAsync(cancellationToken); - var owners = await GetOwnersAsync(packageId, cancellationToken); - if (owners.Any(o => string.Equals(o.OwnerName, ownerName, StringComparison.OrdinalIgnoreCase))) - { - return OwnerChangeResult.AlreadyOwner; - } + return OwnerChangeResult.Success; + } - _context.PackageOwners.Add(new PackageOwner { PackageId = packageId, OwnerName = ownerName }); - await _context.SaveChangesAsync(cancellationToken); + public async Task RemoveOwnerAsync(string packageId, string ownerName, CancellationToken cancellationToken) + { + var id = packageId.ToLowerInvariant(); + var owners = await _context.PackageOwners + .Where(o => o.PackageId.ToLower() == id) + .ToListAsync(cancellationToken); - return OwnerChangeResult.Success; - } + var owner = owners.FirstOrDefault(o => string.Equals(o.OwnerName, ownerName, StringComparison.OrdinalIgnoreCase)); + if (owner == null) return OwnerChangeResult.NotOwner; + if (owners.Count == 1) return OwnerChangeResult.LastOwner; - public async Task RemoveOwnerAsync(string packageId, string ownerName, CancellationToken cancellationToken) - { - var id = packageId.ToLowerInvariant(); - var owners = await _context.PackageOwners - .Where(o => o.PackageId.ToLower() == id) - .ToListAsync(cancellationToken); + _context.PackageOwners.Remove(owner); + await _context.SaveChangesAsync(cancellationToken); - var owner = owners.FirstOrDefault(o => string.Equals(o.OwnerName, ownerName, StringComparison.OrdinalIgnoreCase)); - if (owner == null) return OwnerChangeResult.NotOwner; - if (owners.Count == 1) return OwnerChangeResult.LastOwner; + return OwnerChangeResult.Success; + } - _context.PackageOwners.Remove(owner); - await _context.SaveChangesAsync(cancellationToken); + /// + /// Mark or unmark the ID as reserved for its owners. Only the superuser may do this. + /// + public async Task SetVerifiedAsync(string packageId, bool verified, CancellationToken cancellationToken) + { + var id = packageId.ToLowerInvariant(); + var owners = await _context.PackageOwners + .Where(o => o.PackageId.ToLower() == id) + .ToListAsync(cancellationToken); - return OwnerChangeResult.Success; - } + if (owners.Count == 0) return false; - /// - /// Mark or unmark the ID as reserved for its owners. Only the superuser may do this. - /// - public async Task SetVerifiedAsync(string packageId, bool verified, CancellationToken cancellationToken) - { - var id = packageId.ToLowerInvariant(); - var owners = await _context.PackageOwners - .Where(o => o.PackageId.ToLower() == id) - .ToListAsync(cancellationToken); + owners.ForEach(o => o.IsVerified = verified); + await _context.SaveChangesAsync(cancellationToken); - if (owners.Count == 0) return false; + return true; + } - owners.ForEach(o => o.IsVerified = verified); - await _context.SaveChangesAsync(cancellationToken); + public async Task IsVerifiedAsync(string packageId, CancellationToken cancellationToken) + { + var id = packageId.ToLowerInvariant(); - return true; - } + return await _context.PackageOwners.AnyAsync(o => o.PackageId.ToLower() == id && o.IsVerified, cancellationToken); + } - public async Task IsVerifiedAsync(string packageId, CancellationToken cancellationToken) - { - var id = packageId.ToLowerInvariant(); + public async Task> GetOrganizationsAsync(string userId, CancellationToken cancellationToken) + { + return await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.UserId == userId && m.Organization != null) + .Select(m => m.Organization) + .OrderBy(o => o.Name) + .ToListAsync(cancellationToken); + } - return await _context.PackageOwners.AnyAsync(o => o.PackageId.ToLower() == id && o.IsVerified, cancellationToken); - } + /// + /// Create an organization with its creator as the first administrator. False if + /// the name is already a user or an organization. + /// + public async Task CreateOrganizationAsync(string name, string creatorUserId, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(name) || await AccountExistsAsync(name, cancellationToken)) return false; - public async Task> GetOrganizationsAsync(string userId, CancellationToken cancellationToken) + var organization = new Organization { Name = name.Trim(), Created = _time.UtcNow }; + _context.Organizations.Add(organization); + _context.OrganizationMembers.Add(new OrganizationMember { - return await _context.OrganizationMembers - .AsNoTracking() - .Where(m => m.UserId == userId && m.Organization != null) - .Select(m => m.Organization) - .OrderBy(o => o.Name) - .ToListAsync(cancellationToken); - } + Organization = organization, + UserId = creatorUserId, + IsAdmin = true, + }); - /// - /// Create an organization with its creator as the first administrator. False if - /// the name is already a user or an organization. - /// - public async Task CreateOrganizationAsync(string name, string creatorUserId, CancellationToken cancellationToken) - { - if (string.IsNullOrWhiteSpace(name) || await AccountExistsAsync(name, cancellationToken)) return false; + await _context.SaveChangesAsync(cancellationToken); - var organization = new Organization { Name = name.Trim(), Created = _time.UtcNow }; - _context.Organizations.Add(organization); - _context.OrganizationMembers.Add(new OrganizationMember - { - Organization = organization, - UserId = creatorUserId, - IsAdmin = true, - }); + return true; + } - await _context.SaveChangesAsync(cancellationToken); + public async Task> GetMembersAsync(string organizationName, CancellationToken cancellationToken) + { + var name = organizationName.ToLowerInvariant(); - return true; - } + return await _context.OrganizationMembers + .AsNoTracking() + .Where(m => m.Organization != null && m.Organization.Name.ToLower() == name) + .ToListAsync(cancellationToken); + } - public async Task> GetMembersAsync(string organizationName, CancellationToken cancellationToken) - { - var name = organizationName.ToLowerInvariant(); + public async Task IsOrganizationAdminAsync(string organizationName, string userId, CancellationToken cancellationToken) + { + var members = await GetMembersAsync(organizationName, cancellationToken); - return await _context.OrganizationMembers - .AsNoTracking() - .Where(m => m.Organization != null && m.Organization.Name.ToLower() == name) - .ToListAsync(cancellationToken); - } + return members.Any(m => m.UserId == userId && m.IsAdmin); + } - public async Task IsOrganizationAdminAsync(string organizationName, string userId, CancellationToken cancellationToken) - { - var members = await GetMembersAsync(organizationName, cancellationToken); + public async Task AddMemberAsync(string organizationName, string userId, bool isAdmin, CancellationToken cancellationToken) + { + var name = organizationName.ToLowerInvariant(); + var organization = await _context.Organizations.FirstOrDefaultAsync(o => o.Name.ToLower() == name, cancellationToken); + if (organization == null) return false; - return members.Any(m => m.UserId == userId && m.IsAdmin); - } + var members = await GetMembersAsync(organizationName, cancellationToken); + if (members.Any(m => m.UserId == userId)) return false; - public async Task AddMemberAsync(string organizationName, string userId, bool isAdmin, CancellationToken cancellationToken) + _context.OrganizationMembers.Add(new OrganizationMember { - var name = organizationName.ToLowerInvariant(); - var organization = await _context.Organizations.FirstOrDefaultAsync(o => o.Name.ToLower() == name, cancellationToken); - if (organization == null) return false; - - var members = await GetMembersAsync(organizationName, cancellationToken); - if (members.Any(m => m.UserId == userId)) return false; - - _context.OrganizationMembers.Add(new OrganizationMember - { - OrganizationKey = organization.Key, - UserId = userId, - IsAdmin = isAdmin, - }); - await _context.SaveChangesAsync(cancellationToken); - - return true; - } + OrganizationKey = organization.Key, + UserId = userId, + IsAdmin = isAdmin, + }); + await _context.SaveChangesAsync(cancellationToken); - /// - /// Remove a member. The last administrator cannot be removed. - /// - public async Task RemoveMemberAsync(string organizationName, string userId, CancellationToken cancellationToken) - { - var name = organizationName.ToLowerInvariant(); - var members = await _context.OrganizationMembers - .Where(m => m.Organization != null && m.Organization.Name.ToLower() == name) - .ToListAsync(cancellationToken); + return true; + } + + /// + /// Remove a member. The last administrator cannot be removed. + /// + public async Task RemoveMemberAsync(string organizationName, string userId, CancellationToken cancellationToken) + { + var name = organizationName.ToLowerInvariant(); + var members = await _context.OrganizationMembers + .Where(m => m.Organization != null && m.Organization.Name.ToLower() == name) + .ToListAsync(cancellationToken); - var member = members.FirstOrDefault(m => m.UserId == userId); - if (member == null) return false; - if (member.IsAdmin && members.Count(m => m.IsAdmin) == 1) return false; + var member = members.FirstOrDefault(m => m.UserId == userId); + if (member == null) return false; + if (member.IsAdmin && members.Count(m => m.IsAdmin) == 1) return false; - _context.OrganizationMembers.Remove(member); - await _context.SaveChangesAsync(cancellationToken); + _context.OrganizationMembers.Remove(member); + await _context.SaveChangesAsync(cancellationToken); - return true; - } + return true; } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Account/AccountPageModel.cs b/src/BaGet.Identity/Pages/Account/AccountPageModel.cs index 57e1f669b..c63b3b082 100644 --- a/src/BaGet.Identity/Pages/Account/AccountPageModel.cs +++ b/src/BaGet.Identity/Pages/Account/AccountPageModel.cs @@ -6,64 +6,63 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -namespace BaGet.Identity.Pages.Account +namespace BaGet.Identity.Pages.Account; + +/// +/// Shared by the account pages. The pages are always compiled in, but answer 404 while +/// accounts are disabled, so their services are resolved per request rather than +/// injected: they are only registered when accounts are enabled. +/// +public abstract class AccountPageModel : PageModel { - /// - /// Shared by the account pages. The pages are always compiled in, but answer 404 while - /// accounts are disabled, so their services are resolved per request rather than - /// injected: they are only registered when accounts are enabled. - /// - public abstract class AccountPageModel : PageModel - { - protected AccountsOptions Accounts - => HttpContext.RequestServices.GetRequiredService>().Value; + protected AccountsOptions Accounts + => HttpContext.RequestServices.GetRequiredService>().Value; - protected SignInManager SignInManager - => HttpContext.RequestServices.GetRequiredService>(); + protected SignInManager SignInManager + => HttpContext.RequestServices.GetRequiredService>(); - protected UserManager UserManager - => HttpContext.RequestServices.GetRequiredService>(); + protected UserManager UserManager + => HttpContext.RequestServices.GetRequiredService>(); - protected PackageOwnershipService Ownership - => HttpContext.RequestServices.GetRequiredService(); + protected PackageOwnershipService Ownership + => HttpContext.RequestServices.GetRequiredService(); - protected ApiKeyService ApiKeys - => HttpContext.RequestServices.GetRequiredService(); + protected ApiKeyService ApiKeys + => HttpContext.RequestServices.GetRequiredService(); - /// - /// Checked here rather than with [Authorize]: while accounts are disabled there is - /// no scheme to challenge with, and the page must answer 404 instead. - /// - protected virtual bool RequiresSignIn => false; + /// + /// Checked here rather than with [Authorize]: while accounts are disabled there is + /// no scheme to challenge with, and the page must answer 404 instead. + /// + protected virtual bool RequiresSignIn => false; - public override void OnPageHandlerExecuting(PageHandlerExecutingContext context) + public override void OnPageHandlerExecuting(PageHandlerExecutingContext context) + { + if (!Accounts.Enabled) { - if (!Accounts.Enabled) - { - context.Result = NotFound(); - return; - } - - if (RequiresSignIn && User.Identity?.IsAuthenticated != true) - { - context.Result = Challenge(); - return; - } - - base.OnPageHandlerExecuting(context); + context.Result = NotFound(); + return; } - /// - /// Only follow a local return URL, so a sign-in link cannot redirect elsewhere. - /// - protected IActionResult RedirectToLocal(string returnUrl) + if (RequiresSignIn && User.Identity?.IsAuthenticated != true) { - if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)) - { - return LocalRedirect(returnUrl); - } + context.Result = Challenge(); + return; + } + + base.OnPageHandlerExecuting(context); + } - return LocalRedirect(Url.Content("~/")); + /// + /// Only follow a local return URL, so a sign-in link cannot redirect elsewhere. + /// + protected IActionResult RedirectToLocal(string returnUrl) + { + if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)) + { + return LocalRedirect(returnUrl); } + + return LocalRedirect(Url.Content("~/")); } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Account/ApiKeys.cshtml.cs b/src/BaGet.Identity/Pages/Account/ApiKeys.cshtml.cs index 39966774f..a8927d8b1 100644 --- a/src/BaGet.Identity/Pages/Account/ApiKeys.cshtml.cs +++ b/src/BaGet.Identity/Pages/Account/ApiKeys.cshtml.cs @@ -8,87 +8,86 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; -namespace BaGet.Identity.Pages.Account +namespace BaGet.Identity.Pages.Account; + +public class ApiKeysModel : AccountPageModel { - public class ApiKeysModel : AccountPageModel - { - protected override bool RequiresSignIn => true; + protected override bool RequiresSignIn => true; + + [BindProperty] + [StringLength(AbstractContext.MaxApiKeyDescriptionLength)] + public string Description { get; set; } - [BindProperty] - [StringLength(AbstractContext.MaxApiKeyDescriptionLength)] - public string Description { get; set; } + [BindProperty] + public List Scopes { get; set; } = new List(); - [BindProperty] - public List Scopes { get; set; } = new List(); + [BindProperty] + [Display(Name = "Package glob pattern")] + public string PackageGlobPattern { get; set; } = "*"; - [BindProperty] - [Display(Name = "Package glob pattern")] - public string PackageGlobPattern { get; set; } = "*"; + [BindProperty] + [Range(1, 3650)] + [Display(Name = "Expires after (days)")] + public int? ExpiresInDays { get; set; } = 365; - [BindProperty] - [Range(1, 3650)] - [Display(Name = "Expires after (days)")] - public int? ExpiresInDays { get; set; } = 365; + public IReadOnlyList Keys { get; private set; } = Array.Empty(); - public IReadOnlyList Keys { get; private set; } = Array.Empty(); + /// + /// The key just created. Shown once: only its hash is kept. + /// + public string CreatedKey { get; private set; } - /// - /// The key just created. Shown once: only its hash is kept. - /// - public string CreatedKey { get; private set; } + public async Task OnGetAsync(CancellationToken cancellationToken) + { + await LoadAsync(cancellationToken); + } - public async Task OnGetAsync(CancellationToken cancellationToken) + public async Task OnPostCreateAsync(CancellationToken cancellationToken) + { + if (Scopes.Count == 0) { - await LoadAsync(cancellationToken); + ModelState.AddModelError(nameof(Scopes), "Choose at least one scope."); } - public async Task OnPostCreateAsync(CancellationToken cancellationToken) + if (ModelState.IsValid) { - if (Scopes.Count == 0) + var now = HttpContext.RequestServices.GetRequiredService().UtcNow; + + try { - ModelState.AddModelError(nameof(Scopes), "Choose at least one scope."); + CreatedKey = await ApiKeys.CreateAsync( + UserManager.GetUserId(User), + Description, + Scopes, + PackageGlobPattern, + ExpiresInDays.HasValue ? now.AddDays(ExpiresInDays.Value) : (DateTime?)null, + cancellationToken); } - - if (ModelState.IsValid) + catch (ArgumentException e) { - var now = HttpContext.RequestServices.GetRequiredService().UtcNow; - - try - { - CreatedKey = await ApiKeys.CreateAsync( - UserManager.GetUserId(User), - Description, - Scopes, - PackageGlobPattern, - ExpiresInDays.HasValue ? now.AddDays(ExpiresInDays.Value) : (DateTime?)null, - cancellationToken); - } - catch (ArgumentException e) - { - ModelState.AddModelError(nameof(Scopes), e.Message); - } + ModelState.AddModelError(nameof(Scopes), e.Message); } - - await LoadAsync(cancellationToken); - - return Page(); } - public async Task OnPostRevokeAsync(int key, CancellationToken cancellationToken) - { - await ApiKeys.RevokeAsync(UserManager.GetUserId(User), key, cancellationToken); + await LoadAsync(cancellationToken); - return RedirectToPage(); - } + return Page(); + } - private async Task LoadAsync(CancellationToken cancellationToken) - { - Keys = await ApiKeys.ListAsync(UserManager.GetUserId(User), cancellationToken); - } + public async Task OnPostRevokeAsync(int key, CancellationToken cancellationToken) + { + await ApiKeys.RevokeAsync(UserManager.GetUserId(User), key, cancellationToken); - public static string Describe(ApiKey key) - => string.Join(", ", key.Scopes ?? Array.Empty()) + " on " + key.PackageGlobPattern; + return RedirectToPage(); + } - public static IReadOnlyList AllScopes => ApiKeyScopes.All; + private async Task LoadAsync(CancellationToken cancellationToken) + { + Keys = await ApiKeys.ListAsync(UserManager.GetUserId(User), cancellationToken); } -} + + public static string Describe(ApiKey key) + => string.Join(", ", key.Scopes ?? Array.Empty()) + " on " + key.PackageGlobPattern; + + public static IReadOnlyList AllScopes => ApiKeyScopes.All; +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Account/Login.cshtml.cs b/src/BaGet.Identity/Pages/Account/Login.cshtml.cs index 89d9fe431..a42cb3712 100644 --- a/src/BaGet.Identity/Pages/Account/Login.cshtml.cs +++ b/src/BaGet.Identity/Pages/Account/Login.cshtml.cs @@ -7,141 +7,140 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; -namespace BaGet.Identity.Pages.Account +namespace BaGet.Identity.Pages.Account; + +public class LoginModel : AccountPageModel { - public class LoginModel : AccountPageModel - { - [BindProperty] - [Required] - [Display(Name = "User name")] - public string UserName { get; set; } + [BindProperty] + [Required] + [Display(Name = "User name")] + public string UserName { get; set; } + + [BindProperty] + [Required] + [DataType(DataType.Password)] + public string Password { get; set; } + + [BindProperty] + [Display(Name = "Remember me")] + public bool RememberMe { get; set; } - [BindProperty] - [Required] - [DataType(DataType.Password)] - public string Password { get; set; } + [BindProperty(SupportsGet = true)] + public string ReturnUrl { get; set; } - [BindProperty] - [Display(Name = "Remember me")] - public bool RememberMe { get; set; } + public bool AllowRegistration => Accounts.AllowRegistration; - [BindProperty(SupportsGet = true)] - public string ReturnUrl { get; set; } + public bool HasExternalProvider => Accounts.OpenIdConnect.IsConfigured; - public bool AllowRegistration => Accounts.AllowRegistration; + public string ExternalProviderName => Accounts.OpenIdConnect.DisplayName; - public bool HasExternalProvider => Accounts.OpenIdConnect.IsConfigured; + public string Error { get; set; } - public string ExternalProviderName => Accounts.OpenIdConnect.DisplayName; + public void OnGet() + { + } - public string Error { get; set; } + public async Task OnPostAsync() + { + if (!ModelState.IsValid) return Page(); - public void OnGet() + var result = await SignInManager.PasswordSignInAsync(UserName, Password, RememberMe, lockoutOnFailure: true); + if (result.Succeeded) { + return RedirectToLocal(ReturnUrl); } - public async Task OnPostAsync() - { - if (!ModelState.IsValid) return Page(); + Error = result.IsLockedOut + ? "The account is locked after too many failed attempts. Try again later." + : "The user name or password is incorrect."; + + return Page(); + } + + public IActionResult OnPostExternal() + { + if (!HasExternalProvider) return NotFound(); - var result = await SignInManager.PasswordSignInAsync(UserName, Password, RememberMe, lockoutOnFailure: true); - if (result.Succeeded) - { - return RedirectToLocal(ReturnUrl); - } + var callback = Url.Page("/Account/Login", "Callback", new { ReturnUrl }); + var properties = SignInManager.ConfigureExternalAuthenticationProperties( + AccountsServiceCollectionExtensions.OpenIdConnectScheme, + callback); - Error = result.IsLockedOut - ? "The account is locked after too many failed attempts. Try again later." - : "The user name or password is incorrect."; + return Challenge(properties, AccountsServiceCollectionExtensions.OpenIdConnectScheme); + } + /// + /// The provider has signed the user in. The first time, an account is created for + /// them: the provider is the gate, so this does not depend on AllowRegistration. + /// + public async Task OnGetCallbackAsync(CancellationToken cancellationToken) + { + var info = await SignInManager.GetExternalLoginInfoAsync(); + if (info == null) + { + Error = "The external sign-in failed."; return Page(); } - public IActionResult OnPostExternal() + var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); + if (result.Succeeded) { - if (!HasExternalProvider) return NotFound(); - - var callback = Url.Page("/Account/Login", "Callback", new { ReturnUrl }); - var properties = SignInManager.ConfigureExternalAuthenticationProperties( - AccountsServiceCollectionExtensions.OpenIdConnectScheme, - callback); + return RedirectToLocal(ReturnUrl); + } - return Challenge(properties, AccountsServiceCollectionExtensions.OpenIdConnectScheme); + var name = await ChooseUserNameAsync(info.Principal, cancellationToken); + if (name == null) + { + Error = "The external account has no usable name."; + return Page(); } - /// - /// The provider has signed the user in. The first time, an account is created for - /// them: the provider is the gate, so this does not depend on AllowRegistration. - /// - public async Task OnGetCallbackAsync(CancellationToken cancellationToken) + var user = new BaGetUser { - var info = await SignInManager.GetExternalLoginInfoAsync(); - if (info == null) - { - Error = "The external sign-in failed."; - return Page(); - } - - var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); - if (result.Succeeded) - { - return RedirectToLocal(ReturnUrl); - } - - var name = await ChooseUserNameAsync(info.Principal, cancellationToken); - if (name == null) - { - Error = "The external account has no usable name."; - return Page(); - } - - var user = new BaGetUser - { - UserName = name, - Email = info.Principal.FindFirstValue(ClaimTypes.Email), - Created = HttpContext.RequestServices.GetRequiredService().UtcNow, - }; - - var created = await UserManager.CreateAsync(user); - if (created.Succeeded) - { - created = await UserManager.AddLoginAsync(user, info); - } - - if (!created.Succeeded) - { - Error = string.Join(" ", created.Errors.Select(e => e.Description)); - return Page(); - } - - await SignInManager.SignInAsync(user, isPersistent: false); + UserName = name, + Email = info.Principal.FindFirstValue(ClaimTypes.Email), + Created = HttpContext.RequestServices.GetRequiredService().UtcNow, + }; - return RedirectToLocal(ReturnUrl); + var created = await UserManager.CreateAsync(user); + if (created.Succeeded) + { + created = await UserManager.AddLoginAsync(user, info); } - /// - /// The provider's preferred user name, else the email's local part, made unique - /// across users and organizations by a numeric suffix. - /// - private async Task ChooseUserNameAsync(ClaimsPrincipal principal, CancellationToken cancellationToken) + if (!created.Succeeded) { - var candidate = principal.FindFirstValue("preferred_username") - ?? principal.FindFirstValue(ClaimTypes.Email)?.Split('@')[0] - ?? principal.FindFirstValue(ClaimTypes.Name); + Error = string.Join(" ", created.Errors.Select(e => e.Description)); + return Page(); + } + + await SignInManager.SignInAsync(user, isPersistent: false); - if (string.IsNullOrWhiteSpace(candidate)) return null; + return RedirectToLocal(ReturnUrl); + } - var allowed = UserManager.Options.User.AllowedUserNameCharacters; - candidate = new string(candidate.Where(c => allowed.Contains(c)).ToArray()); - if (candidate.Length == 0) return null; + /// + /// The provider's preferred user name, else the email's local part, made unique + /// across users and organizations by a numeric suffix. + /// + private async Task ChooseUserNameAsync(ClaimsPrincipal principal, CancellationToken cancellationToken) + { + var candidate = principal.FindFirstValue("preferred_username") + ?? principal.FindFirstValue(ClaimTypes.Email)?.Split('@')[0] + ?? principal.FindFirstValue(ClaimTypes.Name); - var name = candidate; - for (var suffix = 2; await Ownership.AccountExistsAsync(name, cancellationToken); suffix++) - { - name = candidate + suffix; - } + if (string.IsNullOrWhiteSpace(candidate)) return null; - return name; + var allowed = UserManager.Options.User.AllowedUserNameCharacters; + candidate = new string(candidate.Where(c => allowed.Contains(c)).ToArray()); + if (candidate.Length == 0) return null; + + var name = candidate; + for (var suffix = 2; await Ownership.AccountExistsAsync(name, cancellationToken); suffix++) + { + name = candidate + suffix; } + + return name; } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Account/Logout.cshtml.cs b/src/BaGet.Identity/Pages/Account/Logout.cshtml.cs index 04d38f178..b83f3b559 100644 --- a/src/BaGet.Identity/Pages/Account/Logout.cshtml.cs +++ b/src/BaGet.Identity/Pages/Account/Logout.cshtml.cs @@ -1,22 +1,21 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; -namespace BaGet.Identity.Pages.Account +namespace BaGet.Identity.Pages.Account; + +/// +/// Signing out is a POST, so a link elsewhere cannot sign the user out. +/// +public class LogoutModel : AccountPageModel { - /// - /// Signing out is a POST, so a link elsewhere cannot sign the user out. - /// - public class LogoutModel : AccountPageModel + public void OnGet() { - public void OnGet() - { - } + } - public async Task OnPostAsync() - { - await SignInManager.SignOutAsync(); + public async Task OnPostAsync() + { + await SignInManager.SignOutAsync(); - return RedirectToLocal(null); - } + return RedirectToLocal(null); } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Account/Organizations.cshtml.cs b/src/BaGet.Identity/Pages/Account/Organizations.cshtml.cs index 24342bedc..6fb69ca93 100644 --- a/src/BaGet.Identity/Pages/Account/Organizations.cshtml.cs +++ b/src/BaGet.Identity/Pages/Account/Organizations.cshtml.cs @@ -6,110 +6,109 @@ using BaGet.Core; using Microsoft.AspNetCore.Mvc; -namespace BaGet.Identity.Pages.Account +namespace BaGet.Identity.Pages.Account; + +/// +/// The signed in user's organizations: create one, and manage the members of those +/// the user administers. +/// +public class OrganizationsModel : AccountPageModel { - /// - /// The signed in user's organizations: create one, and manage the members of those - /// the user administers. - /// - public class OrganizationsModel : AccountPageModel + protected override bool RequiresSignIn => true; + + public IReadOnlyList Organizations { get; private set; } = Array.Empty(); + + public string Message { get; private set; } + + public async Task OnGetAsync(CancellationToken cancellationToken) { - protected override bool RequiresSignIn => true; + await LoadAsync(cancellationToken); + } - public IReadOnlyList Organizations { get; private set; } = Array.Empty(); + public async Task OnPostCreateAsync(string name, CancellationToken cancellationToken) + { + var created = await Ownership.CreateOrganizationAsync(name, UserManager.GetUserId(User), cancellationToken); - public string Message { get; private set; } + return await DoneAsync(created ? $"Created {name}." : "That name is taken.", cancellationToken); + } - public async Task OnGetAsync(CancellationToken cancellationToken) + public async Task OnPostAddMemberAsync(string organization, string userName, bool isAdmin, CancellationToken cancellationToken) + { + if (!await Ownership.IsOrganizationAdminAsync(organization, UserManager.GetUserId(User), cancellationToken)) { - await LoadAsync(cancellationToken); + return StatusCode(403); } - public async Task OnPostCreateAsync(string name, CancellationToken cancellationToken) + var user = string.IsNullOrWhiteSpace(userName) ? null : await UserManager.FindByNameAsync(userName.Trim()); + if (user == null) { - var created = await Ownership.CreateOrganizationAsync(name, UserManager.GetUserId(User), cancellationToken); - - return await DoneAsync(created ? $"Created {name}." : "That name is taken.", cancellationToken); + return await DoneAsync("There is no user with that name.", cancellationToken); } - public async Task OnPostAddMemberAsync(string organization, string userName, bool isAdmin, CancellationToken cancellationToken) - { - if (!await Ownership.IsOrganizationAdminAsync(organization, UserManager.GetUserId(User), cancellationToken)) - { - return StatusCode(403); - } + var added = await Ownership.AddMemberAsync(organization, user.Id, isAdmin, cancellationToken); - var user = string.IsNullOrWhiteSpace(userName) ? null : await UserManager.FindByNameAsync(userName.Trim()); - if (user == null) - { - return await DoneAsync("There is no user with that name.", cancellationToken); - } - - var added = await Ownership.AddMemberAsync(organization, user.Id, isAdmin, cancellationToken); + return await DoneAsync(added ? $"{user.UserName} joined {organization}." : $"{user.UserName} is already a member.", cancellationToken); + } - return await DoneAsync(added ? $"{user.UserName} joined {organization}." : $"{user.UserName} is already a member.", cancellationToken); - } + public async Task OnPostRemoveMemberAsync(string organization, string userName, CancellationToken cancellationToken) + { + var currentUserId = UserManager.GetUserId(User); + var user = await UserManager.FindByNameAsync(userName ?? string.Empty); - public async Task OnPostRemoveMemberAsync(string organization, string userName, CancellationToken cancellationToken) + // An administrator may remove anyone; any member may leave. + if (user == null + || (user.Id != currentUserId && !await Ownership.IsOrganizationAdminAsync(organization, currentUserId, cancellationToken))) { - var currentUserId = UserManager.GetUserId(User); - var user = await UserManager.FindByNameAsync(userName ?? string.Empty); + return StatusCode(403); + } - // An administrator may remove anyone; any member may leave. - if (user == null - || (user.Id != currentUserId && !await Ownership.IsOrganizationAdminAsync(organization, currentUserId, cancellationToken))) - { - return StatusCode(403); - } + var removed = await Ownership.RemoveMemberAsync(organization, user.Id, cancellationToken); - var removed = await Ownership.RemoveMemberAsync(organization, user.Id, cancellationToken); + return await DoneAsync( + removed ? $"{user.UserName} left {organization}." : "An organization must keep at least one administrator.", + cancellationToken); + } - return await DoneAsync( - removed ? $"{user.UserName} left {organization}." : "An organization must keep at least one administrator.", - cancellationToken); - } + private async Task DoneAsync(string message, CancellationToken cancellationToken) + { + Message = message; + await LoadAsync(cancellationToken); - private async Task DoneAsync(string message, CancellationToken cancellationToken) - { - Message = message; - await LoadAsync(cancellationToken); + return Page(); + } - return Page(); - } + private async Task LoadAsync(CancellationToken cancellationToken) + { + var userId = UserManager.GetUserId(User); + var views = new List(); - private async Task LoadAsync(CancellationToken cancellationToken) + foreach (var organization in await Ownership.GetOrganizationsAsync(userId, cancellationToken)) { - var userId = UserManager.GetUserId(User); - var views = new List(); - - foreach (var organization in await Ownership.GetOrganizationsAsync(userId, cancellationToken)) + var members = await Ownership.GetMembersAsync(organization.Name, cancellationToken); + var names = new List<(string, bool)>(); + foreach (var member in members) { - var members = await Ownership.GetMembersAsync(organization.Name, cancellationToken); - var names = new List<(string, bool)>(); - foreach (var member in members) - { - var user = await UserManager.FindByIdAsync(member.UserId); - if (user != null) names.Add((user.UserName, member.IsAdmin)); - } - - views.Add(new OrganizationView - { - Name = organization.Name, - IsAdmin = members.Any(m => m.UserId == userId && m.IsAdmin), - Members = names.OrderBy(n => n.Item1, StringComparer.OrdinalIgnoreCase).ToList(), - }); + var user = await UserManager.FindByIdAsync(member.UserId); + if (user != null) names.Add((user.UserName, member.IsAdmin)); } - Organizations = views; + views.Add(new OrganizationView + { + Name = organization.Name, + IsAdmin = members.Any(m => m.UserId == userId && m.IsAdmin), + Members = names.OrderBy(n => n.Item1, StringComparer.OrdinalIgnoreCase).ToList(), + }); } - public class OrganizationView - { - public string Name { get; set; } + Organizations = views; + } + + public class OrganizationView + { + public string Name { get; set; } - public bool IsAdmin { get; set; } + public bool IsAdmin { get; set; } - public IReadOnlyList<(string UserName, bool IsAdmin)> Members { get; set; } - } + public IReadOnlyList<(string UserName, bool IsAdmin)> Members { get; set; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Account/Packages.cshtml.cs b/src/BaGet.Identity/Pages/Account/Packages.cshtml.cs index e2008c389..6f8ebbf27 100644 --- a/src/BaGet.Identity/Pages/Account/Packages.cshtml.cs +++ b/src/BaGet.Identity/Pages/Account/Packages.cshtml.cs @@ -8,141 +8,140 @@ using Microsoft.Extensions.DependencyInjection; using NuGet.Versioning; -namespace BaGet.Identity.Pages.Account +namespace BaGet.Identity.Pages.Account; + +/// +/// The package IDs the signed-in user owns, directly or through an organization, and the +/// way into each one's management page. +/// +public class PackagesModel : AccountPageModel { - /// - /// The package IDs the signed-in user owns, directly or through an organization, and the - /// way into each one's management page. - /// - public class PackagesModel : AccountPageModel - { - protected override bool RequiresSignIn => true; + protected override bool RequiresSignIn => true; - public IReadOnlyList Packages { get; private set; } = Array.Empty(); + public IReadOnlyList Packages { get; private set; } = Array.Empty(); - public async Task OnGetAsync(CancellationToken cancellationToken) + public async Task OnGetAsync(CancellationToken cancellationToken) + { + // Ownership, not the package table, decides what is listed: an ID whose every + // version was deleted is still the user's, and hiding it would hide the page + // where its owners are managed. + var ids = await Ownership.GetOwnedPackageIdsAsync( + UserManager.GetUserId(User), + User.Identity.Name, + cancellationToken); + + if (ids.Count == 0) { - // Ownership, not the package table, decides what is listed: an ID whose every - // version was deleted is still the user's, and hiding it would hide the page - // where its owners are managed. - var ids = await Ownership.GetOwnedPackageIdsAsync( - UserManager.GetUserId(User), - User.Identity.Name, - cancellationToken); - - if (ids.Count == 0) + Packages = Array.Empty(); + return; + } + + Packages = Summarise(ids, await ListVersionsAsync(ids, cancellationToken)); + } + + /// + /// Every owned ID's versions, in one query, projected to the four columns the page + /// shows. The page cost must not grow with how successful a publisher the user is: + /// a per-ID + /// would be six round trips each - it eagerly loads the dependencies, package types, + /// target frameworks, deprecation and vulnerabilities of every version - to compute + /// three numbers from them. + /// + /// + /// Read through , which is what + /// already requires: + /// this page cannot work on a database without one either way, so routing it through + /// bought nothing. + /// + private async Task> ListVersionsAsync( + IReadOnlyList ids, + CancellationToken cancellationToken) + { + var context = HttpContext.RequestServices.GetRequiredService(); + var lowered = ids.Select(id => id.ToLowerInvariant()).ToList(); + + // Unlisted versions included: they are the owner's own, and an ID whose versions + // are all unlisted would otherwise look empty. + return await context.Packages + .AsNoTracking() + .Where(p => lowered.Contains(p.Id.ToLower())) + .Select(p => new OwnedVersion { - Packages = Array.Empty(); - return; - } + Id = p.Id, + NormalizedVersion = p.NormalizedVersionString, + OriginalVersion = p.OriginalVersionString, + Listed = p.Listed, + Downloads = p.Downloads, + }) + .ToListAsync(cancellationToken); + } - Packages = Summarise(ids, await ListVersionsAsync(ids, cancellationToken)); - } + /// + /// The highest version is decided here rather than in the query: version ordering is + /// SemVer's, which no database sorts correctly. + /// + private static List Summarise(IReadOnlyList ids, List versions) + { + var byId = versions + .GroupBy(v => v.Id, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); - /// - /// Every owned ID's versions, in one query, projected to the four columns the page - /// shows. The page cost must not grow with how successful a publisher the user is: - /// a per-ID - /// would be six round trips each - it eagerly loads the dependencies, package types, - /// target frameworks, deprecation and vulnerabilities of every version - to compute - /// three numbers from them. - /// - /// - /// Read through , which is what - /// already requires: - /// this page cannot work on a database without one either way, so routing it through - /// bought nothing. - /// - private async Task> ListVersionsAsync( - IReadOnlyList ids, - CancellationToken cancellationToken) + var owned = new List(ids.Count); + foreach (var id in ids) { - var context = HttpContext.RequestServices.GetRequiredService(); - var lowered = ids.Select(id => id.ToLowerInvariant()).ToList(); - - // Unlisted versions included: they are the owner's own, and an ID whose versions - // are all unlisted would otherwise look empty. - return await context.Packages - .AsNoTracking() - .Where(p => lowered.Contains(p.Id.ToLower())) - .Select(p => new OwnedVersion - { - Id = p.Id, - NormalizedVersion = p.NormalizedVersionString, - OriginalVersion = p.OriginalVersionString, - Listed = p.Listed, - Downloads = p.Downloads, - }) - .ToListAsync(cancellationToken); - } + if (!byId.TryGetValue(id, out var found)) found = new List(); - /// - /// The highest version is decided here rather than in the query: version ordering is - /// SemVer's, which no database sorts correctly. - /// - private static List Summarise(IReadOnlyList ids, List versions) - { - var byId = versions - .GroupBy(v => v.Id, StringComparer.OrdinalIgnoreCase) - .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); + var latest = found + .OrderByDescending(v => NuGetVersion.Parse(v.OriginalVersion ?? v.NormalizedVersion)) + .FirstOrDefault(); - var owned = new List(ids.Count); - foreach (var id in ids) + owned.Add(new OwnedPackage { - if (!byId.TryGetValue(id, out var found)) found = new List(); - - var latest = found - .OrderByDescending(v => NuGetVersion.Parse(v.OriginalVersion ?? v.NormalizedVersion)) - .FirstOrDefault(); - - owned.Add(new OwnedPackage - { - Id = latest?.Id ?? id, - LatestVersion = latest == null - ? null - : NuGetVersion.Parse(latest.OriginalVersion ?? latest.NormalizedVersion).ToNormalizedString(), - LatestVersionIsListed = latest?.Listed ?? false, - VersionCount = found.Count, - Downloads = found.Sum(v => v.Downloads), - }); - } - - return owned; + Id = latest?.Id ?? id, + LatestVersion = latest == null + ? null + : NuGetVersion.Parse(latest.OriginalVersion ?? latest.NormalizedVersion).ToNormalizedString(), + LatestVersionIsListed = latest?.Listed ?? false, + VersionCount = found.Count, + Downloads = found.Sum(v => v.Downloads), + }); } - /// - /// The columns the summary needs, and nothing else. - /// - private class OwnedVersion - { - public string Id { get; set; } + return owned; + } + + /// + /// The columns the summary needs, and nothing else. + /// + private class OwnedVersion + { + public string Id { get; set; } - public string NormalizedVersion { get; set; } + public string NormalizedVersion { get; set; } - public string OriginalVersion { get; set; } + public string OriginalVersion { get; set; } - public bool Listed { get; set; } + public bool Listed { get; set; } - public long Downloads { get; set; } - } + public long Downloads { get; set; } + } + + /// + /// One owned package ID, summarised across its versions. + /// + public class OwnedPackage + { + public string Id { get; set; } /// - /// One owned package ID, summarised across its versions. + /// The highest version, listed or not, or null when no version remains. /// - public class OwnedPackage - { - public string Id { get; set; } + public string LatestVersion { get; set; } - /// - /// The highest version, listed or not, or null when no version remains. - /// - public string LatestVersion { get; set; } + public bool LatestVersionIsListed { get; set; } - public bool LatestVersionIsListed { get; set; } + public int VersionCount { get; set; } - public int VersionCount { get; set; } - - public long Downloads { get; set; } - } + public long Downloads { get; set; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Account/Profile.cshtml.cs b/src/BaGet.Identity/Pages/Account/Profile.cshtml.cs index 958f31584..cfdf4d1cf 100644 --- a/src/BaGet.Identity/Pages/Account/Profile.cshtml.cs +++ b/src/BaGet.Identity/Pages/Account/Profile.cshtml.cs @@ -1,14 +1,13 @@ using Microsoft.AspNetCore.Mvc; -namespace BaGet.Identity.Pages.Account +namespace BaGet.Identity.Pages.Account; + +/// +/// The signed in user's own profile. +/// +public class MyProfileModel : AccountPageModel { - /// - /// The signed in user's own profile. - /// - public class MyProfileModel : AccountPageModel - { - protected override bool RequiresSignIn => true; + protected override bool RequiresSignIn => true; - public IActionResult OnGet() => LocalRedirect(Url.Content($"~/profiles/{System.Uri.EscapeDataString(User.Identity.Name)}")); - } -} + public IActionResult OnGet() => LocalRedirect(Url.Content($"~/profiles/{System.Uri.EscapeDataString(User.Identity.Name)}")); +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Account/Register.cshtml.cs b/src/BaGet.Identity/Pages/Account/Register.cshtml.cs index fa547e8ca..39ca68a45 100644 --- a/src/BaGet.Identity/Pages/Account/Register.cshtml.cs +++ b/src/BaGet.Identity/Pages/Account/Register.cshtml.cs @@ -7,80 +7,79 @@ using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; -namespace BaGet.Identity.Pages.Account +namespace BaGet.Identity.Pages.Account; + +public class RegisterModel : AccountPageModel { - public class RegisterModel : AccountPageModel + [BindProperty] + [Required] + [Display(Name = "User name")] + public string UserName { get; set; } + + [BindProperty] + [EmailAddress] + public string Email { get; set; } + + [BindProperty] + [Required] + [DataType(DataType.Password)] + public string Password { get; set; } + + [BindProperty] + [Required] + [DataType(DataType.Password)] + [Display(Name = "Confirm password")] + [Compare(nameof(Password), ErrorMessage = "The passwords do not match.")] + public string ConfirmPassword { get; set; } + + [BindProperty(SupportsGet = true)] + public string ReturnUrl { get; set; } + + public override void OnPageHandlerExecuting(PageHandlerExecutingContext context) { - [BindProperty] - [Required] - [Display(Name = "User name")] - public string UserName { get; set; } - - [BindProperty] - [EmailAddress] - public string Email { get; set; } - - [BindProperty] - [Required] - [DataType(DataType.Password)] - public string Password { get; set; } - - [BindProperty] - [Required] - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - [Compare(nameof(Password), ErrorMessage = "The passwords do not match.")] - public string ConfirmPassword { get; set; } - - [BindProperty(SupportsGet = true)] - public string ReturnUrl { get; set; } - - public override void OnPageHandlerExecuting(PageHandlerExecutingContext context) - { - base.OnPageHandlerExecuting(context); + base.OnPageHandlerExecuting(context); - if (context.Result == null && !Accounts.AllowRegistration) - { - context.Result = NotFound(); - } + if (context.Result == null && !Accounts.AllowRegistration) + { + context.Result = NotFound(); } + } + + public void OnGet() + { + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + if (!ModelState.IsValid) return Page(); - public void OnGet() + // User and organization names share a namespace: either can own a package. + if (await Ownership.AccountExistsAsync(UserName, cancellationToken)) { + ModelState.AddModelError(nameof(UserName), "That name is taken."); + return Page(); } - public async Task OnPostAsync(CancellationToken cancellationToken) + var user = new BaGetUser { - if (!ModelState.IsValid) return Page(); + UserName = UserName, + Email = Email, + Created = HttpContext.RequestServices.GetRequiredService().UtcNow, + }; - // User and organization names share a namespace: either can own a package. - if (await Ownership.AccountExistsAsync(UserName, cancellationToken)) + var result = await UserManager.CreateAsync(user, Password); + if (!result.Succeeded) + { + foreach (var error in result.Errors) { - ModelState.AddModelError(nameof(UserName), "That name is taken."); - return Page(); + ModelState.AddModelError(string.Empty, error.Description); } - var user = new BaGetUser - { - UserName = UserName, - Email = Email, - Created = HttpContext.RequestServices.GetRequiredService().UtcNow, - }; - - var result = await UserManager.CreateAsync(user, Password); - if (!result.Succeeded) - { - foreach (var error in result.Errors) - { - ModelState.AddModelError(string.Empty, error.Description); - } - - return Page(); - } + return Page(); + } - await SignInManager.SignInAsync(user, isPersistent: false); + await SignInManager.SignInAsync(user, isPersistent: false); - return RedirectToLocal(ReturnUrl); - } + return RedirectToLocal(ReturnUrl); } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Packages/Manage.cshtml.cs b/src/BaGet.Identity/Pages/Packages/Manage.cshtml.cs index 256b2c949..4bc9ae51a 100644 --- a/src/BaGet.Identity/Pages/Packages/Manage.cshtml.cs +++ b/src/BaGet.Identity/Pages/Packages/Manage.cshtml.cs @@ -13,258 +13,257 @@ using Microsoft.Extensions.Options; using NuGet.Versioning; -namespace BaGet.Identity.Pages.Packages +namespace BaGet.Identity.Pages.Packages; + +/// +/// The owners' page for a package ID: its owners, its versions' listing and +/// deprecation, and the abuse reports against it. +/// +public class ManageModel : AccountPageModel { /// - /// The owners' page for a package ID: its owners, its versions' listing and - /// deprecation, and the abuse reports against it. + /// What every write handler here answers on a read-only server. The API refuses each + /// of these operations with a 401, so the page must refuse all of them too rather + /// than only the one it was last asked about. /// - public class ManageModel : AccountPageModel - { - /// - /// What every write handler here answers on a read-only server. The API refuses each - /// of these operations with a 401, so the page must refuse all of them too rather - /// than only the one it was last asked about. - /// - internal const string ReadOnlyMessage = - "This server is in read-only mode, so nothing can be changed."; + internal const string ReadOnlyMessage = + "This server is in read-only mode, so nothing can be changed."; - protected override bool RequiresSignIn => true; + protected override bool RequiresSignIn => true; - [BindProperty(SupportsGet = true)] - public string Id { get; set; } + [BindProperty(SupportsGet = true)] + public string Id { get; set; } - public IReadOnlyList Owners { get; private set; } = Array.Empty(); + public IReadOnlyList Owners { get; private set; } = Array.Empty(); - public IReadOnlyList Versions { get; private set; } = Array.Empty(); + public IReadOnlyList Versions { get; private set; } = Array.Empty(); - public IReadOnlyList Reports { get; private set; } = Array.Empty(); + public IReadOnlyList Reports { get; private set; } = Array.Empty(); - public string Message { get; private set; } + public string Message { get; private set; } - private IPackageDatabase Packages => HttpContext.RequestServices.GetRequiredService(); + private IPackageDatabase Packages => HttpContext.RequestServices.GetRequiredService(); - private PackageChangeNotifier Notifier => HttpContext.RequestServices.GetRequiredService(); + private PackageChangeNotifier Notifier => HttpContext.RequestServices.GetRequiredService(); - private IContext Context => HttpContext.RequestServices.GetRequiredService(); + private IContext Context => HttpContext.RequestServices.GetRequiredService(); - private IPackageDeletionService Deletions => HttpContext.RequestServices.GetRequiredService(); + private IPackageDeletionService Deletions => HttpContext.RequestServices.GetRequiredService(); - private BaGetOptions Options => HttpContext.RequestServices.GetRequiredService>().Value; + private BaGetOptions Options => HttpContext.RequestServices.GetRequiredService>().Value; - /// - /// What a deletion does on this server. The two behaviours are different operations, - /// so the page says which one the button performs rather than calling both "delete". - /// - public PackageDeletionBehavior DeletionBehavior => Options.PackageDeletionBehavior; + /// + /// What a deletion does on this server. The two behaviours are different operations, + /// so the page says which one the button performs rather than calling both "delete". + /// + public PackageDeletionBehavior DeletionBehavior => Options.PackageDeletionBehavior; - public bool IsReadOnlyMode => Options.IsReadOnlyMode; + public bool IsReadOnlyMode => Options.IsReadOnlyMode; - public bool DeletionIsPermanent => DeletionBehavior == PackageDeletionBehavior.HardDelete; + public bool DeletionIsPermanent => DeletionBehavior == PackageDeletionBehavior.HardDelete; - public string DeleteLabel => DeletionIsPermanent - ? "Delete this version permanently" - : "Unlist this version"; + public string DeleteLabel => DeletionIsPermanent + ? "Delete this version permanently" + : "Unlist this version"; - public string DeleteCaption => DeletionIsPermanent - ? "Removes the database rows and the .nupkg, .nuspec, readme and icon from storage. " - + "Consumers can no longer restore it. Indexed PDBs keep being served, and an " - + "external search index keeps the version until it is reindexed." - : "Hidden from search and from the version list; anyone who knows the exact version " - + "can still restore it."; + public string DeleteCaption => DeletionIsPermanent + ? "Removes the database rows and the .nupkg, .nuspec, readme and icon from storage. " + + "Consumers can no longer restore it. Indexed PDBs keep being served, and an " + + "external search index keeps the version until it is reindexed." + : "Hidden from search and from the version list; anyone who knows the exact version " + + "can still restore it."; - public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) - { - OnPageHandlerExecuting(context); - if (context.Result != null) return; - - // Only an owner, directly or through an organization, may manage the package. - if (!await Ownership.IsOwnerAsync(UserManager.GetUserId(User), User.Identity.Name, Id, HttpContext.RequestAborted)) - { - context.Result = StatusCode(403); - return; - } - - // Every handler on this page but the GET writes to the database, and most of - // them notify the catalog as well. Refused here, once, rather than in each - // handler: unlisting, relisting, deprecating and changing owners are the same - // operations the push and metadata endpoints short-circuit in read-only mode, - // and a page that refused only one of them would contradict itself. - if (IsReadOnlyMode && HttpMethods.IsPost(HttpContext.Request.Method)) - { - Message = ReadOnlyMessage; - await LoadAsync(HttpContext.RequestAborted); - - context.Result = Page(); - return; - } - - await next(); - } + public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) + { + OnPageHandlerExecuting(context); + if (context.Result != null) return; - public async Task OnGetAsync(CancellationToken cancellationToken) + // Only an owner, directly or through an organization, may manage the package. + if (!await Ownership.IsOwnerAsync(UserManager.GetUserId(User), User.Identity.Name, Id, HttpContext.RequestAborted)) { - await LoadAsync(cancellationToken); - return Versions.Count == 0 && Owners.Count == 0 ? NotFound() : Page(); + context.Result = StatusCode(403); + return; } - public async Task OnPostAddOwnerAsync(string ownerName, CancellationToken cancellationToken) + // Every handler on this page but the GET writes to the database, and most of + // them notify the catalog as well. Refused here, once, rather than in each + // handler: unlisting, relisting, deprecating and changing owners are the same + // operations the push and metadata endpoints short-circuit in read-only mode, + // and a page that refused only one of them would contradict itself. + if (IsReadOnlyMode && HttpMethods.IsPost(HttpContext.Request.Method)) { - var result = string.IsNullOrWhiteSpace(ownerName) - ? OwnerChangeResult.UnknownAccount - : await Ownership.AddOwnerAsync(Id, ownerName.Trim(), cancellationToken); + Message = ReadOnlyMessage; + await LoadAsync(HttpContext.RequestAborted); - return await DoneAsync(result == OwnerChangeResult.Success ? $"{ownerName} is now an owner." : Describe(result), cancellationToken); + context.Result = Page(); + return; } - public async Task OnPostRemoveOwnerAsync(string ownerName, CancellationToken cancellationToken) - { - var result = await Ownership.RemoveOwnerAsync(Id, ownerName, cancellationToken); + await next(); + } - return await DoneAsync(result == OwnerChangeResult.Success ? $"{ownerName} is no longer an owner." : Describe(result), cancellationToken); - } + public async Task OnGetAsync(CancellationToken cancellationToken) + { + await LoadAsync(cancellationToken); + return Versions.Count == 0 && Owners.Count == 0 ? NotFound() : Page(); + } - public async Task OnPostUnlistAsync(string version, CancellationToken cancellationToken) - => await ChangeVersionAsync(version, v => Packages.UnlistPackageAsync(Id, v, cancellationToken), "unlisted", cancellationToken); + public async Task OnPostAddOwnerAsync(string ownerName, CancellationToken cancellationToken) + { + var result = string.IsNullOrWhiteSpace(ownerName) + ? OwnerChangeResult.UnknownAccount + : await Ownership.AddOwnerAsync(Id, ownerName.Trim(), cancellationToken); - public async Task OnPostRelistAsync(string version, CancellationToken cancellationToken) - => await ChangeVersionAsync(version, v => Packages.RelistPackageAsync(Id, v, cancellationToken), "relisted", cancellationToken); + return await DoneAsync(result == OwnerChangeResult.Success ? $"{ownerName} is now an owner." : Describe(result), cancellationToken); + } - /// - /// Deletion as the server is configured to perform it: - /// hides the version, removes its rows - /// and its files. The page labels the button from the behaviour, so it never promises a - /// deletion that only unlists. - /// - public async Task OnPostDeleteAsync(string version, CancellationToken cancellationToken) - { - // Read-only mode is refused for every handler at once, in - // OnPageHandlerExecutionAsync, as the push endpoint's DELETE refuses before - // anything is touched. - if (!NuGetVersion.TryParse(version, out var parsed)) return NotFound(); - - // False means the database held no such version - not that nothing happened: - // a hard delete removes the files either way. - var found = await Deletions.TryDeletePackageAsync(Id, parsed, cancellationToken); - var normalized = parsed.ToNormalizedString(); - - // PackageDeletionService notifies the catalog itself, so nothing is notified here. - if (DeletionIsPermanent) - { - return await DoneAsync( - found - ? $"{Id} {normalized} is deleted. Its rows and its files are gone, and consumers " - + "can no longer restore it. Any indexed PDBs are still served, and an external " - + "search index keeps the version until it is reindexed." - : $"{Id} {normalized} was not in the database. Any files left in storage for it were removed.", - cancellationToken); - } + public async Task OnPostRemoveOwnerAsync(string ownerName, CancellationToken cancellationToken) + { + var result = await Ownership.RemoveOwnerAsync(Id, ownerName, cancellationToken); + + return await DoneAsync(result == OwnerChangeResult.Success ? $"{ownerName} is no longer an owner." : Describe(result), cancellationToken); + } + public async Task OnPostUnlistAsync(string version, CancellationToken cancellationToken) + => await ChangeVersionAsync(version, v => Packages.UnlistPackageAsync(Id, v, cancellationToken), "unlisted", cancellationToken); + + public async Task OnPostRelistAsync(string version, CancellationToken cancellationToken) + => await ChangeVersionAsync(version, v => Packages.RelistPackageAsync(Id, v, cancellationToken), "relisted", cancellationToken); + + /// + /// Deletion as the server is configured to perform it: + /// hides the version, removes its rows + /// and its files. The page labels the button from the behaviour, so it never promises a + /// deletion that only unlists. + /// + public async Task OnPostDeleteAsync(string version, CancellationToken cancellationToken) + { + // Read-only mode is refused for every handler at once, in + // OnPageHandlerExecutionAsync, as the push endpoint's DELETE refuses before + // anything is touched. + if (!NuGetVersion.TryParse(version, out var parsed)) return NotFound(); + + // False means the database held no such version - not that nothing happened: + // a hard delete removes the files either way. + var found = await Deletions.TryDeletePackageAsync(Id, parsed, cancellationToken); + var normalized = parsed.ToNormalizedString(); + + // PackageDeletionService notifies the catalog itself, so nothing is notified here. + if (DeletionIsPermanent) + { return await DoneAsync( found - ? $"{Id} {normalized} is unlisted. Deleting is configured to unlist on this server, so " - + "anyone who knows the exact version can still restore it." - : $"There is no {Id} {normalized} to unlist.", + ? $"{Id} {normalized} is deleted. Its rows and its files are gone, and consumers " + + "can no longer restore it. Any indexed PDBs are still served, and an external " + + "search index keeps the version until it is reindexed." + : $"{Id} {normalized} was not in the database. Any files left in storage for it were removed.", cancellationToken); } - public async Task OnPostDeprecateAsync( - string version, - List reasons, - string message, - string alternatePackageId, - CancellationToken cancellationToken) + return await DoneAsync( + found + ? $"{Id} {normalized} is unlisted. Deleting is configured to unlist on this server, so " + + "anyone who knows the exact version can still restore it." + : $"There is no {Id} {normalized} to unlist.", + cancellationToken); + } + + public async Task OnPostDeprecateAsync( + string version, + List reasons, + string message, + string alternatePackageId, + CancellationToken cancellationToken) + { + reasons = reasons?.Where(r => PackageDeprecation.KnownReasons.Contains(r, StringComparer.Ordinal)).Distinct().ToList(); + if (reasons == null || reasons.Count == 0) { - reasons = reasons?.Where(r => PackageDeprecation.KnownReasons.Contains(r, StringComparer.Ordinal)).Distinct().ToList(); - if (reasons == null || reasons.Count == 0) - { - return await DoneAsync("Choose at least one deprecation reason.", cancellationToken); - } - - var deprecation = new PackageDeprecation - { - Reasons = reasons.ToArray(), - Message = string.IsNullOrWhiteSpace(message) ? null : message.Trim(), - AlternatePackageId = string.IsNullOrWhiteSpace(alternatePackageId) ? null : alternatePackageId.Trim(), - }; - - return await ChangeVersionAsync(version, v => Packages.SetDeprecationAsync(Id, v, deprecation, cancellationToken), "deprecated", cancellationToken); + return await DoneAsync("Choose at least one deprecation reason.", cancellationToken); } - public async Task OnPostUndeprecateAsync(string version, CancellationToken cancellationToken) - => await ChangeVersionAsync(version, v => Packages.RemoveDeprecationAsync(Id, v, cancellationToken), "no longer deprecated", cancellationToken); + var deprecation = new PackageDeprecation + { + Reasons = reasons.ToArray(), + Message = string.IsNullOrWhiteSpace(message) ? null : message.Trim(), + AlternatePackageId = string.IsNullOrWhiteSpace(alternatePackageId) ? null : alternatePackageId.Trim(), + }; + + return await ChangeVersionAsync(version, v => Packages.SetDeprecationAsync(Id, v, deprecation, cancellationToken), "deprecated", cancellationToken); + } - public async Task OnPostResolveReportAsync(int key, CancellationToken cancellationToken) + public async Task OnPostUndeprecateAsync(string version, CancellationToken cancellationToken) + => await ChangeVersionAsync(version, v => Packages.RemoveDeprecationAsync(Id, v, cancellationToken), "no longer deprecated", cancellationToken); + + public async Task OnPostResolveReportAsync(int key, CancellationToken cancellationToken) + { + var lowerId = Id.ToLowerInvariant(); + var report = await Context.AbuseReports.FirstOrDefaultAsync(r => r.Key == key && r.PackageId.ToLower() == lowerId, cancellationToken); + if (report != null && report.Resolved == null) { - var lowerId = Id.ToLowerInvariant(); - var report = await Context.AbuseReports.FirstOrDefaultAsync(r => r.Key == key && r.PackageId.ToLower() == lowerId, cancellationToken); - if (report != null && report.Resolved == null) - { - report.Resolved = HttpContext.RequestServices.GetRequiredService().UtcNow; - await Context.SaveChangesAsync(cancellationToken); - } - - return await DoneAsync("The report is resolved.", cancellationToken); + report.Resolved = HttpContext.RequestServices.GetRequiredService().UtcNow; + await Context.SaveChangesAsync(cancellationToken); } - private async Task ChangeVersionAsync( - string version, - Func> change, - string done, - CancellationToken cancellationToken) + return await DoneAsync("The report is resolved.", cancellationToken); + } + + private async Task ChangeVersionAsync( + string version, + Func> change, + string done, + CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var parsed)) return NotFound(); + + bool changed; + try { - if (!NuGetVersion.TryParse(version, out var parsed)) return NotFound(); + changed = await change(parsed); + } + catch (NotSupportedException e) + { + return await DoneAsync(e.Message, cancellationToken); + } - bool changed; - try - { - changed = await change(parsed); - } - catch (NotSupportedException e) - { - return await DoneAsync(e.Message, cancellationToken); - } + if (!changed) return NotFound(); - if (!changed) return NotFound(); + await Notifier.PackageChangedAsync(Id, parsed, cancellationToken); - await Notifier.PackageChangedAsync(Id, parsed, cancellationToken); + return await DoneAsync($"{Id} {parsed.ToNormalizedString()} is {done}.", cancellationToken); + } - return await DoneAsync($"{Id} {parsed.ToNormalizedString()} is {done}.", cancellationToken); - } + private async Task DoneAsync(string message, CancellationToken cancellationToken) + { + Message = message; + await LoadAsync(cancellationToken); - private async Task DoneAsync(string message, CancellationToken cancellationToken) - { - Message = message; - await LoadAsync(cancellationToken); + return Page(); + } - return Page(); - } + private async Task LoadAsync(CancellationToken cancellationToken) + { + Owners = await Ownership.GetOwnersAsync(Id, cancellationToken); + Versions = (await Packages.FindAsync(Id, includeUnlisted: true, cancellationToken)) + .OrderByDescending(p => p.Version) + .ToList(); - private async Task LoadAsync(CancellationToken cancellationToken) + if (!(Context is NullContext)) { - Owners = await Ownership.GetOwnersAsync(Id, cancellationToken); - Versions = (await Packages.FindAsync(Id, includeUnlisted: true, cancellationToken)) - .OrderByDescending(p => p.Version) - .ToList(); - - if (!(Context is NullContext)) - { - var lowerId = Id.ToLowerInvariant(); - Reports = await Context.AbuseReports - .AsNoTracking() - .Where(r => r.PackageId.ToLower() == lowerId && r.Resolved == null) - .OrderByDescending(r => r.Key) - .ToListAsync(cancellationToken); - } + var lowerId = Id.ToLowerInvariant(); + Reports = await Context.AbuseReports + .AsNoTracking() + .Where(r => r.PackageId.ToLower() == lowerId && r.Resolved == null) + .OrderByDescending(r => r.Key) + .ToListAsync(cancellationToken); } - - private static string Describe(OwnerChangeResult result) => result switch - { - OwnerChangeResult.UnknownAccount => "There is no user or organization with that name.", - OwnerChangeResult.AlreadyOwner => "That account is already an owner.", - OwnerChangeResult.NotOwner => "That account is not an owner.", - OwnerChangeResult.LastOwner => "A package must keep at least one owner.", - _ => result.ToString(), - }; } -} + + private static string Describe(OwnerChangeResult result) => result switch + { + OwnerChangeResult.UnknownAccount => "There is no user or organization with that name.", + OwnerChangeResult.AlreadyOwner => "That account is already an owner.", + OwnerChangeResult.NotOwner => "That account is not an owner.", + OwnerChangeResult.LastOwner => "A package must keep at least one owner.", + _ => result.ToString(), + }; +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/Profiles/Profile.cshtml.cs b/src/BaGet.Identity/Pages/Profiles/Profile.cshtml.cs index eb1103198..79a55f427 100644 --- a/src/BaGet.Identity/Pages/Profiles/Profile.cshtml.cs +++ b/src/BaGet.Identity/Pages/Profiles/Profile.cshtml.cs @@ -9,78 +9,77 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -namespace BaGet.Identity.Pages.Profiles -{ - /// - /// A user's or an organization's public page: the packages it owns. - /// - public class ProfileModel : AccountPageModel - { - [BindProperty(SupportsGet = true)] - public string Name { get; set; } +namespace BaGet.Identity.Pages.Profiles; - public bool IsOrganization { get; private set; } - - public IReadOnlyList Packages { get; private set; } = Array.Empty(); +/// +/// A user's or an organization's public page: the packages it owns. +/// +public class ProfileModel : AccountPageModel +{ + [BindProperty(SupportsGet = true)] + public string Name { get; set; } - public IReadOnlyList Members { get; private set; } = Array.Empty(); + public bool IsOrganization { get; private set; } - public bool IsCurrentUser { get; private set; } + public IReadOnlyList Packages { get; private set; } = Array.Empty(); - public async Task OnGetAsync(CancellationToken cancellationToken) - { - var context = HttpContext.RequestServices.GetRequiredService(); - var user = await UserManager.FindByNameAsync(Name); + public IReadOnlyList Members { get; private set; } = Array.Empty(); - IReadOnlyList ids; - if (user != null) - { - Name = user.UserName; - IsCurrentUser = User.Identity?.IsAuthenticated == true && UserManager.GetUserId(User) == user.Id; + public bool IsCurrentUser { get; private set; } - // Only the packages owned in the user's own name: an organization's are on its page. - var lowerName = user.UserName.ToLowerInvariant(); - ids = await context.PackageOwners - .AsNoTracking() - .Where(o => o.OwnerName.ToLower() == lowerName) - .Select(o => o.PackageId) - .ToListAsync(cancellationToken); - } - else - { - var members = await Ownership.GetMembersAsync(Name, cancellationToken); - var lowerName = Name.ToLowerInvariant(); - var organization = await context.Organizations.AsNoTracking().FirstOrDefaultAsync(o => o.Name.ToLower() == lowerName, cancellationToken); - if (organization == null) return NotFound(); + public async Task OnGetAsync(CancellationToken cancellationToken) + { + var context = HttpContext.RequestServices.GetRequiredService(); + var user = await UserManager.FindByNameAsync(Name); - Name = organization.Name; - IsOrganization = true; + IReadOnlyList ids; + if (user != null) + { + Name = user.UserName; + IsCurrentUser = User.Identity?.IsAuthenticated == true && UserManager.GetUserId(User) == user.Id; - var memberIds = members.Select(m => m.UserId).ToList(); - Members = await context.Users - .AsNoTracking() - .Where(u => memberIds.Contains(u.Id)) - .Select(u => u.UserName) - .OrderBy(n => n) - .ToListAsync(cancellationToken); + // Only the packages owned in the user's own name: an organization's are on its page. + var lowerName = user.UserName.ToLowerInvariant(); + ids = await context.PackageOwners + .AsNoTracking() + .Where(o => o.OwnerName.ToLower() == lowerName) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken); + } + else + { + var members = await Ownership.GetMembersAsync(Name, cancellationToken); + var lowerName = Name.ToLowerInvariant(); + var organization = await context.Organizations.AsNoTracking().FirstOrDefaultAsync(o => o.Name.ToLower() == lowerName, cancellationToken); + if (organization == null) return NotFound(); - ids = await context.PackageOwners - .AsNoTracking() - .Where(o => o.OwnerName.ToLower() == lowerName) - .Select(o => o.PackageId) - .ToListAsync(cancellationToken); - } + Name = organization.Name; + IsOrganization = true; - var lowerIds = ids.Select(i => i.ToLowerInvariant()).Distinct().ToList(); - Packages = await context.Packages + var memberIds = members.Select(m => m.UserId).ToList(); + Members = await context.Users .AsNoTracking() - .Where(p => lowerIds.Contains(p.Id.ToLower())) - .GroupBy(p => p.Id) - .Select(g => new PackageDownloads { Id = g.Key, Downloads = g.Sum(p => p.Downloads) }) - .OrderBy(p => p.Id) + .Where(u => memberIds.Contains(u.Id)) + .Select(u => u.UserName) + .OrderBy(n => n) .ToListAsync(cancellationToken); - return Page(); + ids = await context.PackageOwners + .AsNoTracking() + .Where(o => o.OwnerName.ToLower() == lowerName) + .Select(o => o.PackageId) + .ToListAsync(cancellationToken); } + + var lowerIds = ids.Select(i => i.ToLowerInvariant()).Distinct().ToList(); + Packages = await context.Packages + .AsNoTracking() + .Where(p => lowerIds.Contains(p.Id.ToLower())) + .GroupBy(p => p.Id) + .Select(g => new PackageDownloads { Id = g.Key, Downloads = g.Sum(p => p.Downloads) }) + .OrderBy(p => p.Id) + .ToListAsync(cancellationToken); + + return Page(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Identity/Pages/_ViewImports.cshtml b/src/BaGet.Identity/Pages/_ViewImports.cshtml index d2689af2b..85d5de36e 100644 --- a/src/BaGet.Identity/Pages/_ViewImports.cshtml +++ b/src/BaGet.Identity/Pages/_ViewImports.cshtml @@ -1,4 +1,4 @@ @using BaGet.Core @using BaGet.Identity -@namespace BaGet.Identity.Pages +@namespace BaGet.Identity.Pages; @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/src/BaGet.Identity/SessionPrincipalFactory.cs b/src/BaGet.Identity/SessionPrincipalFactory.cs index 283ea0690..827539fd9 100644 --- a/src/BaGet.Identity/SessionPrincipalFactory.cs +++ b/src/BaGet.Identity/SessionPrincipalFactory.cs @@ -3,42 +3,41 @@ using BaGet.Core; using Microsoft.AspNetCore.Identity; -namespace BaGet.Identity +namespace BaGet.Identity; + +/// +/// Turns a signed-in browser session into a , so the browser +/// path is authorized by exactly the rules the API key path is. +/// +public class SessionPrincipalFactory { + private readonly UserManager _users; + + public SessionPrincipalFactory(UserManager users) + { + _users = users ?? throw new ArgumentNullException(nameof(users)); + } + /// - /// Turns a signed-in browser session into a , so the browser - /// path is authorized by exactly the rules the API key path is. + /// A session carries every scope - the user could create a key with all of them + /// anyway - and a glob that matches every ID. Ownership still decides: + /// requires the user to own an existing + /// ID, so a session may push a new ID or one its user owns, and nothing else. It is + /// never the superuser. /// - public class SessionPrincipalFactory + /// Null when nobody is signed in. + public BaGetPrincipal Create(ClaimsPrincipal user) { - private readonly UserManager _users; - - public SessionPrincipalFactory(UserManager users) - { - _users = users ?? throw new ArgumentNullException(nameof(users)); - } - - /// - /// A session carries every scope - the user could create a key with all of them - /// anyway - and a glob that matches every ID. Ownership still decides: - /// requires the user to own an existing - /// ID, so a session may push a new ID or one its user owns, and nothing else. It is - /// never the superuser. - /// - /// Null when nobody is signed in. - public BaGetPrincipal Create(ClaimsPrincipal user) - { - if (user?.Identity?.IsAuthenticated != true) return null; + if (user?.Identity?.IsAuthenticated != true) return null; - var userId = _users.GetUserId(user); - if (string.IsNullOrEmpty(userId)) return null; + var userId = _users.GetUserId(user); + if (string.IsNullOrEmpty(userId)) return null; - return new BaGetPrincipal( - userId: userId, - userName: user.Identity.Name, - isSuperuser: false, - scopes: ApiKeyScopes.All, - packageGlobPattern: "*"); - } + return new BaGetPrincipal( + userId: userId, + userName: user.Identity.Name, + isSuperuser: false, + scopes: ApiKeyScopes.All, + packageGlobPattern: "*"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/CatalogClient.cs b/src/BaGet.Protocol/Catalog/CatalogClient.cs index f87089d95..a01a56981 100644 --- a/src/BaGet.Protocol/Catalog/CatalogClient.cs +++ b/src/BaGet.Protocol/Catalog/CatalogClient.cs @@ -3,46 +3,45 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class CatalogClient : ICatalogClient { - private class CatalogClient : ICatalogClient - { - private readonly NuGetClientFactory _clientfactory; + private readonly NuGetClientFactory _clientfactory; - public CatalogClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } + public CatalogClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } - public async Task GetIndexAsync(CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); + public async Task GetIndexAsync(CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); - return await client.GetIndexAsync(cancellationToken); - } + return await client.GetIndexAsync(cancellationToken); + } - public async Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); + public async Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); - return await client.GetPageAsync(pageUrl, cancellationToken); - } + return await client.GetPageAsync(pageUrl, cancellationToken); + } - public async Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); + public async Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); - return await client.GetPackageDetailsLeafAsync(leafUrl, cancellationToken); - } + return await client.GetPackageDetailsLeafAsync(leafUrl, cancellationToken); + } - public async Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); + public async Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetCatalogClientAsync(cancellationToken); - return await client.GetPackageDeleteLeafAsync(leafUrl, cancellationToken); - } + return await client.GetPackageDeleteLeafAsync(leafUrl, cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/CatalogProcessor.cs b/src/BaGet.Protocol/Catalog/CatalogProcessor.cs index 13c5cc274..19992cd44 100644 --- a/src/BaGet.Protocol/Catalog/CatalogProcessor.cs +++ b/src/BaGet.Protocol/Catalog/CatalogProcessor.cs @@ -4,198 +4,197 @@ using BaGet.Protocol.Models; using Microsoft.Extensions.Logging; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// Processes catalog leafs in chronological order. +/// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/CatalogProcessor.cs +/// +public class CatalogProcessor { + private readonly ICatalogLeafProcessor _leafProcessor; + private readonly ICatalogClient _client; + private readonly ICursor _cursor; + private readonly CatalogProcessorOptions _options; + private readonly ILogger _logger; + /// - /// Processes catalog leafs in chronological order. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/CatalogProcessor.cs + /// Create a processor to discover and download catalog leafs. Leafs are processed + /// by the . /// - public class CatalogProcessor + /// Cursor to track succesfully processed leafs. Leafs before the cursor are skipped. + /// The client to interact with the catalog resource. + /// The leaf processor. + /// The options to configure catalog processing. + /// The logger used for telemetry. + public CatalogProcessor( + ICursor cursor, + ICatalogClient client, + ICatalogLeafProcessor leafProcessor, + CatalogProcessorOptions options, + ILogger logger) { - private readonly ICatalogLeafProcessor _leafProcessor; - private readonly ICatalogClient _client; - private readonly ICursor _cursor; - private readonly CatalogProcessorOptions _options; - private readonly ILogger _logger; - - /// - /// Create a processor to discover and download catalog leafs. Leafs are processed - /// by the . - /// - /// Cursor to track succesfully processed leafs. Leafs before the cursor are skipped. - /// The client to interact with the catalog resource. - /// The leaf processor. - /// The options to configure catalog processing. - /// The logger used for telemetry. - public CatalogProcessor( - ICursor cursor, - ICatalogClient client, - ICatalogLeafProcessor leafProcessor, - CatalogProcessorOptions options, - ILogger logger) - { - _leafProcessor = leafProcessor ?? throw new ArgumentNullException(nameof(leafProcessor)); - _client = client ?? throw new ArgumentNullException(nameof(client)); - _cursor = cursor ?? throw new ArgumentNullException(nameof(cursor)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + _leafProcessor = leafProcessor ?? throw new ArgumentNullException(nameof(leafProcessor)); + _client = client ?? throw new ArgumentNullException(nameof(client)); + _cursor = cursor ?? throw new ArgumentNullException(nameof(cursor)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - /// - /// Discovers and downloads all of the catalog leafs after the current cursor value and before the maximum - /// commit timestamp found in the settings. Each catalog leaf is passed to the catalog leaf processor in - /// chronological order. After a commit is completed, its commit timestamp is written to the cursor, i.e. when - /// transitioning from commit timestamp A to B, A is written to the cursor so that it never is processed again. - /// - /// A token to cancel the task. - /// True if all of the catalog leaves found were processed successfully. - public async Task ProcessAsync(CancellationToken cancellationToken = default) - { - var minCommitTimestamp = await GetMinCommitTimestamp(cancellationToken); - _logger.LogInformation( - "Using time bounds {min:O} (exclusive) to {max:O} (inclusive).", - minCommitTimestamp, - _options.MaxCommitTimestamp); + /// + /// Discovers and downloads all of the catalog leafs after the current cursor value and before the maximum + /// commit timestamp found in the settings. Each catalog leaf is passed to the catalog leaf processor in + /// chronological order. After a commit is completed, its commit timestamp is written to the cursor, i.e. when + /// transitioning from commit timestamp A to B, A is written to the cursor so that it never is processed again. + /// + /// A token to cancel the task. + /// True if all of the catalog leaves found were processed successfully. + public async Task ProcessAsync(CancellationToken cancellationToken = default) + { + var minCommitTimestamp = await GetMinCommitTimestamp(cancellationToken); + _logger.LogInformation( + "Using time bounds {min:O} (exclusive) to {max:O} (inclusive).", + minCommitTimestamp, + _options.MaxCommitTimestamp); - return await ProcessIndexAsync(minCommitTimestamp, cancellationToken); - } + return await ProcessIndexAsync(minCommitTimestamp, cancellationToken); + } - private async Task ProcessIndexAsync(DateTimeOffset minCommitTimestamp, CancellationToken cancellationToken) + private async Task ProcessIndexAsync(DateTimeOffset minCommitTimestamp, CancellationToken cancellationToken) + { + var index = await _client.GetIndexAsync(cancellationToken); + + var pageItems = index.GetPagesInBounds( + minCommitTimestamp, + _options.MaxCommitTimestamp); + _logger.LogInformation( + "{pages} pages were in the time bounds, out of {totalPages}.", + pageItems.Count, + index.Items.Count); + + var success = true; + for (var i = 0; i < pageItems.Count; i++) { - var index = await _client.GetIndexAsync(cancellationToken); - - var pageItems = index.GetPagesInBounds( - minCommitTimestamp, - _options.MaxCommitTimestamp); - _logger.LogInformation( - "{pages} pages were in the time bounds, out of {totalPages}.", - pageItems.Count, - index.Items.Count); - - var success = true; - for (var i = 0; i < pageItems.Count; i++) + success = await ProcessPageAsync(minCommitTimestamp, pageItems[i], cancellationToken); + if (!success) { - success = await ProcessPageAsync(minCommitTimestamp, pageItems[i], cancellationToken); - if (!success) - { - _logger.LogWarning( - "{unprocessedPages} out of {pages} pages were left incomplete due to a processing failure.", - pageItems.Count - i, - pageItems.Count); - break; - } + _logger.LogWarning( + "{unprocessedPages} out of {pages} pages were left incomplete due to a processing failure.", + pageItems.Count - i, + pageItems.Count); + break; } - - return success; } - private async Task ProcessPageAsync( - DateTimeOffset minCommitTimestamp, - CatalogPageItem pageItem, - CancellationToken cancellationToken) + return success; + } + + private async Task ProcessPageAsync( + DateTimeOffset minCommitTimestamp, + CatalogPageItem pageItem, + CancellationToken cancellationToken) + { + var page = await _client.GetPageAsync(pageItem.CatalogPageUrl, cancellationToken); + + var leafItems = page.GetLeavesInBounds( + minCommitTimestamp, + _options.MaxCommitTimestamp, + _options.ExcludeRedundantLeaves); + _logger.LogInformation( + "On page {page}, {leaves} out of {totalLeaves} were in the time bounds.", + pageItem.CatalogPageUrl, + leafItems.Count, + page.Items.Count); + + DateTimeOffset? newCursor = null; + var success = true; + for (var i = 0; i < leafItems.Count; i++) { - var page = await _client.GetPageAsync(pageItem.CatalogPageUrl, cancellationToken); - - var leafItems = page.GetLeavesInBounds( - minCommitTimestamp, - _options.MaxCommitTimestamp, - _options.ExcludeRedundantLeaves); - _logger.LogInformation( - "On page {page}, {leaves} out of {totalLeaves} were in the time bounds.", - pageItem.CatalogPageUrl, - leafItems.Count, - page.Items.Count); - - DateTimeOffset? newCursor = null; - var success = true; - for (var i = 0; i < leafItems.Count; i++) + var leafItem = leafItems[i]; + + if (newCursor.HasValue && newCursor.Value != leafItem.CommitTimestamp) { - var leafItem = leafItems[i]; - - if (newCursor.HasValue && newCursor.Value != leafItem.CommitTimestamp) - { - await _cursor.SetAsync(newCursor.Value, cancellationToken); - } - - newCursor = leafItem.CommitTimestamp; - - success = await ProcessLeafAsync(leafItem, cancellationToken); - if (!success) - { - _logger.LogWarning( - "{unprocessedLeaves} out of {leaves} leaves were left incomplete due to a processing failure.", - leafItems.Count - i, - leafItems.Count); - break; - } + await _cursor.SetAsync(newCursor.Value, cancellationToken); } - if (newCursor.HasValue && success) + newCursor = leafItem.CommitTimestamp; + + success = await ProcessLeafAsync(leafItem, cancellationToken); + if (!success) { - await _cursor.SetAsync(newCursor.Value); + _logger.LogWarning( + "{unprocessedLeaves} out of {leaves} leaves were left incomplete due to a processing failure.", + leafItems.Count - i, + leafItems.Count); + break; } + } - return success; + if (newCursor.HasValue && success) + { + await _cursor.SetAsync(newCursor.Value); } - private async Task ProcessLeafAsync(CatalogLeafItem leafItem, CancellationToken cancellationToken) + return success; + } + + private async Task ProcessLeafAsync(CatalogLeafItem leafItem, CancellationToken cancellationToken) + { + bool success; + try { - bool success; - try + if (leafItem.IsPackageDelete()) { - if (leafItem.IsPackageDelete()) - { - var packageDelete = await _client.GetPackageDeleteLeafAsync(leafItem.CatalogLeafUrl); - success = await _leafProcessor.ProcessPackageDeleteAsync(packageDelete, cancellationToken); - } - else if (leafItem.IsPackageDetails()) - { - var packageDetails = await _client.GetPackageDetailsLeafAsync(leafItem.CatalogLeafUrl); - success = await _leafProcessor.ProcessPackageDetailsAsync(packageDetails, cancellationToken); - } - else - { - throw new NotSupportedException($"The catalog leaf type '{leafItem.Type}' is not supported."); - } + var packageDelete = await _client.GetPackageDeleteLeafAsync(leafItem.CatalogLeafUrl); + success = await _leafProcessor.ProcessPackageDeleteAsync(packageDelete, cancellationToken); } - catch (Exception exception) + else if (leafItem.IsPackageDetails()) { - _logger.LogError( - 0, - exception, - "An exception was thrown while processing leaf {leafUrl}.", - leafItem.CatalogLeafUrl); - success = false; + var packageDetails = await _client.GetPackageDetailsLeafAsync(leafItem.CatalogLeafUrl); + success = await _leafProcessor.ProcessPackageDetailsAsync(packageDetails, cancellationToken); } - - if (!success) + else { - _logger.LogWarning( - "Failed to process leaf {leafUrl} ({packageId} {packageVersion}, {leafType}).", - leafItem.CatalogLeafUrl, - leafItem.PackageId, - leafItem.PackageVersion, - leafItem.Type); + throw new NotSupportedException($"The catalog leaf type '{leafItem.Type}' is not supported."); } - - return success; + } + catch (Exception exception) + { + _logger.LogError( + 0, + exception, + "An exception was thrown while processing leaf {leafUrl}.", + leafItem.CatalogLeafUrl); + success = false; } - private async Task GetMinCommitTimestamp(CancellationToken cancellationToken) + if (!success) { - var minCommitTimestamp = await _cursor.GetAsync(cancellationToken); + _logger.LogWarning( + "Failed to process leaf {leafUrl} ({packageId} {packageVersion}, {leafType}).", + leafItem.CatalogLeafUrl, + leafItem.PackageId, + leafItem.PackageVersion, + leafItem.Type); + } - minCommitTimestamp = minCommitTimestamp - ?? _options.DefaultMinCommitTimestamp - ?? _options.MinCommitTimestamp; + return success; + } - if (minCommitTimestamp.Value < _options.MinCommitTimestamp) - { - minCommitTimestamp = _options.MinCommitTimestamp; - } + private async Task GetMinCommitTimestamp(CancellationToken cancellationToken) + { + var minCommitTimestamp = await _cursor.GetAsync(cancellationToken); + + minCommitTimestamp = minCommitTimestamp + ?? _options.DefaultMinCommitTimestamp + ?? _options.MinCommitTimestamp; - return minCommitTimestamp.Value; + if (minCommitTimestamp.Value < _options.MinCommitTimestamp) + { + minCommitTimestamp = _options.MinCommitTimestamp; } + + return minCommitTimestamp.Value; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/CatalogProcessorOptions.cs b/src/BaGet.Protocol/Catalog/CatalogProcessorOptions.cs index 1b9bd5cc1..0617a01db 100644 --- a/src/BaGet.Protocol/Catalog/CatalogProcessorOptions.cs +++ b/src/BaGet.Protocol/Catalog/CatalogProcessorOptions.cs @@ -1,36 +1,35 @@ using System; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// The options to configure . +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/CatalogProcessorSettings.cs +/// +public class CatalogProcessorOptions { /// - /// The options to configure . - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/CatalogProcessorSettings.cs + /// The minimum commit timestamp to use when no cursor value has been saved. /// - public class CatalogProcessorOptions - { - /// - /// The minimum commit timestamp to use when no cursor value has been saved. - /// - public DateTimeOffset? DefaultMinCommitTimestamp { get; set; } + public DateTimeOffset? DefaultMinCommitTimestamp { get; set; } - /// - /// The absolute minimum (exclusive) commit timestamp to process in the catalog. - /// Use this to filter out catalog items that are "too old". - /// Set this to to process all catalog items. - /// - public DateTimeOffset MinCommitTimestamp { get; set; } + /// + /// The absolute minimum (exclusive) commit timestamp to process in the catalog. + /// Use this to filter out catalog items that are "too old". + /// Set this to to process all catalog items. + /// + public DateTimeOffset MinCommitTimestamp { get; set; } - /// - /// The absolute maximum (inclusive) commit timestamp to process in the catalog. - /// Use this to filter out catalog items that are "too new". - /// Set this to to process all catalog items. - /// - public DateTimeOffset MaxCommitTimestamp { get; set; } + /// + /// The absolute maximum (inclusive) commit timestamp to process in the catalog. + /// Use this to filter out catalog items that are "too new". + /// Set this to to process all catalog items. + /// + public DateTimeOffset MaxCommitTimestamp { get; set; } - /// - /// If multiple catalog leaves are found in a page concerning the same package ID and version, only the latest - /// is processed. - /// - public bool ExcludeRedundantLeaves { get; set; } - } -} + /// + /// If multiple catalog leaves are found in a page concerning the same package ID and version, only the latest + /// is processed. + /// + public bool ExcludeRedundantLeaves { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/FileCursor.cs b/src/BaGet.Protocol/Catalog/FileCursor.cs index 9be09c2c9..3b90aedd8 100644 --- a/src/BaGet.Protocol/Catalog/FileCursor.cs +++ b/src/BaGet.Protocol/Catalog/FileCursor.cs @@ -6,54 +6,53 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// A cursor implementation which stores the cursor in local file. The cursor value is written to the file as +/// a JSON object. +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/FileCursor.cs +/// +public class FileCursor : ICursor { - /// - /// A cursor implementation which stores the cursor in local file. The cursor value is written to the file as - /// a JSON object. - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/FileCursor.cs - /// - public class FileCursor : ICursor - { - private readonly string _path; - private readonly ILogger _logger; + private readonly string _path; + private readonly ILogger _logger; - public FileCursor(string path, ILogger logger) - { - _path = path ?? throw new ArgumentNullException(nameof(path)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public FileCursor(string path, ILogger logger) + { + _path = path ?? throw new ArgumentNullException(nameof(path)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public async Task GetAsync(CancellationToken cancellationToken) + public async Task GetAsync(CancellationToken cancellationToken) + { + try { - try - { - using (var file = File.OpenRead(_path)) - { - var data = await JsonSerializer.DeserializeAsync(file, options: null, cancellationToken); - _logger.LogDebug("Read cursor value {cursor:O} from {path}.", data.Value, _path); - return data.Value; - } - } - catch (Exception e) when (e is FileNotFoundException || e is JsonException) + using (var file = File.OpenRead(_path)) { - return null; + var data = await JsonSerializer.DeserializeAsync(file, options: null, cancellationToken); + _logger.LogDebug("Read cursor value {cursor:O} from {path}.", data.Value, _path); + return data.Value; } } - - public Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken) + catch (Exception e) when (e is FileNotFoundException || e is JsonException) { - var data = new Data { Value = value }; - var jsonString = JsonSerializer.Serialize(data); - File.WriteAllText(_path, jsonString); - _logger.LogDebug("Wrote cursor value {cursor:O} to {path}.", data.Value, _path); - return Task.CompletedTask; + return null; } + } - private class Data - { - [JsonPropertyName("value")] - public DateTimeOffset Value { get; set; } - } + public Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken) + { + var data = new Data { Value = value }; + var jsonString = JsonSerializer.Serialize(data); + File.WriteAllText(_path, jsonString); + _logger.LogDebug("Wrote cursor value {cursor:O} to {path}.", data.Value, _path); + return Task.CompletedTask; + } + + private class Data + { + [JsonPropertyName("value")] + public DateTimeOffset Value { get; set; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/ICatalogClient.cs b/src/BaGet.Protocol/Catalog/ICatalogClient.cs index 65dbb4604..7331c3766 100644 --- a/src/BaGet.Protocol/Catalog/ICatalogClient.cs +++ b/src/BaGet.Protocol/Catalog/ICatalogClient.cs @@ -2,55 +2,54 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The Catalog client, used to discover package events. +/// You can use this resource to query for all published packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource +/// +public interface ICatalogClient { /// - /// The Catalog client, used to discover package events. - /// You can use this resource to query for all published packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource + /// Get the entry point for the catalog resource. + /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-index /// - public interface ICatalogClient - { - /// - /// Get the entry point for the catalog resource. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-index - /// - /// A token to cancel the task. - /// The catalog index. - Task GetIndexAsync(CancellationToken cancellationToken = default); + /// A token to cancel the task. + /// The catalog index. + Task GetIndexAsync(CancellationToken cancellationToken = default); - /// - /// Get a single catalog page, used to discover catalog leafs. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page - /// - /// The URL of the page, from the . - /// A token to cancel the task. - /// A catalog page. - Task GetPageAsync( - string pageUrl, - CancellationToken cancellationToken = default); + /// + /// Get a single catalog page, used to discover catalog leafs. + /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page + /// + /// The URL of the page, from the . + /// A token to cancel the task. + /// A catalog page. + Task GetPageAsync( + string pageUrl, + CancellationToken cancellationToken = default); - /// - /// Get a single catalog leaf, representing a package deletion event. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf - /// - /// The URL of the leaf, from a . - /// A token to cancel the task. - /// A catalog leaf. - Task GetPackageDeleteLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default); + /// + /// Get a single catalog leaf, representing a package deletion event. + /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf + /// + /// The URL of the leaf, from a . + /// A token to cancel the task. + /// A catalog leaf. + Task GetPackageDeleteLeafAsync( + string leafUrl, + CancellationToken cancellationToken = default); - /// - /// Get a single catalog leaf, representing a package creation or update event. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf - /// - /// The URL of the leaf, from a . - /// A token to cancel the task. - /// A catalog leaf. - Task GetPackageDetailsLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default); - } -} + /// + /// Get a single catalog leaf, representing a package creation or update event. + /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf + /// + /// The URL of the leaf, from a . + /// A token to cancel the task. + /// A catalog leaf. + Task GetPackageDetailsLeafAsync( + string leafUrl, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/ICatalogLeafProcessor.cs b/src/BaGet.Protocol/Catalog/ICatalogLeafProcessor.cs index c45641a72..ca4875d34 100644 --- a/src/BaGet.Protocol/Catalog/ICatalogLeafProcessor.cs +++ b/src/BaGet.Protocol/Catalog/ICatalogLeafProcessor.cs @@ -2,37 +2,36 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// An interface which allows custom processing of catalog leaves. This interface should be implemented when the +/// catalog leaf documents need to be downloaded and processed in chronological order. +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/master/src/NuGet.Protocol.Catalog/ICatalogLeafProcessor.cs +/// +public interface ICatalogLeafProcessor { /// - /// An interface which allows custom processing of catalog leaves. This interface should be implemented when the - /// catalog leaf documents need to be downloaded and processed in chronological order. - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/master/src/NuGet.Protocol.Catalog/ICatalogLeafProcessor.cs + /// Process a catalog leaf containing package details. This method should return false or throw an exception + /// if the catalog leaf cannot be processed. In this case, the will stop + /// processing items. Note that the same package ID/version combination can be passed to this multiple times, + /// for example due to an edit in the package metadata or due to a transient error and retry on the part of the + /// . /// - public interface ICatalogLeafProcessor - { - /// - /// Process a catalog leaf containing package details. This method should return false or throw an exception - /// if the catalog leaf cannot be processed. In this case, the will stop - /// processing items. Note that the same package ID/version combination can be passed to this multiple times, - /// for example due to an edit in the package metadata or due to a transient error and retry on the part of the - /// . - /// - /// The leaf document. - /// A token to cancel the task. - /// True, if the leaf was successfully processed. False, otherwise. - Task ProcessPackageDetailsAsync(PackageDetailsCatalogLeaf leaf, CancellationToken cancellationToken = default); + /// The leaf document. + /// A token to cancel the task. + /// True, if the leaf was successfully processed. False, otherwise. + Task ProcessPackageDetailsAsync(PackageDetailsCatalogLeaf leaf, CancellationToken cancellationToken = default); - /// - /// Process a catalog leaf containing a package delete. This method should return false or throw an exception - /// if the catalog leaf cannot be processed. In this case, the will stop - /// processing items. Note that the same package ID/version combination can be passed to this multiple times, - /// for example due to a package being deleted again due to a transient error and retry on the part of the - /// . - /// - /// The leaf document. - /// A token to cancel the task. - /// True, if the leaf was successfully processed. False, otherwise. - Task ProcessPackageDeleteAsync(PackageDeleteCatalogLeaf leaf, CancellationToken cancellationToken = default); - } -} + /// + /// Process a catalog leaf containing a package delete. This method should return false or throw an exception + /// if the catalog leaf cannot be processed. In this case, the will stop + /// processing items. Note that the same package ID/version combination can be passed to this multiple times, + /// for example due to a package being deleted again due to a transient error and retry on the part of the + /// . + /// + /// The leaf document. + /// A token to cancel the task. + /// True, if the leaf was successfully processed. False, otherwise. + Task ProcessPackageDeleteAsync(PackageDeleteCatalogLeaf leaf, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/ICursor.cs b/src/BaGet.Protocol/Catalog/ICursor.cs index a564f8c59..f30eceffa 100644 --- a/src/BaGet.Protocol/Catalog/ICursor.cs +++ b/src/BaGet.Protocol/Catalog/ICursor.cs @@ -2,29 +2,28 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// The NuGet Catalog resource is an append-only data structure indexed by time. +/// The tracks up to what point in the catalog has been successfully +/// processed. The value is a catalog commit timestamp. +/// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#cursor +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/ICursor.cs +/// +public interface ICursor { /// - /// The NuGet Catalog resource is an append-only data structure indexed by time. - /// The tracks up to what point in the catalog has been successfully - /// processed. The value is a catalog commit timestamp. - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#cursor - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/3a468fe534a03dcced897eb5992209fdd3c4b6c9/src/NuGet.Protocol.Catalog/ICursor.cs + /// Get the value of the cursor. /// - public interface ICursor - { - /// - /// Get the value of the cursor. - /// - /// A token to cancel the task. - /// The cursor value. Null if the cursor has no value yet. - Task GetAsync(CancellationToken cancellationToken = default); + /// A token to cancel the task. + /// The cursor value. Null if the cursor has no value yet. + Task GetAsync(CancellationToken cancellationToken = default); - /// - /// Set the value of the cursor. - /// - /// The new cursor value. - /// A token to cancel the task. - Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken = default); - } -} + /// + /// Set the value of the cursor. + /// + /// The new cursor value. + /// A token to cancel the task. + Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/NullCatalogClient.cs b/src/BaGet.Protocol/Catalog/NullCatalogClient.cs index b77dc15b0..e7a9811d9 100644 --- a/src/BaGet.Protocol/Catalog/NullCatalogClient.cs +++ b/src/BaGet.Protocol/Catalog/NullCatalogClient.cs @@ -4,33 +4,32 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +public class NullCatalogClient : ICatalogClient { - public class NullCatalogClient : ICatalogClient + public Task GetIndexAsync(CancellationToken cancellationToken = default) { - public Task GetIndexAsync(CancellationToken cancellationToken = default) + return Task.FromResult(new CatalogIndex { - return Task.FromResult(new CatalogIndex - { - CommitTimestamp = DateTimeOffset.MinValue, - Count = 0, - Items = new List() - }); - } + CommitTimestamp = DateTimeOffset.MinValue, + Count = 0, + Items = new List() + }); + } - public Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) - { - throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog pages."); - } + public Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) + { + throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog pages."); + } - public Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog leaves."); - } + public Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) + { + throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog leaves."); + } - public Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog leaves."); - } + public Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) + { + throw new NotSupportedException($"{nameof(NullCatalogClient)} does not support loading catalog leaves."); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/NullCursor.cs b/src/BaGet.Protocol/Catalog/NullCursor.cs index 8af2f2f57..91b03530c 100644 --- a/src/BaGet.Protocol/Catalog/NullCursor.cs +++ b/src/BaGet.Protocol/Catalog/NullCursor.cs @@ -2,23 +2,22 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Catalog +namespace BaGet.Protocol.Catalog; + +/// +/// A cursor that does not persist any state. Use this with a +/// to process all leafs each time +/// is called. +/// +public class NullCursor : ICursor { - /// - /// A cursor that does not persist any state. Use this with a - /// to process all leafs each time - /// is called. - /// - public class NullCursor : ICursor + public Task GetAsync(CancellationToken cancellationToken = default) { - public Task GetAsync(CancellationToken cancellationToken = default) - { - return Task.FromResult(null); - } + return Task.FromResult(null); + } - public Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } + public Task SetAsync(DateTimeOffset value, CancellationToken cancellationToken = default) + { + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Catalog/RawCatalogClient.cs b/src/BaGet.Protocol/Catalog/RawCatalogClient.cs index d773e3654..3ddc2cbe4 100644 --- a/src/BaGet.Protocol/Catalog/RawCatalogClient.cs +++ b/src/BaGet.Protocol/Catalog/RawCatalogClient.cs @@ -5,60 +5,59 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +public class RawCatalogClient : ICatalogClient { - public class RawCatalogClient : ICatalogClient + private readonly HttpClient _httpClient; + private readonly string _catalogUrl; + + public RawCatalogClient(HttpClient httpClient, string catalogUrl) { - private readonly HttpClient _httpClient; - private readonly string _catalogUrl; + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _catalogUrl = catalogUrl ?? throw new ArgumentNullException(nameof(catalogUrl)); + } - public RawCatalogClient(HttpClient httpClient, string catalogUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _catalogUrl = catalogUrl ?? throw new ArgumentNullException(nameof(catalogUrl)); - } + public async Task GetIndexAsync(CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync(_catalogUrl, cancellationToken); + } - public async Task GetIndexAsync(CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync(_catalogUrl, cancellationToken); - } + public async Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync(pageUrl, cancellationToken); + } - public async Task GetPageAsync(string pageUrl, CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync(pageUrl, cancellationToken); - } + public async Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) + { + return await GetAndValidateLeafAsync( + "PackageDelete", + leafUrl, + cancellationToken); + } - public async Task GetPackageDeleteLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - return await GetAndValidateLeafAsync( - "PackageDelete", - leafUrl, - cancellationToken); - } + public async Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) + { + return await GetAndValidateLeafAsync( + "PackageDetails", + leafUrl, + cancellationToken); + } - public async Task GetPackageDetailsLeafAsync(string leafUrl, CancellationToken cancellationToken = default) - { - return await GetAndValidateLeafAsync( - "PackageDetails", - leafUrl, - cancellationToken); - } + private async Task GetAndValidateLeafAsync( + string leafType, + string leafUrl, + CancellationToken cancellationToken) where TCatalogLeaf : CatalogLeaf + { + var leaf = await _httpClient.GetFromJsonAsync(leafUrl, cancellationToken); - private async Task GetAndValidateLeafAsync( - string leafType, - string leafUrl, - CancellationToken cancellationToken) where TCatalogLeaf : CatalogLeaf + if (leaf.Type.FirstOrDefault() != leafType) { - var leaf = await _httpClient.GetFromJsonAsync(leafUrl, cancellationToken); - - if (leaf.Type.FirstOrDefault() != leafType) - { - throw new ArgumentException( - $"The leaf type found in the document does not match the expected '{leafType}' type.", - nameof(leafType)); - } - - return leaf; + throw new ArgumentException( + $"The leaf type found in the document does not match the expected '{leafType}' type.", + nameof(leafType)); } + + return leaf; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Converters/PackageDependencyRangeJsonConverter.cs b/src/BaGet.Protocol/Converters/PackageDependencyRangeJsonConverter.cs index 9514cb5d5..d88bab9cf 100644 --- a/src/BaGet.Protocol/Converters/PackageDependencyRangeJsonConverter.cs +++ b/src/BaGet.Protocol/Converters/PackageDependencyRangeJsonConverter.cs @@ -2,56 +2,55 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// This is an internal API that may be changed or removed without notice in any release. +/// +public class PackageDependencyRangeJsonConverter : JsonConverter { - /// - /// This is an internal API that may be changed or removed without notice in any release. - /// - public class PackageDependencyRangeJsonConverter : JsonConverter + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + if (reader.TokenType == JsonTokenType.String) { - if (reader.TokenType == JsonTokenType.String) - { - return reader.GetString(); - } + return reader.GetString(); + } + + // There are some quirky packages with arrays of dependency version ranges. + // In this case, we take the first element. + // Example: https://api.nuget.org/v3/catalog0/data/2016.02.21.11.06.01/dingu.generic.repo.ef7.1.0.0-beta2.json + if (reader.TokenType != JsonTokenType.StartArray) + { + throw new JsonException(); + } + + reader.Read(); + if (reader.TokenType != JsonTokenType.String) + { + throw new JsonException(); + } + + var result = reader.GetString(); - // There are some quirky packages with arrays of dependency version ranges. - // In this case, we take the first element. - // Example: https://api.nuget.org/v3/catalog0/data/2016.02.21.11.06.01/dingu.generic.repo.ef7.1.0.0-beta2.json - if (reader.TokenType != JsonTokenType.StartArray) + // Ignore all other strings until we reach the end of the array. + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndArray) { - throw new JsonException(); + break; } - reader.Read(); if (reader.TokenType != JsonTokenType.String) { throw new JsonException(); } - - var result = reader.GetString(); - - // Ignore all other strings until we reach the end of the array. - while (reader.Read()) - { - if (reader.TokenType == JsonTokenType.EndArray) - { - break; - } - - if (reader.TokenType != JsonTokenType.String) - { - throw new JsonException(); - } - } - - return result; } - public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) - { - writer.WriteStringValue(value); - } + return result; + } + + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + writer.WriteStringValue(value); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Converters/StringOrStringArrayJsonConverter.cs b/src/BaGet.Protocol/Converters/StringOrStringArrayJsonConverter.cs index d4ea42e04..68ced637b 100644 --- a/src/BaGet.Protocol/Converters/StringOrStringArrayJsonConverter.cs +++ b/src/BaGet.Protocol/Converters/StringOrStringArrayJsonConverter.cs @@ -3,58 +3,57 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// This is an internal API that may be changed or removed without notice in any release. +/// +public class StringOrStringArrayJsonConverter : JsonConverter> { - /// - /// This is an internal API that may be changed or removed without notice in any release. - /// - public class StringOrStringArrayJsonConverter : JsonConverter> + public override IReadOnlyList Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - public override IReadOnlyList Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + // Try to read a single string first. + if (reader.TokenType == JsonTokenType.String) + { + return new List { reader.GetString() }; + } + + // Try to read an array of strings. + if (reader.TokenType != JsonTokenType.StartArray) + { + throw new JsonException(); + } + + var result = new List(); + + while (reader.Read()) { - // Try to read a single string first. if (reader.TokenType == JsonTokenType.String) { - return new List { reader.GetString() }; + result.Add(reader.GetString()); } - - // Try to read an array of strings. - if (reader.TokenType != JsonTokenType.StartArray) + else if (reader.TokenType == JsonTokenType.EndArray) { - throw new JsonException(); + return result; } - - var result = new List(); - - while (reader.Read()) + else { - if (reader.TokenType == JsonTokenType.String) - { - result.Add(reader.GetString()); - } - else if (reader.TokenType == JsonTokenType.EndArray) - { - return result; - } - else - { - break; - } + break; } - - throw new JsonException(); } - public override void Write(Utf8JsonWriter writer, IReadOnlyList values, JsonSerializerOptions options) - { - writer.WriteStartArray(); + throw new JsonException(); + } - foreach (var value in values) - { - writer.WriteStringValue(value); - } + public override void Write(Utf8JsonWriter writer, IReadOnlyList values, JsonSerializerOptions options) + { + writer.WriteStartArray(); - writer.WriteEndArray(); + foreach (var value in values) + { + writer.WriteStringValue(value); } + + writer.WriteEndArray(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/EndpointFailover.cs b/src/BaGet.Protocol/EndpointFailover.cs index 017a7771f..ef0577bb7 100644 --- a/src/BaGet.Protocol/EndpointFailover.cs +++ b/src/BaGet.Protocol/EndpointFailover.cs @@ -8,123 +8,122 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// Runs an operation against the endpoints a service index advertises for one resource, +/// moving on to the next endpoint when an endpoint proves unusable. +/// +/// Only a failure of the endpoint itself causes a failover. A response that the server +/// produced is its answer, not a broken endpoint: a 404 means "there is nothing here" and +/// must never be retried elsewhere, or a missing package would be reported as an outage and +/// every request would cost one round trip per endpoint. +/// +internal static class EndpointFailover { /// - /// Runs an operation against the endpoints a service index advertises for one resource, - /// moving on to the next endpoint when an endpoint proves unusable. - /// - /// Only a failure of the endpoint itself causes a failover. A response that the server - /// produced is its answer, not a broken endpoint: a 404 means "there is nothing here" and - /// must never be retried elsewhere, or a missing package would be reported as an outage and - /// every request would cost one round trip per endpoint. + /// Run against the first endpoint that can serve it. /// - internal static class EndpointFailover + /// The client type, one per endpoint. + /// The operation's result. + /// The resource's clients, in the order they should be tried. + /// The operation to run against an endpoint. + /// A token to cancel the task. + /// The result from the first endpoint that answered. + /// + /// Every endpoint failed, and there was more than one. The inner exceptions are each + /// endpoint's failure, in the order the endpoints were tried. + /// + public static async Task ExecuteAsync( + IReadOnlyList clients, + Func> operation, + CancellationToken cancellationToken) { - /// - /// Run against the first endpoint that can serve it. - /// - /// The client type, one per endpoint. - /// The operation's result. - /// The resource's clients, in the order they should be tried. - /// The operation to run against an endpoint. - /// A token to cancel the task. - /// The result from the first endpoint that answered. - /// - /// Every endpoint failed, and there was more than one. The inner exceptions are each - /// endpoint's failure, in the order the endpoints were tried. - /// - public static async Task ExecuteAsync( - IReadOnlyList clients, - Func> operation, - CancellationToken cancellationToken) + if (clients == null) throw new ArgumentNullException(nameof(clients)); + if (operation == null) throw new ArgumentNullException(nameof(operation)); + + if (clients.Count == 0) { - if (clients == null) throw new ArgumentNullException(nameof(clients)); - if (operation == null) throw new ArgumentNullException(nameof(operation)); + throw new InvalidOperationException( + "The service index does not advertise any endpoint for this resource"); + } - if (clients.Count == 0) - { - throw new InvalidOperationException( - "The service index does not advertise any endpoint for this resource"); - } + List failures = null; - List failures = null; + foreach (var client in clients) + { + cancellationToken.ThrowIfCancellationRequested(); - foreach (var client in clients) + try { - cancellationToken.ThrowIfCancellationRequested(); - - try - { - return await operation(client, cancellationToken); - } - catch (Exception exception) when (IsEndpointFailure(exception, cancellationToken)) - { - failures = failures ?? new List(clients.Count); - failures.Add(exception); - } + return await operation(client, cancellationToken); } - - // Every endpoint failed. A resource with a single endpoint - by far the common case - - // keeps throwing exactly what that endpoint threw, so that existing error handling - // still works. Several endpoints report every failure, as knowing why each endpoint - // was unusable is the only way to tell a local network problem from a server outage. - if (failures.Count == 1) + catch (Exception exception) when (IsEndpointFailure(exception, cancellationToken)) { - ExceptionDispatchInfo.Capture(failures[0]).Throw(); + failures = failures ?? new List(clients.Count); + failures.Add(exception); } - - throw new AggregateException( - $"All {failures.Count} endpoints for this resource failed", - failures); } - /// - /// Whether a failure means the endpoint is unusable, so the next endpoint should be tried. - /// - internal static bool IsEndpointFailure(Exception exception, CancellationToken cancellationToken) + // Every endpoint failed. A resource with a single endpoint - by far the common case - + // keeps throwing exactly what that endpoint threw, so that existing error handling + // still works. Several endpoints report every failure, as knowing why each endpoint + // was unusable is the only way to tell a local network problem from a server outage. + if (failures.Count == 1) { - switch (exception) - { - // A transport failure - an unresolvable host, a refused connection, a TLS error, - // a dropped response - carries no status code: the endpoint never answered. - case HttpRequestException httpException: - return httpException.StatusCode == null - || IsEndpointFailure(httpException.StatusCode.Value); - - // HttpClient reports its own timeout as a cancellation. A cancellation the caller - // asked for is not an endpoint failure and must reach the caller untouched. - case OperationCanceledException _: - return !cancellationToken.IsCancellationRequested; - - case TimeoutException _: - return true; - - // A connection dropped while the response body was being read surfaces as an - // IOException - HttpIOException derives from it - rather than an - // HttpRequestException, because the request itself had already succeeded. - case IOException _: - return true; - - // The endpoint answered with something that is not the resource it advertised. - case JsonException _: - return true; - - default: - return false; - } + ExceptionDispatchInfo.Capture(failures[0]).Throw(); } - private static bool IsEndpointFailure(HttpStatusCode statusCode) + throw new AggregateException( + $"All {failures.Count} endpoints for this resource failed", + failures); + } + + /// + /// Whether a failure means the endpoint is unusable, so the next endpoint should be tried. + /// + internal static bool IsEndpointFailure(Exception exception, CancellationToken cancellationToken) + { + switch (exception) { - var code = (int)statusCode; + // A transport failure - an unresolvable host, a refused connection, a TLS error, + // a dropped response - carries no status code: the endpoint never answered. + case HttpRequestException httpException: + return httpException.StatusCode == null + || IsEndpointFailure(httpException.StatusCode.Value); + + // HttpClient reports its own timeout as a cancellation. A cancellation the caller + // asked for is not an endpoint failure and must reach the caller untouched. + case OperationCanceledException _: + return !cancellationToken.IsCancellationRequested; + + case TimeoutException _: + return true; + + // A connection dropped while the response body was being read surfaces as an + // IOException - HttpIOException derives from it - rather than an + // HttpRequestException, because the request itself had already succeeded. + case IOException _: + return true; + + // The endpoint answered with something that is not the resource it advertised. + case JsonException _: + return true; + + default: + return false; + } + } + + private static bool IsEndpointFailure(HttpStatusCode statusCode) + { + var code = (int)statusCode; - // The endpoint is reachable but cannot serve the request now, which is exactly what a - // second endpoint is for. Every other status - 404 included - is the server's answer. - if (code == (int)HttpStatusCode.RequestTimeout) return true; - if (code == 429 /* Too Many Requests */) return true; + // The endpoint is reachable but cannot serve the request now, which is exactly what a + // second endpoint is for. Every other status - 404 included - is the server's answer. + if (code == (int)HttpStatusCode.RequestTimeout) return true; + if (code == 429 /* Too Many Requests */) return true; - return code >= 500 && code <= 599; - } + return code >= 500 && code <= 599; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/CatalogModelExtensions.cs b/src/BaGet.Protocol/Extensions/CatalogModelExtensions.cs index 66f18ffd3..3a219cf8d 100644 --- a/src/BaGet.Protocol/Extensions/CatalogModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/CatalogModelExtensions.cs @@ -5,242 +5,241 @@ using NuGet.Frameworks; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the catalog API. +/// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/ModelExtensions.cs +/// +public static class CatalogModelExtensions { /// - /// These are documented interpretations of values returned by the catalog API. - /// Based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/ModelExtensions.cs + /// Gets the leaves that lie within the provided commit timestamp bounds. The result is sorted by commit + /// timestamp, then package ID, then package version (SemVer order). /// - public static class CatalogModelExtensions + /// + /// The exclusive lower time bound on . + /// The inclusive upper time bound on . + /// Only show the latest leaf concerning each package. + public static List GetLeavesInBounds( + this CatalogPage catalogPage, + DateTimeOffset minCommitTimestamp, + DateTimeOffset maxCommitTimestamp, + bool excludeRedundantLeaves) { - /// - /// Gets the leaves that lie within the provided commit timestamp bounds. The result is sorted by commit - /// timestamp, then package ID, then package version (SemVer order). - /// - /// - /// The exclusive lower time bound on . - /// The inclusive upper time bound on . - /// Only show the latest leaf concerning each package. - public static List GetLeavesInBounds( - this CatalogPage catalogPage, - DateTimeOffset minCommitTimestamp, - DateTimeOffset maxCommitTimestamp, - bool excludeRedundantLeaves) + var leaves = catalogPage + .Items + .Where(x => x.CommitTimestamp > minCommitTimestamp && x.CommitTimestamp <= maxCommitTimestamp) + .OrderBy(x => x.CommitTimestamp); + + if (excludeRedundantLeaves) { - var leaves = catalogPage - .Items - .Where(x => x.CommitTimestamp > minCommitTimestamp && x.CommitTimestamp <= maxCommitTimestamp) + leaves = leaves + .GroupBy(x => new + { + PackageId = x.PackageId.ToLowerInvariant(), + PackageVersion = x.ParsePackageVersion() + }) + .Select(x => x.Last()) .OrderBy(x => x.CommitTimestamp); - - if (excludeRedundantLeaves) - { - leaves = leaves - .GroupBy(x => new - { - PackageId = x.PackageId.ToLowerInvariant(), - PackageVersion = x.ParsePackageVersion() - }) - .Select(x => x.Last()) - .OrderBy(x => x.CommitTimestamp); - } - - return leaves - .ThenBy(x => x.PackageId, StringComparer.OrdinalIgnoreCase) - .ThenBy(x => x.ParsePackageVersion()) - .ToList(); } - /// - /// Gets the pages that may have catalog leaves within the provided commit timestamp bounds. The result is - /// sorted by commit timestamp. - /// - /// The catalog index to fetch pages from. - /// The exclusive lower time bound on . - /// The inclusive upper time bound on . - public static List GetPagesInBounds( - this CatalogIndex catalogIndex, - DateTimeOffset minCommitTimestamp, - DateTimeOffset maxCommitTimestamp) - { - return catalogIndex - .GetPagesInBoundsLazy(minCommitTimestamp, maxCommitTimestamp) - .ToList(); - } + return leaves + .ThenBy(x => x.PackageId, StringComparer.OrdinalIgnoreCase) + .ThenBy(x => x.ParsePackageVersion()) + .ToList(); + } - private static IEnumerable GetPagesInBoundsLazy( - this CatalogIndex catalogIndex, - DateTimeOffset minCommitTimestamp, - DateTimeOffset maxCommitTimestamp) + /// + /// Gets the pages that may have catalog leaves within the provided commit timestamp bounds. The result is + /// sorted by commit timestamp. + /// + /// The catalog index to fetch pages from. + /// The exclusive lower time bound on . + /// The inclusive upper time bound on . + public static List GetPagesInBounds( + this CatalogIndex catalogIndex, + DateTimeOffset minCommitTimestamp, + DateTimeOffset maxCommitTimestamp) + { + return catalogIndex + .GetPagesInBoundsLazy(minCommitTimestamp, maxCommitTimestamp) + .ToList(); + } + + private static IEnumerable GetPagesInBoundsLazy( + this CatalogIndex catalogIndex, + DateTimeOffset minCommitTimestamp, + DateTimeOffset maxCommitTimestamp) + { + // Filter out pages that fall entirely before the minimum commit timestamp and sort the remaining pages by + // commit timestamp. + var upperRange = catalogIndex + .Items + .Where(x => x.CommitTimestamp > minCommitTimestamp) + .OrderBy(x => x.CommitTimestamp); + + // Take pages from the sorted list until the commit timestamp goes past the maximum commit timestamp. This + // essentially LINQ's TakeWhile plus one more element. + foreach (var page in upperRange) { - // Filter out pages that fall entirely before the minimum commit timestamp and sort the remaining pages by - // commit timestamp. - var upperRange = catalogIndex - .Items - .Where(x => x.CommitTimestamp > minCommitTimestamp) - .OrderBy(x => x.CommitTimestamp); + yield return page; - // Take pages from the sorted list until the commit timestamp goes past the maximum commit timestamp. This - // essentially LINQ's TakeWhile plus one more element. - foreach (var page in upperRange) + if (page.CommitTimestamp > maxCommitTimestamp) { - yield return page; - - if (page.CommitTimestamp > maxCommitTimestamp) - { - break; - } + break; } } + } - /// - /// Parse the package version as a . - /// - /// The catalog leaf. - /// The package version. - public static NuGetVersion ParsePackageVersion(this ICatalogLeafItem leaf) + /// + /// Parse the package version as a . + /// + /// The catalog leaf. + /// The package version. + public static NuGetVersion ParsePackageVersion(this ICatalogLeafItem leaf) + { + return NuGetVersion.Parse(leaf.PackageVersion); + } + + /// + /// Parse the target framework as a . + /// + /// The package dependency group. + /// The framework. + public static NuGetFramework ParseTargetFramework(this DependencyGroupItem packageDependencyGroup) + { + if (string.IsNullOrEmpty(packageDependencyGroup.TargetFramework)) { - return NuGetVersion.Parse(leaf.PackageVersion); + return NuGetFramework.AnyFramework; } - /// - /// Parse the target framework as a . - /// - /// The package dependency group. - /// The framework. - public static NuGetFramework ParseTargetFramework(this DependencyGroupItem packageDependencyGroup) - { - if (string.IsNullOrEmpty(packageDependencyGroup.TargetFramework)) - { - return NuGetFramework.AnyFramework; - } + return NuGetFramework.Parse(packageDependencyGroup.TargetFramework); + } - return NuGetFramework.Parse(packageDependencyGroup.TargetFramework); + /// + /// Parse the version range as a . + /// + /// The package dependency. + /// The version range. + public static VersionRange ParseRange(this DependencyItem packageDependency) + { + // Server side treats invalid version ranges as empty strings. + // Source: https://github.com/NuGet/NuGet.Services.Metadata/blob/382c214c60993edfd7158bc6d223fafeebbc920c/src/Catalog/Helpers/NuGetVersionUtility.cs#L25-L34 + // Client side treats empty string version ranges as the "all" range. + // Source: https://github.com/NuGet/NuGet.Client/blob/849063018d8ee08625774a2dcd07ab84224dabb9/src/NuGet.Core/NuGet.Protocol/DependencyInfo/RegistrationUtility.cs#L20-L30 + // Example: https://api.nuget.org/v3/catalog0/data/2016.03.14.21.19.28/servicestack.extras.serilog.2.0.1.json + if (!VersionRange.TryParse(packageDependency.Range, out var parsed)) + { + return VersionRange.All; } - /// - /// Parse the version range as a . - /// - /// The package dependency. - /// The version range. - public static VersionRange ParseRange(this DependencyItem packageDependency) - { - // Server side treats invalid version ranges as empty strings. - // Source: https://github.com/NuGet/NuGet.Services.Metadata/blob/382c214c60993edfd7158bc6d223fafeebbc920c/src/Catalog/Helpers/NuGetVersionUtility.cs#L25-L34 - // Client side treats empty string version ranges as the "all" range. - // Source: https://github.com/NuGet/NuGet.Client/blob/849063018d8ee08625774a2dcd07ab84224dabb9/src/NuGet.Core/NuGet.Protocol/DependencyInfo/RegistrationUtility.cs#L20-L30 - // Example: https://api.nuget.org/v3/catalog0/data/2016.03.14.21.19.28/servicestack.extras.serilog.2.0.1.json - if (!VersionRange.TryParse(packageDependency.Range, out var parsed)) - { - return VersionRange.All; - } + return parsed; + } - return parsed; - } + /// + /// Determines if the provided catalog leaf is a package delete. + /// + /// The catalog leaf. + /// True if the catalog leaf represents a package delete. + public static bool IsPackageDelete(this CatalogLeafItem leaf) + { + return leaf.Type == "nuget:PackageDelete"; + } - /// - /// Determines if the provided catalog leaf is a package delete. - /// - /// The catalog leaf. - /// True if the catalog leaf represents a package delete. - public static bool IsPackageDelete(this CatalogLeafItem leaf) - { - return leaf.Type == "nuget:PackageDelete"; - } + /// + /// Determines if the provided catalog leaf is a package delete. + /// + /// The catalog leaf. + /// True if the catalog leaf represents a package delete. + public static bool IsPackageDelete(this CatalogLeaf leaf) + { + return leaf.Type.FirstOrDefault() == "PackageDelete"; + } - /// - /// Determines if the provided catalog leaf is a package delete. - /// - /// The catalog leaf. - /// True if the catalog leaf represents a package delete. - public static bool IsPackageDelete(this CatalogLeaf leaf) - { - return leaf.Type.FirstOrDefault() == "PackageDelete"; - } + /// + /// Determines if the provided catalog leaf is contains package details. + /// + /// The catalog leaf. + /// True if the catalog leaf contains package details. + public static bool IsPackageDetails(this CatalogLeafItem leaf) + { + return leaf.Type == "nuget:PackageDetails"; + } - /// - /// Determines if the provided catalog leaf is contains package details. - /// - /// The catalog leaf. - /// True if the catalog leaf contains package details. - public static bool IsPackageDetails(this CatalogLeafItem leaf) - { - return leaf.Type == "nuget:PackageDetails"; - } + /// + /// Determines if the provided catalog leaf is contains package details. + /// + /// The catalog leaf. + /// True if the catalog leaf contains package details. + public static bool IsPackageDetails(this CatalogLeaf leaf) + { + return leaf.Type.FirstOrDefault() == "PackageDetails"; + } - /// - /// Determines if the provided catalog leaf is contains package details. - /// - /// The catalog leaf. - /// True if the catalog leaf contains package details. - public static bool IsPackageDetails(this CatalogLeaf leaf) + /// + /// Determines if the provided package details leaf represents a listed package. + /// + /// The catalog leaf. + /// True if the package is listed. + public static bool IsListed(this PackageDetailsCatalogLeaf leaf) + { + if (leaf.Listed.HasValue) { - return leaf.Type.FirstOrDefault() == "PackageDetails"; + return leaf.Listed.Value; } - /// - /// Determines if the provided package details leaf represents a listed package. - /// - /// The catalog leaf. - /// True if the package is listed. - public static bool IsListed(this PackageDetailsCatalogLeaf leaf) - { - if (leaf.Listed.HasValue) - { - return leaf.Listed.Value; - } + // A published year of 1900 indicates that this package is unlisted, when the listed property itself is + // not present (legacy behavior). + // Example: https://api.nuget.org/v3/catalog0/data/2015.02.01.06.22.45/antixss.4.0.1.json + return leaf.Published.Year != 1900; + } - // A published year of 1900 indicates that this package is unlisted, when the listed property itself is - // not present (legacy behavior). - // Example: https://api.nuget.org/v3/catalog0/data/2015.02.01.06.22.45/antixss.4.0.1.json - return leaf.Published.Year != 1900; + /// + /// Determines if the provied package details leaf represents a SemVer 2.0.0 package. A package is considered + /// SemVer 2.0.0 if it's version is SemVer 2.0.0 or one of its dependency version ranges is SemVer 2.0.0. + /// + /// The catalog leaf. + /// True if the package is SemVer 2.0.0. + public static bool IsSemVer2(this PackageDetailsCatalogLeaf leaf) + { + var parsedPackageVersion = leaf.ParsePackageVersion(); + if (parsedPackageVersion.IsSemVer2) + { + return true; } - /// - /// Determines if the provied package details leaf represents a SemVer 2.0.0 package. A package is considered - /// SemVer 2.0.0 if it's version is SemVer 2.0.0 or one of its dependency version ranges is SemVer 2.0.0. - /// - /// The catalog leaf. - /// True if the package is SemVer 2.0.0. - public static bool IsSemVer2(this PackageDetailsCatalogLeaf leaf) + if (leaf.VerbatimVersion != null) { - var parsedPackageVersion = leaf.ParsePackageVersion(); - if (parsedPackageVersion.IsSemVer2) + var parsedVerbatimVersion = NuGetVersion.Parse(leaf.VerbatimVersion); + if (parsedVerbatimVersion.IsSemVer2) { return true; } + } - if (leaf.VerbatimVersion != null) + if (leaf.DependencyGroups != null) + { + foreach (var dependencyGroup in leaf.DependencyGroups) { - var parsedVerbatimVersion = NuGetVersion.Parse(leaf.VerbatimVersion); - if (parsedVerbatimVersion.IsSemVer2) + // Example: https://api.nuget.org/v3/catalog0/data/2018.10.28.07.42.42/mvcsitemapprovider.3.3.0-pre1.json + if (dependencyGroup.Dependencies == null) { - return true; + continue; } - } - if (leaf.DependencyGroups != null) - { - foreach (var dependencyGroup in leaf.DependencyGroups) + foreach (var dependency in dependencyGroup.Dependencies) { - // Example: https://api.nuget.org/v3/catalog0/data/2018.10.28.07.42.42/mvcsitemapprovider.3.3.0-pre1.json - if (dependencyGroup.Dependencies == null) + var versionRange = dependency.ParseRange(); + if ((versionRange.MaxVersion != null && versionRange.MaxVersion.IsSemVer2) + || (versionRange.MinVersion != null && versionRange.MinVersion.IsSemVer2)) { - continue; - } - - foreach (var dependency in dependencyGroup.Dependencies) - { - var versionRange = dependency.ParseRange(); - if ((versionRange.MaxVersion != null && versionRange.MaxVersion.IsSemVer2) - || (versionRange.MinVersion != null && versionRange.MinVersion.IsSemVer2)) - { - return true; - } + return true; } } } - - return false; } + + return false; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/HttpClientExtensions.cs b/src/BaGet.Protocol/Extensions/HttpClientExtensions.cs index 95db48fd0..cdd432e73 100644 --- a/src/BaGet.Protocol/Extensions/HttpClientExtensions.cs +++ b/src/BaGet.Protocol/Extensions/HttpClientExtensions.cs @@ -4,70 +4,69 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +internal static class HttpClientExtensions { - internal static class HttpClientExtensions + /// + /// Deserialize JSON content. + /// + /// The JSON type to deserialize. + /// The HTTP client that will perform the request. + /// The request URI. + /// A token to cancel the task. + /// The deserialized JSON content + public static async Task GetFromJsonAsync( + this HttpClient httpClient, + string requestUri, + CancellationToken cancellationToken = default) { - /// - /// Deserialize JSON content. - /// - /// The JSON type to deserialize. - /// The HTTP client that will perform the request. - /// The request URI. - /// A token to cancel the task. - /// The deserialized JSON content - public static async Task GetFromJsonAsync( - this HttpClient httpClient, - string requestUri, - CancellationToken cancellationToken = default) + using (var response = await httpClient.GetAsync( + requestUri, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken)) { - using (var response = await httpClient.GetAsync( - requestUri, - HttpCompletionOption.ResponseHeadersRead, - cancellationToken)) - { - // This is similar to System.Net.Http.Json's implementation, however, - // this does not validate that the response's content type indicates JSON content. - response.EnsureSuccessStatusCode(); + // This is similar to System.Net.Http.Json's implementation, however, + // this does not validate that the response's content type indicates JSON content. + response.EnsureSuccessStatusCode(); - using (var stream = await response.Content.ReadAsStreamAsync()) - { - return await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); - } + using (var stream = await response.Content.ReadAsStreamAsync()) + { + return await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); } } + } - /// - /// Deserialize JSON content. If the HTTP response status code is 404, - /// returns the default value. - /// - /// The JSON type to deserialize. - /// The HTTP client that will perform the request. - /// The request URI. - /// A token to cancel the task. - /// The JSON content, or, the default value if the HTTP response status code is 404. - public static async Task GetFromJsonOrDefaultAsync( - this HttpClient httpClient, - string requestUri, - CancellationToken cancellationToken = default) + /// + /// Deserialize JSON content. If the HTTP response status code is 404, + /// returns the default value. + /// + /// The JSON type to deserialize. + /// The HTTP client that will perform the request. + /// The request URI. + /// A token to cancel the task. + /// The JSON content, or, the default value if the HTTP response status code is 404. + public static async Task GetFromJsonOrDefaultAsync( + this HttpClient httpClient, + string requestUri, + CancellationToken cancellationToken = default) + { + using (var response = await httpClient.GetAsync( + requestUri, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken)) { - using (var response = await httpClient.GetAsync( - requestUri, - HttpCompletionOption.ResponseHeadersRead, - cancellationToken)) + if (response.StatusCode == HttpStatusCode.NotFound) { - if (response.StatusCode == HttpStatusCode.NotFound) - { - return default; - } + return default; + } - response.EnsureSuccessStatusCode(); + response.EnsureSuccessStatusCode(); - using (var stream = await response.Content.ReadAsStreamAsync()) - { - return await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); - } + using (var stream = await response.Content.ReadAsStreamAsync()) + { + return await JsonSerializer.DeserializeAsync(stream, cancellationToken: cancellationToken); } } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/NuGetClientFactoryExtensions.cs b/src/BaGet.Protocol/Extensions/NuGetClientFactoryExtensions.cs index 5a17073d8..0efd38764 100644 --- a/src/BaGet.Protocol/Extensions/NuGetClientFactoryExtensions.cs +++ b/src/BaGet.Protocol/Extensions/NuGetClientFactoryExtensions.cs @@ -1,35 +1,34 @@ using BaGet.Protocol.Catalog; using Microsoft.Extensions.Logging; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public static class NuGetClientFactoryExtensions { - public static class NuGetClientFactoryExtensions + /// + /// Create a new to discover and download catalog leafs. + /// Leafs are processed by the . + /// + /// The factory used to create NuGet clients. + /// Cursor to track succesfully processed leafs. Leafs before the cursor are skipped. + /// The leaf processor. + /// The options to configure catalog processing. + /// The logger used for telemetry. + /// The catalog processor. + public static CatalogProcessor CreateCatalogProcessor( + this NuGetClientFactory clientFactory, + ICursor cursor, + ICatalogLeafProcessor leafProcessor, + CatalogProcessorOptions options, + ILogger logger) { - /// - /// Create a new to discover and download catalog leafs. - /// Leafs are processed by the . - /// - /// The factory used to create NuGet clients. - /// Cursor to track succesfully processed leafs. Leafs before the cursor are skipped. - /// The leaf processor. - /// The options to configure catalog processing. - /// The logger used for telemetry. - /// The catalog processor. - public static CatalogProcessor CreateCatalogProcessor( - this NuGetClientFactory clientFactory, - ICursor cursor, - ICatalogLeafProcessor leafProcessor, - CatalogProcessorOptions options, - ILogger logger) - { - var catalogClient = clientFactory.CreateCatalogClient(); + var catalogClient = clientFactory.CreateCatalogClient(); - return new CatalogProcessor( - cursor, - catalogClient, - leafProcessor, - options, - logger); - } + return new CatalogProcessor( + cursor, + catalogClient, + leafProcessor, + options, + logger); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/PackageContentModelExtensions.cs b/src/BaGet.Protocol/Extensions/PackageContentModelExtensions.cs index 0a026cdf9..a625d6e51 100644 --- a/src/BaGet.Protocol/Extensions/PackageContentModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/PackageContentModelExtensions.cs @@ -3,24 +3,23 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the Package Content resource. +/// +public static class PackageContentModelExtensions { /// - /// These are documented interpretations of values returned by the Package Content resource. + /// Parse the package versions as s. /// - public static class PackageContentModelExtensions + /// The package versions response. + /// The package versions. + public static IReadOnlyList ParseVersions(this PackageVersionsResponse response) { - /// - /// Parse the package versions as s. - /// - /// The package versions response. - /// The package versions. - public static IReadOnlyList ParseVersions(this PackageVersionsResponse response) - { - return response - .Versions - .Select(NuGetVersion.Parse) - .ToList(); - } + return response + .Versions + .Select(NuGetVersion.Parse) + .ToList(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/PackageMetadataModelExtensions.cs b/src/BaGet.Protocol/Extensions/PackageMetadataModelExtensions.cs index 65947846b..5fc909ded 100644 --- a/src/BaGet.Protocol/Extensions/PackageMetadataModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/PackageMetadataModelExtensions.cs @@ -1,59 +1,58 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the +/// Package Metadata resource API. +/// +public static class RegistrationModelExtensions { /// - /// These are documented interpretations of values returned by the - /// Package Metadata resource API. + /// Parse the package version as a . /// - public static class RegistrationModelExtensions + /// The package metadata. + /// The package version. + public static NuGetVersion ParseVersion(this PackageMetadata package) { - /// - /// Parse the package version as a . - /// - /// The package metadata. - /// The package version. - public static NuGetVersion ParseVersion(this PackageMetadata package) - { - return NuGetVersion.Parse(package.Version); - } + return NuGetVersion.Parse(package.Version); + } - /// - /// Determines if the provided package metadata represents a listed package. - /// - /// The package metadata. - /// True if the package is listed. - public static bool IsListed(this PackageMetadata package) + /// + /// Determines if the provided package metadata represents a listed package. + /// + /// The package metadata. + /// True if the package is listed. + public static bool IsListed(this PackageMetadata package) + { + if (package.Listed.HasValue) { - if (package.Listed.HasValue) - { - return package.Listed.Value; - } - - // A published year of 1900 indicates that this package is unlisted, when the listed property itself is - // not present (legacy behavior). - return package.Published.Year != 1900; + return package.Listed.Value; } - /// - /// Parse the registration page's lower version as a . - /// - /// The registration page. - /// The page's lower version. - public static NuGetVersion ParseLower(this RegistrationIndexPage page) - { - return NuGetVersion.Parse(page.Lower); - } + // A published year of 1900 indicates that this package is unlisted, when the listed property itself is + // not present (legacy behavior). + return package.Published.Year != 1900; + } - /// - /// Parse the registration page's upper version as a . - /// - /// The registration page. - /// The page's upper version. - public static NuGetVersion ParseUpper(this RegistrationIndexPage page) - { - return NuGetVersion.Parse(page.Upper); - } + /// + /// Parse the registration page's lower version as a . + /// + /// The registration page. + /// The page's lower version. + public static NuGetVersion ParseLower(this RegistrationIndexPage page) + { + return NuGetVersion.Parse(page.Lower); + } + + /// + /// Parse the registration page's upper version as a . + /// + /// The registration page. + /// The page's upper version. + public static NuGetVersion ParseUpper(this RegistrationIndexPage page) + { + return NuGetVersion.Parse(page.Upper); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/SearchModelExtensions.cs b/src/BaGet.Protocol/Extensions/SearchModelExtensions.cs index e849ea777..299afe9f3 100644 --- a/src/BaGet.Protocol/Extensions/SearchModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/SearchModelExtensions.cs @@ -1,31 +1,30 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the Search resource. +/// +public static class SearchModelExtensions { /// - /// These are documented interpretations of values returned by the Search resource. + /// Parse the search result's version as a . /// - public static class SearchModelExtensions + /// The search result. + /// The search result's version. + public static NuGetVersion ParseVersion(this SearchResult result) { - /// - /// Parse the search result's version as a . - /// - /// The search result. - /// The search result's version. - public static NuGetVersion ParseVersion(this SearchResult result) - { - return NuGetVersion.Parse(result.Version); - } + return NuGetVersion.Parse(result.Version); + } - /// - /// Parse the search result's version as a . - /// - /// The search result. - /// The search result's version. - public static NuGetVersion ParseVersion(this SearchResultVersion result) - { - return NuGetVersion.Parse(result.Version); - } + /// + /// Parse the search result's version as a . + /// + /// The search result. + /// The search result's version. + public static NuGetVersion ParseVersion(this SearchResultVersion result) + { + return NuGetVersion.Parse(result.Version); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Extensions/ServiceIndexModelExtensions.cs b/src/BaGet.Protocol/Extensions/ServiceIndexModelExtensions.cs index 1e6e50a30..608eb80a2 100644 --- a/src/BaGet.Protocol/Extensions/ServiceIndexModelExtensions.cs +++ b/src/BaGet.Protocol/Extensions/ServiceIndexModelExtensions.cs @@ -3,140 +3,139 @@ using System.Linq; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// These are documented interpretations of values returned by the Service Index resource. +/// +public static class ServiceIndexModelExtensions { + // See: https://github.com/NuGet/NuGet.Client/blob/e08358296db5bfa6f7f32d6f4ec8de288f3b0388/src/NuGet.Core/NuGet.Protocol/ServiceTypes.cs + private static readonly string Version200 = "/2.0.0"; + private static readonly string Version300beta = "/3.0.0-beta"; + private static readonly string Version300 = "/3.0.0"; + private static readonly string Version340 = "/3.4.0"; + private static readonly string Version360 = "/3.6.0"; + private static readonly string Version470 = "/4.7.0"; + private static readonly string Version490 = "/4.9.0"; + private static readonly string Version500 = "/5.0.0"; + private static readonly string Version510 = "/5.1.0"; + + private static readonly string[] Catalog = { "Catalog" + Version300 }; + private static readonly string[] SearchQueryService = { "SearchQueryService" + Version340, "SearchQueryService" + Version300beta, "SearchQueryService" }; + private static readonly string[] RegistrationsBaseUrl = { "RegistrationsBaseUrl" + Version360, "RegistrationsBaseUrl" + Version340, "RegistrationsBaseUrl" + Version300beta, "RegistrationsBaseUrl" }; + private static readonly string[] SearchAutocompleteService = { "SearchAutocompleteService", "SearchAutocompleteService" + Version300beta }; + private static readonly string[] ReportAbuse = { "ReportAbuseUriTemplate", "ReportAbuseUriTemplate" + Version300 }; + private static readonly string[] PackageDetailsUriTemplate = { "PackageDetailsUriTemplate" + Version510 }; + private static readonly string[] LegacyGallery = { "LegacyGallery" + Version200 }; + private static readonly string[] PackagePublish = { "PackagePublish" + Version200 }; + private static readonly string[] PackageBaseAddress = { "PackageBaseAddress" + Version300 }; + private static readonly string[] RepositorySignatures = { "RepositorySignatures" + Version500, "RepositorySignatures" + Version490, "RepositorySignatures" + Version470 }; + private static readonly string[] SymbolPackagePublish = { "SymbolPackagePublish" + Version490 }; + + public static string GetPackageContentResourceUrl(this ServiceIndexResponse serviceIndex) + { + return serviceIndex.GetRequiredResourceUrl(PackageBaseAddress, nameof(PackageBaseAddress)); + } + + public static string GetPackageMetadataResourceUrl(this ServiceIndexResponse serviceIndex) + { + return serviceIndex.GetRequiredResourceUrl(RegistrationsBaseUrl, nameof(RegistrationsBaseUrl)); + } + + public static string GetSearchQueryResourceUrl(this ServiceIndexResponse serviceIndex) + { + return serviceIndex.GetRequiredResourceUrl(SearchQueryService, nameof(SearchQueryService)); + } + /// - /// These are documented interpretations of values returned by the Service Index resource. + /// All the Search resource's endpoints, in the order a client should try them. + /// A service index may advertise several endpoints for this resource. /// - public static class ServiceIndexModelExtensions + public static IReadOnlyList GetSearchQueryResourceUrls(this ServiceIndexResponse serviceIndex) { - // See: https://github.com/NuGet/NuGet.Client/blob/e08358296db5bfa6f7f32d6f4ec8de288f3b0388/src/NuGet.Core/NuGet.Protocol/ServiceTypes.cs - private static readonly string Version200 = "/2.0.0"; - private static readonly string Version300beta = "/3.0.0-beta"; - private static readonly string Version300 = "/3.0.0"; - private static readonly string Version340 = "/3.4.0"; - private static readonly string Version360 = "/3.6.0"; - private static readonly string Version470 = "/4.7.0"; - private static readonly string Version490 = "/4.9.0"; - private static readonly string Version500 = "/5.0.0"; - private static readonly string Version510 = "/5.1.0"; - - private static readonly string[] Catalog = { "Catalog" + Version300 }; - private static readonly string[] SearchQueryService = { "SearchQueryService" + Version340, "SearchQueryService" + Version300beta, "SearchQueryService" }; - private static readonly string[] RegistrationsBaseUrl = { "RegistrationsBaseUrl" + Version360, "RegistrationsBaseUrl" + Version340, "RegistrationsBaseUrl" + Version300beta, "RegistrationsBaseUrl" }; - private static readonly string[] SearchAutocompleteService = { "SearchAutocompleteService", "SearchAutocompleteService" + Version300beta }; - private static readonly string[] ReportAbuse = { "ReportAbuseUriTemplate", "ReportAbuseUriTemplate" + Version300 }; - private static readonly string[] PackageDetailsUriTemplate = { "PackageDetailsUriTemplate" + Version510 }; - private static readonly string[] LegacyGallery = { "LegacyGallery" + Version200 }; - private static readonly string[] PackagePublish = { "PackagePublish" + Version200 }; - private static readonly string[] PackageBaseAddress = { "PackageBaseAddress" + Version300 }; - private static readonly string[] RepositorySignatures = { "RepositorySignatures" + Version500, "RepositorySignatures" + Version490, "RepositorySignatures" + Version470 }; - private static readonly string[] SymbolPackagePublish = { "SymbolPackagePublish" + Version490 }; - - public static string GetPackageContentResourceUrl(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetRequiredResourceUrl(PackageBaseAddress, nameof(PackageBaseAddress)); - } + return serviceIndex.GetRequiredResourceUrls(SearchQueryService, nameof(SearchQueryService)); + } - public static string GetPackageMetadataResourceUrl(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetRequiredResourceUrl(RegistrationsBaseUrl, nameof(RegistrationsBaseUrl)); - } + /// + /// All the Autocomplete resource's endpoints, in the order a client should try them. + /// The list is empty if the service index does not advertise this optional resource. + /// + public static IReadOnlyList GetSearchAutocompleteResourceUrls(this ServiceIndexResponse serviceIndex) + { + return serviceIndex.GetResourceUrls(SearchAutocompleteService); + } - public static string GetSearchQueryResourceUrl(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetRequiredResourceUrl(SearchQueryService, nameof(SearchQueryService)); - } + public static string GetCatalogResourceUrl(this ServiceIndexResponse serviceIndex) + { + return serviceIndex.GetResourceUrl(Catalog); + } - /// - /// All the Search resource's endpoints, in the order a client should try them. - /// A service index may advertise several endpoints for this resource. - /// - public static IReadOnlyList GetSearchQueryResourceUrls(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetRequiredResourceUrls(SearchQueryService, nameof(SearchQueryService)); - } + public static string GetSearchAutocompleteResourceUrl(this ServiceIndexResponse serviceIndex) + { + return serviceIndex.GetResourceUrl(SearchAutocompleteService); + } - /// - /// All the Autocomplete resource's endpoints, in the order a client should try them. - /// The list is empty if the service index does not advertise this optional resource. - /// - public static IReadOnlyList GetSearchAutocompleteResourceUrls(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetResourceUrls(SearchAutocompleteService); - } + public static string GetResourceUrl(this ServiceIndexResponse serviceIndex, string[] types) + { + return serviceIndex.GetResourceUrls(types).FirstOrDefault(); + } - public static string GetCatalogResourceUrl(this ServiceIndexResponse serviceIndex) - { - return serviceIndex.GetResourceUrl(Catalog); - } + /// + /// All the endpoints that the service index advertises for a resource, in the order a + /// client should try them: the most preferred resource type first and, within a type, + /// the order the service index itself used. + /// + /// A URL advertised under several of the resource's type versions is returned once, so + /// that a failover does not retry an endpoint that has already failed. + /// + /// The service index to read. + /// The resource's type identifiers, most preferred first. + /// The resource's endpoints. Empty if the resource is not advertised. + public static IReadOnlyList GetResourceUrls(this ServiceIndexResponse serviceIndex, string[] types) + { + if (serviceIndex == null) throw new ArgumentNullException(nameof(serviceIndex)); + if (types == null) throw new ArgumentNullException(nameof(types)); - public static string GetSearchAutocompleteResourceUrl(this ServiceIndexResponse serviceIndex) + if (serviceIndex.Resources == null) { - return serviceIndex.GetResourceUrl(SearchAutocompleteService); + return Array.Empty(); } - public static string GetResourceUrl(this ServiceIndexResponse serviceIndex, string[] types) - { - return serviceIndex.GetResourceUrls(types).FirstOrDefault(); - } + return types + .SelectMany(type => serviceIndex.Resources.Where(resource => resource.Type == type)) + .Select(resource => resource.ResourceUrl?.Trim('/')) + .Where(resourceUrl => !string.IsNullOrEmpty(resourceUrl)) + .Distinct(StringComparer.Ordinal) + .ToList(); + } - /// - /// All the endpoints that the service index advertises for a resource, in the order a - /// client should try them: the most preferred resource type first and, within a type, - /// the order the service index itself used. - /// - /// A URL advertised under several of the resource's type versions is returned once, so - /// that a failover does not retry an endpoint that has already failed. - /// - /// The service index to read. - /// The resource's type identifiers, most preferred first. - /// The resource's endpoints. Empty if the resource is not advertised. - public static IReadOnlyList GetResourceUrls(this ServiceIndexResponse serviceIndex, string[] types) - { - if (serviceIndex == null) throw new ArgumentNullException(nameof(serviceIndex)); - if (types == null) throw new ArgumentNullException(nameof(types)); - - if (serviceIndex.Resources == null) - { - return Array.Empty(); - } - - return types - .SelectMany(type => serviceIndex.Resources.Where(resource => resource.Type == type)) - .Select(resource => resource.ResourceUrl?.Trim('/')) - .Where(resourceUrl => !string.IsNullOrEmpty(resourceUrl)) - .Distinct(StringComparer.Ordinal) - .ToList(); - } + public static string GetRequiredResourceUrl(this ServiceIndexResponse serviceIndex, string[] types, string resourceName) + { + return serviceIndex.GetRequiredResourceUrls(types, resourceName)[0]; + } - public static string GetRequiredResourceUrl(this ServiceIndexResponse serviceIndex, string[] types, string resourceName) + /// + /// All the endpoints that the service index advertises for a required resource. + /// + /// The service index to read. + /// The resource's type identifiers, most preferred first. + /// The resource's name, used in the error message. + /// The resource's endpoints, in the order a client should try them. + public static IReadOnlyList GetRequiredResourceUrls( + this ServiceIndexResponse serviceIndex, + string[] types, + string resourceName) + { + // For more information on required resources, + // see: https://docs.microsoft.com/en-us/nuget/api/overview#resources-and-schema + var resourceUrls = serviceIndex.GetResourceUrls(types); + if (resourceUrls.Count == 0) { - return serviceIndex.GetRequiredResourceUrls(types, resourceName)[0]; + throw new InvalidOperationException( + $"The service index does not have a resource named '{resourceName}'"); } - /// - /// All the endpoints that the service index advertises for a required resource. - /// - /// The service index to read. - /// The resource's type identifiers, most preferred first. - /// The resource's name, used in the error message. - /// The resource's endpoints, in the order a client should try them. - public static IReadOnlyList GetRequiredResourceUrls( - this ServiceIndexResponse serviceIndex, - string[] types, - string resourceName) - { - // For more information on required resources, - // see: https://docs.microsoft.com/en-us/nuget/api/overview#resources-and-schema - var resourceUrls = serviceIndex.GetResourceUrls(types); - if (resourceUrls.Count == 0) - { - throw new InvalidOperationException( - $"The service index does not have a resource named '{resourceName}'"); - } - - return resourceUrls; - } + return resourceUrls; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/AlternatePackage.cs b/src/BaGet.Protocol/Models/AlternatePackage.cs index a5e272adc..63dbc3831 100644 --- a/src/BaGet.Protocol/Models/AlternatePackage.cs +++ b/src/BaGet.Protocol/Models/AlternatePackage.cs @@ -1,30 +1,29 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The alternate package that should be used instead of a deprecated package. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation +/// +public class AlternatePackage { - /// - /// The alternate package that should be used instead of a deprecated package. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation - /// - public class AlternatePackage - { - [JsonPropertyName("@id")] - public string Url { get; set; } + [JsonPropertyName("@id")] + public string Url { get; set; } - [JsonPropertyName("@type")] - public string Type { get; set; } + [JsonPropertyName("@type")] + public string Type { get; set; } - /// - /// The ID of the alternate package. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + /// + /// The ID of the alternate package. + /// + [JsonPropertyName("id")] + public string Id { get; set; } - /// - /// The allowed version range, or * if any version is allowed. - /// - [JsonPropertyName("range")] - public string Range { get; set; } - } -} + /// + /// The allowed version range, or * if any version is allowed. + /// + [JsonPropertyName("range")] + public string Range { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/AutocompleteContext.cs b/src/BaGet.Protocol/Models/AutocompleteContext.cs index 96b711c2f..5862759ab 100644 --- a/src/BaGet.Protocol/Models/AutocompleteContext.cs +++ b/src/BaGet.Protocol/Models/AutocompleteContext.cs @@ -1,15 +1,14 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +public class AutocompleteContext { - public class AutocompleteContext + public static readonly AutocompleteContext Default = new AutocompleteContext { - public static readonly AutocompleteContext Default = new AutocompleteContext - { - Vocab = "http://schema.nuget.org/schema#" - }; + Vocab = "http://schema.nuget.org/schema#" + }; - [JsonPropertyName("@vocab")] - public string Vocab { get; set; } - } -} + [JsonPropertyName("@vocab")] + public string Vocab { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/AutocompleteResponse.cs b/src/BaGet.Protocol/Models/AutocompleteResponse.cs index 5522656fe..936f9d0b0 100644 --- a/src/BaGet.Protocol/Models/AutocompleteResponse.cs +++ b/src/BaGet.Protocol/Models/AutocompleteResponse.cs @@ -1,28 +1,27 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The package ids that matched the autocomplete query. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids +/// +public class AutocompleteResponse { + [JsonPropertyName("@context")] + public AutocompleteContext Context { get; set; } + /// - /// The package ids that matched the autocomplete query. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids + /// The total number of matches, disregarding skip and take. /// - public class AutocompleteResponse - { - [JsonPropertyName("@context")] - public AutocompleteContext Context { get; set; } - - /// - /// The total number of matches, disregarding skip and take. - /// - [JsonPropertyName("totalHits")] - public long TotalHits { get; set; } + [JsonPropertyName("totalHits")] + public long TotalHits { get; set; } - /// - /// The package IDs matched by the autocomplete query. - /// - [JsonPropertyName("data")] - public IReadOnlyList Data { get; set; } - } -} + /// + /// The package IDs matched by the autocomplete query. + /// + [JsonPropertyName("data")] + public IReadOnlyList Data { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogIndex.cs b/src/BaGet.Protocol/Models/CatalogIndex.cs index beeea373e..19cbdc070 100644 --- a/src/BaGet.Protocol/Models/CatalogIndex.cs +++ b/src/BaGet.Protocol/Models/CatalogIndex.cs @@ -2,34 +2,32 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models -{ - // This class is based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogIndex.cs +namespace BaGet.Protocol.Models; +// This class is based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogIndex.cs +/// +/// The catalog index is the entry point for the catalog resource. +/// Use this to discover catalog pages, which in turn can be used to discover catalog leafs. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-index +/// +public class CatalogIndex +{ /// - /// The catalog index is the entry point for the catalog resource. - /// Use this to discover catalog pages, which in turn can be used to discover catalog leafs. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-index + /// A timestamp of the most recent commit. /// - public class CatalogIndex - { - /// - /// A timestamp of the most recent commit. - /// - [JsonPropertyName("commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } + [JsonPropertyName("commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } - /// - /// The number of catalog pages in the catalog index. - /// - [JsonPropertyName("count")] - public int Count { get; set; } + /// + /// The number of catalog pages in the catalog index. + /// + [JsonPropertyName("count")] + public int Count { get; set; } - /// - /// The items used to discover s. - /// - [JsonPropertyName("items")] - public List Items { get; set; } - } -} + /// + /// The items used to discover s. + /// + [JsonPropertyName("items")] + public List Items { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogLeaf.cs b/src/BaGet.Protocol/Models/CatalogLeaf.cs index f41ce62b9..069c3853e 100644 --- a/src/BaGet.Protocol/Models/CatalogLeaf.cs +++ b/src/BaGet.Protocol/Models/CatalogLeaf.cs @@ -2,58 +2,56 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; +// This classed is based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogLeaf.cs + +/// +/// A catalog leaf. Represents a single package event. +/// Leafs can be discovered from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf +/// +public class CatalogLeaf : ICatalogLeafItem { - // This classed is based off: https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogLeaf.cs + /// + /// The URL to the current catalog leaf. + /// + [JsonPropertyName("@id")] + public string CatalogLeafUrl { get; set; } + + /// + /// The type of the current catalog leaf. + /// + [JsonPropertyName("@type")] + public IReadOnlyList Type { get; set; } + + /// + /// The catalog commit ID associated with this catalog item. + /// + [JsonPropertyName("catalog:commitId")] + public string CommitId { get; set; } + + /// + /// The commit timestamp of this catalog item. + /// + [JsonPropertyName("catalog:commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } + + /// + /// The package ID of the catalog item. + /// + [JsonPropertyName("id")] + public string PackageId { get; set; } + + /// + /// The published date of the package catalog item. + /// + [JsonPropertyName("published")] + public DateTimeOffset Published { get; set; } /// - /// A catalog leaf. Represents a single package event. - /// Leafs can be discovered from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf + /// The package version of the catalog item. /// - public class CatalogLeaf : ICatalogLeafItem - { - /// - /// The URL to the current catalog leaf. - /// - [JsonPropertyName("@id")] - public string CatalogLeafUrl { get; set; } - - /// - /// The type of the current catalog leaf. - /// - [JsonPropertyName("@type")] - public IReadOnlyList Type { get; set; } - - /// - /// The catalog commit ID associated with this catalog item. - /// - [JsonPropertyName("catalog:commitId")] - public string CommitId { get; set; } - - /// - /// The commit timestamp of this catalog item. - /// - [JsonPropertyName("catalog:commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } - - /// - /// The package ID of the catalog item. - /// - [JsonPropertyName("id")] - public string PackageId { get; set; } - - /// - /// The published date of the package catalog item. - /// - [JsonPropertyName("published")] - public DateTimeOffset Published { get; set; } - - /// - /// The package version of the catalog item. - /// - [JsonPropertyName("version")] - public string PackageVersion { get; set; } - } -} + [JsonPropertyName("version")] + public string PackageVersion { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogLeafItem.cs b/src/BaGet.Protocol/Models/CatalogLeafItem.cs index 36dcb940e..91ca9cb0e 100644 --- a/src/BaGet.Protocol/Models/CatalogLeafItem.cs +++ b/src/BaGet.Protocol/Models/CatalogLeafItem.cs @@ -1,45 +1,43 @@ using System; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogLeafItem.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogLeafItem.cs +/// +/// An item in a that references a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-item-object-in-a-page +/// +public class CatalogLeafItem : ICatalogLeafItem +{ /// - /// An item in a that references a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-item-object-in-a-page + /// The URL to the current catalog leaf. /// - public class CatalogLeafItem : ICatalogLeafItem - { - /// - /// The URL to the current catalog leaf. - /// - [JsonPropertyName("@id")] - public string CatalogLeafUrl { get; set; } + [JsonPropertyName("@id")] + public string CatalogLeafUrl { get; set; } - /// - /// The type of the current catalog leaf. - /// - [JsonPropertyName("@type")] - public string Type { get; set; } + /// + /// The type of the current catalog leaf. + /// + [JsonPropertyName("@type")] + public string Type { get; set; } - /// - /// The commit timestamp of this catalog item. - /// - [JsonPropertyName("commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } + /// + /// The commit timestamp of this catalog item. + /// + [JsonPropertyName("commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } - /// - /// The package ID of the catalog item. - /// - [JsonPropertyName("nuget:id")] - public string PackageId { get; set; } + /// + /// The package ID of the catalog item. + /// + [JsonPropertyName("nuget:id")] + public string PackageId { get; set; } - /// - /// The package version of the catalog item. - /// - [JsonPropertyName("nuget:version")] - public string PackageVersion { get; set; } - } -} + /// + /// The package version of the catalog item. + /// + [JsonPropertyName("nuget:version")] + public string PackageVersion { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogPage.cs b/src/BaGet.Protocol/Models/CatalogPage.cs index 65f9e6d3f..769acefc8 100644 --- a/src/BaGet.Protocol/Models/CatalogPage.cs +++ b/src/BaGet.Protocol/Models/CatalogPage.cs @@ -2,40 +2,38 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogPage.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogPage.cs +/// +/// A catalog page, used to discover catalog leafs. +/// Pages can be discovered from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page +/// +public class CatalogPage +{ /// - /// A catalog page, used to discover catalog leafs. - /// Pages can be discovered from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page + /// A unique ID associated with the most recent commit in this page. /// - public class CatalogPage - { - /// - /// A unique ID associated with the most recent commit in this page. - /// - [JsonPropertyName("commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } + [JsonPropertyName("commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } - /// - /// The number of items in the page. - /// - [JsonPropertyName("count")] - public int Count { get; set; } + /// + /// The number of items in the page. + /// + [JsonPropertyName("count")] + public int Count { get; set; } - /// - /// The items used to discover s. - /// - [JsonPropertyName("items")] - public List Items { get; set; } + /// + /// The items used to discover s. + /// + [JsonPropertyName("items")] + public List Items { get; set; } - /// - /// The URL to the Catalog Index. - /// - [JsonPropertyName("parent")] - public string CatalogIndexUrl { get; set; } - } -} + /// + /// The URL to the Catalog Index. + /// + [JsonPropertyName("parent")] + public string CatalogIndexUrl { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/CatalogPageItem.cs b/src/BaGet.Protocol/Models/CatalogPageItem.cs index 0240d9e23..ee69ad548 100644 --- a/src/BaGet.Protocol/Models/CatalogPageItem.cs +++ b/src/BaGet.Protocol/Models/CatalogPageItem.cs @@ -1,33 +1,31 @@ using System; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogPageItem.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/CatalogPageItem.cs +/// +/// An item in the that references a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page-object-in-the-index +/// +public class CatalogPageItem +{ /// - /// An item in the that references a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-page-object-in-the-index + /// The URL to this item's corresponding . /// - public class CatalogPageItem - { - /// - /// The URL to this item's corresponding . - /// - [JsonPropertyName("@id")] - public string CatalogPageUrl { get; set; } + [JsonPropertyName("@id")] + public string CatalogPageUrl { get; set; } - /// - /// A timestamp of the most recent commit in this page. - /// - [JsonPropertyName("commitTimeStamp")] - public DateTimeOffset CommitTimestamp { get; set; } + /// + /// A timestamp of the most recent commit in this page. + /// + [JsonPropertyName("commitTimeStamp")] + public DateTimeOffset CommitTimestamp { get; set; } - /// - /// The number of items in the page. - /// - [JsonPropertyName("count")] - public int Count { get; set; } - } -} + /// + /// The number of items in the page. + /// + [JsonPropertyName("count")] + public int Count { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/DependencyGroupItem.cs b/src/BaGet.Protocol/Models/DependencyGroupItem.cs index e9626c053..28f24be35 100644 --- a/src/BaGet.Protocol/Models/DependencyGroupItem.cs +++ b/src/BaGet.Protocol/Models/DependencyGroupItem.cs @@ -1,25 +1,24 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The dependencies of the package for a specific target framework. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency-group +/// +public class DependencyGroupItem { /// - /// The dependencies of the package for a specific target framework. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency-group + /// The target framework that these dependencies are applicable to. /// - public class DependencyGroupItem - { - /// - /// The target framework that these dependencies are applicable to. - /// - [JsonPropertyName("targetFramework")] - public string TargetFramework { get; set; } + [JsonPropertyName("targetFramework")] + public string TargetFramework { get; set; } - /// - /// A list of dependencies. - /// - [JsonPropertyName("dependencies")] - public List Dependencies { get; set; } - } -} + /// + /// A list of dependencies. + /// + [JsonPropertyName("dependencies")] + public List Dependencies { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/DependencyItem.cs b/src/BaGet.Protocol/Models/DependencyItem.cs index 95af13012..555e84bc5 100644 --- a/src/BaGet.Protocol/Models/DependencyItem.cs +++ b/src/BaGet.Protocol/Models/DependencyItem.cs @@ -1,26 +1,25 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Internal; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// Represents a package dependency. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency +/// +public class DependencyItem { /// - /// Represents a package dependency. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-dependency + /// The ID of the package dependency. /// - public class DependencyItem - { - /// - /// The ID of the package dependency. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } - /// - /// The allowed version range of the dependency. - /// - [JsonPropertyName("range")] - [JsonConverter(typeof(PackageDependencyRangeJsonConverter))] - public string Range { get; set; } - } -} + /// + /// The allowed version range of the dependency. + /// + [JsonPropertyName("range")] + [JsonConverter(typeof(PackageDependencyRangeJsonConverter))] + public string Range { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/ICatalogLeafItem.cs b/src/BaGet.Protocol/Models/ICatalogLeafItem.cs index 2cd59a37f..7987d55b1 100644 --- a/src/BaGet.Protocol/Models/ICatalogLeafItem.cs +++ b/src/BaGet.Protocol/Models/ICatalogLeafItem.cs @@ -1,30 +1,28 @@ using System; -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/ICatalogLeafItem.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/ICatalogLeafItem.cs +/// +/// A catalog leaf. Represents a single package event. +/// Leafs can be discovered from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf +/// +public interface ICatalogLeafItem +{ /// - /// A catalog leaf. Represents a single package event. - /// Leafs can be discovered from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf + /// The commit timestamp of this catalog item. /// - public interface ICatalogLeafItem - { - /// - /// The commit timestamp of this catalog item. - /// - DateTimeOffset CommitTimestamp { get; } + DateTimeOffset CommitTimestamp { get; } - /// - /// The package ID of the catalog item. - /// - string PackageId { get; } + /// + /// The package ID of the catalog item. + /// + string PackageId { get; } - /// - /// The package version of the catalog item. - /// - string PackageVersion { get; } - } -} + /// + /// The package version of the catalog item. + /// + string PackageVersion { get; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageDeleteCatalogLeaf.cs b/src/BaGet.Protocol/Models/PackageDeleteCatalogLeaf.cs index da53173a4..90444cac0 100644 --- a/src/BaGet.Protocol/Models/PackageDeleteCatalogLeaf.cs +++ b/src/BaGet.Protocol/Models/PackageDeleteCatalogLeaf.cs @@ -1,14 +1,12 @@ -namespace BaGet.Protocol.Models -{ - // This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/PackageDeleteCatalogLeaf.cs +namespace BaGet.Protocol.Models; +// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/PackageDeleteCatalogLeaf.cs - /// - /// A "package delete" catalog leaf. Represents a single package deletion event. - /// Leafs can be discovered from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf - /// - public class PackageDeleteCatalogLeaf : CatalogLeaf - { - } -} +/// +/// A "package delete" catalog leaf. Represents a single package deletion event. +/// Leafs can be discovered from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf +/// +public class PackageDeleteCatalogLeaf : CatalogLeaf +{ +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageDeprecation.cs b/src/BaGet.Protocol/Models/PackageDeprecation.cs index 9445ade2d..40d04d952 100644 --- a/src/BaGet.Protocol/Models/PackageDeprecation.cs +++ b/src/BaGet.Protocol/Models/PackageDeprecation.cs @@ -1,38 +1,37 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A package's metadata. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation +/// +public class PackageDeprecation { /// - /// A package's metadata. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#package-deprecation + /// The URL to the document used to produce this object. /// - public class PackageDeprecation - { - /// - /// The URL to the document used to produce this object. - /// - [JsonPropertyName("@id")] - public string CatalogLeafUrl { get; set; } + [JsonPropertyName("@id")] + public string CatalogLeafUrl { get; set; } - /// - /// The reasons why the package was deprecated. - /// Deprecation reasons include: "Legacy", "CriticalBugs", and "Other". - /// - [JsonPropertyName("reasons")] - public IReadOnlyList Reasons { get; set; } + /// + /// The reasons why the package was deprecated. + /// Deprecation reasons include: "Legacy", "CriticalBugs", and "Other". + /// + [JsonPropertyName("reasons")] + public IReadOnlyList Reasons { get; set; } - /// - /// The additional details about this deprecation. - /// - [JsonPropertyName("message")] - public string Message { get; set; } + /// + /// The additional details about this deprecation. + /// + [JsonPropertyName("message")] + public string Message { get; set; } - /// - /// The alternate package that should be used instead. - /// - [JsonPropertyName("alternatePackage")] - public AlternatePackage AlternatePackage { get; set; } - } -} + /// + /// The alternate package that should be used instead. + /// + [JsonPropertyName("alternatePackage")] + public AlternatePackage AlternatePackage { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageDetailsCatalogLeaf.cs b/src/BaGet.Protocol/Models/PackageDetailsCatalogLeaf.cs index 5e8cf2575..093254e8e 100644 --- a/src/BaGet.Protocol/Models/PackageDetailsCatalogLeaf.cs +++ b/src/BaGet.Protocol/Models/PackageDetailsCatalogLeaf.cs @@ -2,169 +2,167 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/PackageDetailsCatalogLeaf.cs +/// +/// A "package details" catalog leaf. Represents a single package create or update event. +/// s can be discovered from a . +/// +/// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf +/// +public class PackageDetailsCatalogLeaf : CatalogLeaf { - /// This class is based off https://github.com/NuGet/NuGet.Services.Metadata/blob/64af0b59c5a79e0143f0808b39946df9f16cb2e7/src/NuGet.Protocol.Catalog/Models/PackageDetailsCatalogLeaf.cs - - /// - /// A "package details" catalog leaf. Represents a single package create or update event. - /// s can be discovered from a . - /// - /// See: https://docs.microsoft.com/en-us/nuget/api/catalog-resource#catalog-leaf - /// - public class PackageDetailsCatalogLeaf : CatalogLeaf - { - /// - /// The package's authors. - /// - [JsonPropertyName("authors")] - public string Authors { get; set; } - - /// - /// The package's copyright. - /// - [JsonPropertyName("copyright")] - public string Copyright { get; set; } - - /// - /// A timestamp of when the package was first created. Fallback property: . - /// - [JsonPropertyName("created")] - public DateTimeOffset Created { get; set; } - - /// - /// A timestamp of when the package was last edited. - /// - [JsonPropertyName("lastEdited")] - public DateTimeOffset LastEdited { get; set; } - - /// - /// The dependencies of the package, grouped by target framework. - /// - [JsonPropertyName("dependencyGroups")] - public List DependencyGroups { get; set; } - - /// - /// The package's description. - /// - [JsonPropertyName("description")] - public string Description { get; set; } - - /// - /// The URL to the package's icon. - /// - [JsonPropertyName("iconUrl")] - public string IconUrl { get; set; } - - /// - /// Whether or not the package is prerelease. Can be detected from . - /// Note that the NuGet.org catalog had this wrong in some cases. - /// Example: https://api.nuget.org/v3/catalog0/data/2016.03.11.21.02.55/mvid.fody.2.json - /// - [JsonPropertyName("isPrerelease")] - public bool IsPrerelease { get; set; } - - /// - /// The package's language. - /// - [JsonPropertyName("language")] - public string Language { get; set; } - - /// - /// THe URL to the package's license. - /// - [JsonPropertyName("licenseUrl")] - public string LicenseUrl { get; set; } - - /// - /// Whether the pacakge is listed. - /// - [JsonPropertyName("listed")] - public bool? Listed { get; set; } - - /// - /// The minimum NuGet client version needed to use this package. - /// - [JsonPropertyName("minClientVersion")] - public string MinClientVersion { get; set; } - - /// - /// The hash of the package encoded using Base64. - /// Hash algorithm can be detected using . - /// - [JsonPropertyName("packageHash")] - public string PackageHash { get; set; } - - /// - /// The algorithm used to hash . - /// - [JsonPropertyName("packageHashAlgorithm")] - public string PackageHashAlgorithm { get; set; } - - /// - /// The size of the package .nupkg in bytes. - /// - [JsonPropertyName("packageSize")] - public long PackageSize { get; set; } - - /// - /// The URL for the package's home page. - /// - [JsonPropertyName("projectUrl")] - public string ProjectUrl { get; set; } - - /// - /// The package's release notes. - /// - [JsonPropertyName("releaseNotes")] - public string ReleaseNotes { get; set; } - - /// - /// If true, the package requires its license to be accepted. - /// - [JsonPropertyName("requireLicenseAcceptance")] - public bool? RequireLicenseAcceptance { get; set; } - - /// - /// The package's summary. - /// - [JsonPropertyName("summary")] - public string Summary { get; set; } - - /// - /// The package's tags. - /// - [JsonPropertyName("tags")] - public List Tags { get; set; } - - /// - /// The package's title. - /// - [JsonPropertyName("title")] - public string Title { get; set; } - - /// - /// The version string as it's originally found in the .nuspec. - /// - [JsonPropertyName("verbatimVersion")] - public string VerbatimVersion { get; set; } - - /// - /// The package's License Expression. - /// - [JsonPropertyName("licenseExpression")] - public string LicenseExpression { get; set; } - - /// - /// The package's license file. - /// - [JsonPropertyName("licenseFile")] - public string LicenseFile { get; set; } - - /// - /// The package's icon file. - /// - [JsonPropertyName("iconFile")] - public string IconFile { get; set; } - } -} + /// + /// The package's authors. + /// + [JsonPropertyName("authors")] + public string Authors { get; set; } + + /// + /// The package's copyright. + /// + [JsonPropertyName("copyright")] + public string Copyright { get; set; } + + /// + /// A timestamp of when the package was first created. Fallback property: . + /// + [JsonPropertyName("created")] + public DateTimeOffset Created { get; set; } + + /// + /// A timestamp of when the package was last edited. + /// + [JsonPropertyName("lastEdited")] + public DateTimeOffset LastEdited { get; set; } + + /// + /// The dependencies of the package, grouped by target framework. + /// + [JsonPropertyName("dependencyGroups")] + public List DependencyGroups { get; set; } + + /// + /// The package's description. + /// + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// The URL to the package's icon. + /// + [JsonPropertyName("iconUrl")] + public string IconUrl { get; set; } + + /// + /// Whether or not the package is prerelease. Can be detected from . + /// Note that the NuGet.org catalog had this wrong in some cases. + /// Example: https://api.nuget.org/v3/catalog0/data/2016.03.11.21.02.55/mvid.fody.2.json + /// + [JsonPropertyName("isPrerelease")] + public bool IsPrerelease { get; set; } + + /// + /// The package's language. + /// + [JsonPropertyName("language")] + public string Language { get; set; } + + /// + /// THe URL to the package's license. + /// + [JsonPropertyName("licenseUrl")] + public string LicenseUrl { get; set; } + + /// + /// Whether the pacakge is listed. + /// + [JsonPropertyName("listed")] + public bool? Listed { get; set; } + + /// + /// The minimum NuGet client version needed to use this package. + /// + [JsonPropertyName("minClientVersion")] + public string MinClientVersion { get; set; } + + /// + /// The hash of the package encoded using Base64. + /// Hash algorithm can be detected using . + /// + [JsonPropertyName("packageHash")] + public string PackageHash { get; set; } + + /// + /// The algorithm used to hash . + /// + [JsonPropertyName("packageHashAlgorithm")] + public string PackageHashAlgorithm { get; set; } + + /// + /// The size of the package .nupkg in bytes. + /// + [JsonPropertyName("packageSize")] + public long PackageSize { get; set; } + + /// + /// The URL for the package's home page. + /// + [JsonPropertyName("projectUrl")] + public string ProjectUrl { get; set; } + + /// + /// The package's release notes. + /// + [JsonPropertyName("releaseNotes")] + public string ReleaseNotes { get; set; } + + /// + /// If true, the package requires its license to be accepted. + /// + [JsonPropertyName("requireLicenseAcceptance")] + public bool? RequireLicenseAcceptance { get; set; } + + /// + /// The package's summary. + /// + [JsonPropertyName("summary")] + public string Summary { get; set; } + + /// + /// The package's tags. + /// + [JsonPropertyName("tags")] + public List Tags { get; set; } + + /// + /// The package's title. + /// + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// The version string as it's originally found in the .nuspec. + /// + [JsonPropertyName("verbatimVersion")] + public string VerbatimVersion { get; set; } + + /// + /// The package's License Expression. + /// + [JsonPropertyName("licenseExpression")] + public string LicenseExpression { get; set; } + + /// + /// The package's license file. + /// + [JsonPropertyName("licenseFile")] + public string LicenseFile { get; set; } + + /// + /// The package's icon file. + /// + [JsonPropertyName("iconFile")] + public string IconFile { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageMetadata.cs b/src/BaGet.Protocol/Models/PackageMetadata.cs index fe4f097a6..553f0a769 100644 --- a/src/BaGet.Protocol/Models/PackageMetadata.cs +++ b/src/BaGet.Protocol/Models/PackageMetadata.cs @@ -2,134 +2,133 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A package's metadata. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#catalog-entry +/// +public class PackageMetadata { /// - /// A package's metadata. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#catalog-entry - /// - public class PackageMetadata - { - /// - /// The URL to the document used to produce this object. - /// - [JsonPropertyName("@id")] - public string CatalogLeafUrl { get; set; } - - /// - /// The ID of the package. - /// - [JsonPropertyName("id")] - public string PackageId { get; set; } - - /// - /// The full NuGet version after normalization, including any SemVer 2.0.0 build metadata. - /// - [JsonPropertyName("version")] - public string Version { get; set; } - - /// - /// The package's authors. - /// - [JsonPropertyName("authors")] - public string Authors { get; set; } - - /// - /// The dependencies of the package, grouped by target framework. - /// - [JsonPropertyName("dependencyGroups")] - public IReadOnlyList DependencyGroups { get; set; } - - /// - /// The deprecation associated with the package, if any. - /// - [JsonPropertyName("deprecation")] - public PackageDeprecation Deprecation { get; set; } - - /// - /// The package's description. - /// - [JsonPropertyName("description")] - public string Description { get; set; } - - /// - /// The URL to the package's icon. - /// - [JsonPropertyName("iconUrl")] - public string IconUrl { get; set; } - - /// - /// The package's language. - /// - [JsonPropertyName("language")] - public string Language { get; set; } - - /// - /// The URL to the package's license. - /// - [JsonPropertyName("licenseUrl")] - public string LicenseUrl { get; set; } - - /// - /// Whether the package is listed in search results. - /// If , the package should be considered as listed. - /// - [JsonPropertyName("listed")] - public bool? Listed { get; set; } - - /// - /// The minimum NuGet client version needed to use this package. - /// - [JsonPropertyName("minClientVersion")] - public string MinClientVersion { get; set; } - - /// - /// The URL to download the package's content. - /// - [JsonPropertyName("packageContent")] - public string PackageContentUrl { get; set; } - - /// - /// The URL for the package's home page. - /// - [JsonPropertyName("projectUrl")] - public string ProjectUrl { get; set; } - - /// - /// The package's publish date. - /// - [JsonPropertyName("published")] - public DateTimeOffset Published { get; set; } - - /// - /// If true, the package requires its license to be accepted. - /// - [JsonPropertyName("requireLicenseAcceptance")] - public bool RequireLicenseAcceptance { get; set; } - - /// - /// The package's summary. - /// - [JsonPropertyName("summary")] - public string Summary { get; set; } - - /// - /// The package's tags. - /// - [JsonPropertyName("tags")] - public IReadOnlyList Tags { get; set; } - - /// - /// The package's title. - /// - [JsonPropertyName("title")] - public string Title { get; set; } - - /// - /// The known vulnerabilities affecting this version, or null if there are none. - /// - [JsonPropertyName("vulnerabilities")] - public IReadOnlyList Vulnerabilities { get; set; } - } -} + /// The URL to the document used to produce this object. + /// + [JsonPropertyName("@id")] + public string CatalogLeafUrl { get; set; } + + /// + /// The ID of the package. + /// + [JsonPropertyName("id")] + public string PackageId { get; set; } + + /// + /// The full NuGet version after normalization, including any SemVer 2.0.0 build metadata. + /// + [JsonPropertyName("version")] + public string Version { get; set; } + + /// + /// The package's authors. + /// + [JsonPropertyName("authors")] + public string Authors { get; set; } + + /// + /// The dependencies of the package, grouped by target framework. + /// + [JsonPropertyName("dependencyGroups")] + public IReadOnlyList DependencyGroups { get; set; } + + /// + /// The deprecation associated with the package, if any. + /// + [JsonPropertyName("deprecation")] + public PackageDeprecation Deprecation { get; set; } + + /// + /// The package's description. + /// + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// The URL to the package's icon. + /// + [JsonPropertyName("iconUrl")] + public string IconUrl { get; set; } + + /// + /// The package's language. + /// + [JsonPropertyName("language")] + public string Language { get; set; } + + /// + /// The URL to the package's license. + /// + [JsonPropertyName("licenseUrl")] + public string LicenseUrl { get; set; } + + /// + /// Whether the package is listed in search results. + /// If , the package should be considered as listed. + /// + [JsonPropertyName("listed")] + public bool? Listed { get; set; } + + /// + /// The minimum NuGet client version needed to use this package. + /// + [JsonPropertyName("minClientVersion")] + public string MinClientVersion { get; set; } + + /// + /// The URL to download the package's content. + /// + [JsonPropertyName("packageContent")] + public string PackageContentUrl { get; set; } + + /// + /// The URL for the package's home page. + /// + [JsonPropertyName("projectUrl")] + public string ProjectUrl { get; set; } + + /// + /// The package's publish date. + /// + [JsonPropertyName("published")] + public DateTimeOffset Published { get; set; } + + /// + /// If true, the package requires its license to be accepted. + /// + [JsonPropertyName("requireLicenseAcceptance")] + public bool RequireLicenseAcceptance { get; set; } + + /// + /// The package's summary. + /// + [JsonPropertyName("summary")] + public string Summary { get; set; } + + /// + /// The package's tags. + /// + [JsonPropertyName("tags")] + public IReadOnlyList Tags { get; set; } + + /// + /// The package's title. + /// + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// The known vulnerabilities affecting this version, or null if there are none. + /// + [JsonPropertyName("vulnerabilities")] + public IReadOnlyList Vulnerabilities { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageNotFoundException.cs b/src/BaGet.Protocol/Models/PackageNotFoundException.cs index 880c5e71c..682260eae 100644 --- a/src/BaGet.Protocol/Models/PackageNotFoundException.cs +++ b/src/BaGet.Protocol/Models/PackageNotFoundException.cs @@ -1,33 +1,32 @@ using System; using NuGet.Versioning; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// An exception thrown when a package could not be found on the NuGet server. +/// +public class PackageNotFoundException : Exception { /// - /// An exception thrown when a package could not be found on the NuGet server. + /// Create a new instance of the . /// - public class PackageNotFoundException : Exception + /// The ID of the package that could not be found. + /// The version of the package that could not be found. + public PackageNotFoundException(string packageId, NuGetVersion packageVersion) + : base($"Could not find package {packageId} {packageVersion}") { - /// - /// Create a new instance of the . - /// - /// The ID of the package that could not be found. - /// The version of the package that could not be found. - public PackageNotFoundException(string packageId, NuGetVersion packageVersion) - : base($"Could not find package {packageId} {packageVersion}") - { - PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); - PackageVersion = packageVersion ?? throw new ArgumentNullException(nameof(packageVersion)); - } + PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); + PackageVersion = packageVersion ?? throw new ArgumentNullException(nameof(packageVersion)); + } - /// - /// The package ID that could not be found. - /// - public string PackageId { get; } + /// + /// The package ID that could not be found. + /// + public string PackageId { get; } - /// - /// The package version that could not be found. - /// - public NuGetVersion PackageVersion { get; } - } -} + /// + /// The package version that could not be found. + /// + public NuGetVersion PackageVersion { get; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageVersionsResponse.cs b/src/BaGet.Protocol/Models/PackageVersionsResponse.cs index 4a8a64f93..4f88500de 100644 --- a/src/BaGet.Protocol/Models/PackageVersionsResponse.cs +++ b/src/BaGet.Protocol/Models/PackageVersionsResponse.cs @@ -1,19 +1,18 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The full list of versions for a single package. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions +/// +public class PackageVersionsResponse { /// - /// The full list of versions for a single package. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions + /// The versions, lowercased and normalized. /// - public class PackageVersionsResponse - { - /// - /// The versions, lowercased and normalized. - /// - [JsonPropertyName("versions")] - public IReadOnlyList Versions { get; set; } - } -} + [JsonPropertyName("versions")] + public IReadOnlyList Versions { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/PackageVulnerabilityMetadata.cs b/src/BaGet.Protocol/Models/PackageVulnerabilityMetadata.cs index cd547e418..7ddbd4687 100644 --- a/src/BaGet.Protocol/Models/PackageVulnerabilityMetadata.cs +++ b/src/BaGet.Protocol/Models/PackageVulnerabilityMetadata.cs @@ -1,26 +1,25 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A known vulnerability affecting a package version, as it appears in the package's +/// registration metadata. +/// +/// See https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#vulnerabilities +/// +public class PackageVulnerabilityMetadata { /// - /// A known vulnerability affecting a package version, as it appears in the package's - /// registration metadata. - /// - /// See https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource#vulnerabilities + /// The URL of the advisory describing the vulnerability. /// - public class PackageVulnerabilityMetadata - { - /// - /// The URL of the advisory describing the vulnerability. - /// - [JsonPropertyName("advisoryUrl")] - public string AdvisoryUrl { get; set; } + [JsonPropertyName("advisoryUrl")] + public string AdvisoryUrl { get; set; } - /// - /// The severity: "0" low, "1" moderate, "2" high, "3" critical. A string in the - /// registration metadata, unlike the VulnerabilityInfo resource, which uses a number. - /// - [JsonPropertyName("severity")] - public string Severity { get; set; } - } -} + /// + /// The severity: "0" low, "1" moderate, "2" high, "3" critical. A string in the + /// registration metadata, unlike the VulnerabilityInfo resource, which uses a number. + /// + [JsonPropertyName("severity")] + public string Severity { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/ProtocolException.cs b/src/BaGet.Protocol/Models/ProtocolException.cs index 893c89024..7d0b8dc67 100644 --- a/src/BaGet.Protocol/Models/ProtocolException.cs +++ b/src/BaGet.Protocol/Models/ProtocolException.cs @@ -2,52 +2,51 @@ using System.Net; using System.Net.Http; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// An exception that is thrown when an API has returned an unexpected result. +/// +public class ProtocolException : Exception { /// - /// An exception that is thrown when an API has returned an unexpected result. + /// Create a new . /// - public class ProtocolException : Exception + /// The HTTP response message. + /// The HTTP request method. + /// The URI that was requested. + /// The response status code. + /// The HTTP reason phrase. + public ProtocolException( + string message, + HttpMethod method, + string requestUri, + HttpStatusCode statusCode, + string reasonPhrase) : base(message) { - /// - /// Create a new . - /// - /// The HTTP response message. - /// The HTTP request method. - /// The URI that was requested. - /// The response status code. - /// The HTTP reason phrase. - public ProtocolException( - string message, - HttpMethod method, - string requestUri, - HttpStatusCode statusCode, - string reasonPhrase) : base(message) - { - Method = method ?? throw new ArgumentNullException(nameof(method)); - RequestUri = requestUri ?? throw new ArgumentNullException(nameof(requestUri)); - StatusCode = statusCode; - ReasonPhrase = reasonPhrase ?? throw new ArgumentNullException(nameof(reasonPhrase)); - } + Method = method ?? throw new ArgumentNullException(nameof(method)); + RequestUri = requestUri ?? throw new ArgumentNullException(nameof(requestUri)); + StatusCode = statusCode; + ReasonPhrase = reasonPhrase ?? throw new ArgumentNullException(nameof(reasonPhrase)); + } - /// - /// The HTTP response message. - /// - public HttpMethod Method { get; } + /// + /// The HTTP response message. + /// + public HttpMethod Method { get; } - /// - /// The URI that was requested. - /// - public string RequestUri { get; } + /// + /// The URI that was requested. + /// + public string RequestUri { get; } - /// - /// The response status code. - /// - public HttpStatusCode StatusCode { get; } + /// + /// The response status code. + /// + public HttpStatusCode StatusCode { get; } - /// - /// The response reason phrase. - /// - public string ReasonPhrase { get; } - } -} + /// + /// The response reason phrase. + /// + public string ReasonPhrase { get; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationIndexPage.cs b/src/BaGet.Protocol/Models/RegistrationIndexPage.cs index e7190af5c..8edb10f85 100644 --- a/src/BaGet.Protocol/Models/RegistrationIndexPage.cs +++ b/src/BaGet.Protocol/Models/RegistrationIndexPage.cs @@ -1,46 +1,45 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The registration page object found in the registration index. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page-object +/// +public class RegistrationIndexPage { /// - /// The registration page object found in the registration index. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page-object + /// The URL to the registration page. /// - public class RegistrationIndexPage - { - /// - /// The URL to the registration page. - /// - [JsonPropertyName("@id")] - public string RegistrationPageUrl { get; set; } + [JsonPropertyName("@id")] + public string RegistrationPageUrl { get; set; } - /// - /// The number of registration leafs in the page. - /// - [JsonPropertyName("count")] - public int Count { get; set; } + /// + /// The number of registration leafs in the page. + /// + [JsonPropertyName("count")] + public int Count { get; set; } - /// - /// if this package's registration is paged. The items can be found - /// by following the page's . - /// - [JsonPropertyName("items")] - public IReadOnlyList ItemsOrNull { get; set; } + /// + /// if this package's registration is paged. The items can be found + /// by following the page's . + /// + [JsonPropertyName("items")] + public IReadOnlyList ItemsOrNull { get; set; } - /// - /// This page's lowest package version. The version should be lowercased, normalized, - /// and the SemVer 2.0.0 build metadata removed, if any. - /// - [JsonPropertyName("lower")] - public string Lower { get; set; } + /// + /// This page's lowest package version. The version should be lowercased, normalized, + /// and the SemVer 2.0.0 build metadata removed, if any. + /// + [JsonPropertyName("lower")] + public string Lower { get; set; } - /// - /// This page's highest package version. The version should be lowercased, normalized, - /// and the SemVer 2.0.0 build metadata removed, if any. - /// - [JsonPropertyName("upper")] - public string Upper { get; set; } - } -} + /// + /// This page's highest package version. The version should be lowercased, normalized, + /// and the SemVer 2.0.0 build metadata removed, if any. + /// + [JsonPropertyName("upper")] + public string Upper { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationIndexPageItem.cs b/src/BaGet.Protocol/Models/RegistrationIndexPageItem.cs index 91668366a..4a34353e9 100644 --- a/src/BaGet.Protocol/Models/RegistrationIndexPageItem.cs +++ b/src/BaGet.Protocol/Models/RegistrationIndexPageItem.cs @@ -1,30 +1,29 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// An item in the that references a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf-object-in-a-page +/// +public class RegistrationIndexPageItem { /// - /// An item in the that references a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf-object-in-a-page + /// The URL to the registration leaf. /// - public class RegistrationIndexPageItem - { - /// - /// The URL to the registration leaf. - /// - [JsonPropertyName("@id")] - public string RegistrationLeafUrl { get; set; } + [JsonPropertyName("@id")] + public string RegistrationLeafUrl { get; set; } - /// - /// The catalog entry containing the package metadata. - /// - [JsonPropertyName("catalogEntry")] - public PackageMetadata PackageMetadata { get; set; } + /// + /// The catalog entry containing the package metadata. + /// + [JsonPropertyName("catalogEntry")] + public PackageMetadata PackageMetadata { get; set; } - /// - /// The URL to the package content (.nupkg) - /// - [JsonPropertyName("packageContent")] - public string PackageContentUrl { get; set; } - } -} + /// + /// The URL to the package content (.nupkg) + /// + [JsonPropertyName("packageContent")] + public string PackageContentUrl { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationIndexResponse.cs b/src/BaGet.Protocol/Models/RegistrationIndexResponse.cs index 79cf01bac..60ebe49be 100644 --- a/src/BaGet.Protocol/Models/RegistrationIndexResponse.cs +++ b/src/BaGet.Protocol/Models/RegistrationIndexResponse.cs @@ -1,45 +1,44 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The metadata for a package and all of its versions. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index +/// +public class RegistrationIndexResponse { - /// - /// The metadata for a package and all of its versions. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-index - /// - public class RegistrationIndexResponse + public static readonly IReadOnlyList DefaultType = new List { - public static readonly IReadOnlyList DefaultType = new List - { - "catalog:CatalogRoot", - "PackageRegistration", - "catalog:Permalink" - }; + "catalog:CatalogRoot", + "PackageRegistration", + "catalog:Permalink" + }; - /// - /// The URL to the registration index. - /// - [JsonPropertyName("@id")] - public string RegistrationIndexUrl { get; set; } + /// + /// The URL to the registration index. + /// + [JsonPropertyName("@id")] + public string RegistrationIndexUrl { get; set; } - /// - /// The registration index's type. - /// - [JsonPropertyName("@type")] - public IReadOnlyList Type { get; set; } + /// + /// The registration index's type. + /// + [JsonPropertyName("@type")] + public IReadOnlyList Type { get; set; } - /// - /// The number of registration pages. See . - /// - [JsonPropertyName("count")] - public int Count { get; set; } + /// + /// The number of registration pages. See . + /// + [JsonPropertyName("count")] + public int Count { get; set; } - /// - /// The pages that contain all of the versions of the package, ordered - /// by the package's version. - /// - [JsonPropertyName("items")] - public IReadOnlyList Pages { get; set; } - } -} + /// + /// The pages that contain all of the versions of the package, ordered + /// by the package's version. + /// + [JsonPropertyName("items")] + public IReadOnlyList Pages { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationLeafResponse.cs b/src/BaGet.Protocol/Models/RegistrationLeafResponse.cs index c95ca7ed1..02f125fca 100644 --- a/src/BaGet.Protocol/Models/RegistrationLeafResponse.cs +++ b/src/BaGet.Protocol/Models/RegistrationLeafResponse.cs @@ -2,56 +2,55 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The metadata for a single version of a package. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf +/// +public class RegistrationLeafResponse { + public static readonly IReadOnlyList DefaultType = new List + { + "Package", + "http://schema.nuget.org/catalog#Permalink" + }; + /// - /// The metadata for a single version of a package. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-leaf + /// The URL to the registration leaf. /// - public class RegistrationLeafResponse - { - public static readonly IReadOnlyList DefaultType = new List - { - "Package", - "http://schema.nuget.org/catalog#Permalink" - }; - - /// - /// The URL to the registration leaf. - /// - [JsonPropertyName("@id")] - public string RegistrationLeafUrl { get; set; } - - /// - /// The registration leaf's type. - /// - [JsonPropertyName("@type")] - public IReadOnlyList Type { get; set; } - - /// - /// Whether the package is listed. - /// - [JsonPropertyName("listed")] - public bool Listed { get; set; } - - /// - /// The URL to the package content (.nupkg). - /// - [JsonPropertyName("packageContent")] - public string PackageContentUrl { get; set; } - - /// - /// The date the package was published. On NuGet.org, - /// is set to the year 1900 if the package is unlisted. - /// - [JsonPropertyName("published")] - public DateTimeOffset Published { get; set; } - - /// - /// The URL to the package's registration index. - /// - [JsonPropertyName("registration")] - public string RegistrationIndexUrl { get; set; } - } -} + [JsonPropertyName("@id")] + public string RegistrationLeafUrl { get; set; } + + /// + /// The registration leaf's type. + /// + [JsonPropertyName("@type")] + public IReadOnlyList Type { get; set; } + + /// + /// Whether the package is listed. + /// + [JsonPropertyName("listed")] + public bool Listed { get; set; } + + /// + /// The URL to the package content (.nupkg). + /// + [JsonPropertyName("packageContent")] + public string PackageContentUrl { get; set; } + + /// + /// The date the package was published. On NuGet.org, + /// is set to the year 1900 if the package is unlisted. + /// + [JsonPropertyName("published")] + public DateTimeOffset Published { get; set; } + + /// + /// The URL to the package's registration index. + /// + [JsonPropertyName("registration")] + public string RegistrationIndexUrl { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/RegistrationPageResponse.cs b/src/BaGet.Protocol/Models/RegistrationPageResponse.cs index 60ee23d75..c7a4e819c 100644 --- a/src/BaGet.Protocol/Models/RegistrationPageResponse.cs +++ b/src/BaGet.Protocol/Models/RegistrationPageResponse.cs @@ -1,11 +1,10 @@ -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A page of package metadata entries. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page +/// +public class RegistrationPageResponse : RegistrationIndexPage { - /// - /// A page of package metadata entries. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - public class RegistrationPageResponse : RegistrationIndexPage - { - } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchContext.cs b/src/BaGet.Protocol/Models/SearchContext.cs index 6abfb92ea..19e231b21 100644 --- a/src/BaGet.Protocol/Models/SearchContext.cs +++ b/src/BaGet.Protocol/Models/SearchContext.cs @@ -1,22 +1,21 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +public class SearchContext { - public class SearchContext + public static SearchContext Default(string registrationBaseUrl) { - public static SearchContext Default(string registrationBaseUrl) + return new SearchContext { - return new SearchContext - { - Vocab = "http://schema.nuget.org/schema#", - Base = registrationBaseUrl - }; - } + Vocab = "http://schema.nuget.org/schema#", + Base = registrationBaseUrl + }; + } - [JsonPropertyName("@vocab")] - public string Vocab { get; set; } + [JsonPropertyName("@vocab")] + public string Vocab { get; set; } - [JsonPropertyName("@base")] - public string Base { get; set; } - } -} + [JsonPropertyName("@base")] + public string Base { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchResponse.cs b/src/BaGet.Protocol/Models/SearchResponse.cs index 70fce7393..f6145d595 100644 --- a/src/BaGet.Protocol/Models/SearchResponse.cs +++ b/src/BaGet.Protocol/Models/SearchResponse.cs @@ -1,28 +1,27 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The response to a search query. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#response +/// +public class SearchResponse { + [JsonPropertyName("@context")] + public SearchContext Context { get; set; } + /// - /// The response to a search query. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#response + /// The total number of matches, disregarding skip and take. /// - public class SearchResponse - { - [JsonPropertyName("@context")] - public SearchContext Context { get; set; } - - /// - /// The total number of matches, disregarding skip and take. - /// - [JsonPropertyName("totalHits")] - public long TotalHits { get; set; } + [JsonPropertyName("totalHits")] + public long TotalHits { get; set; } - /// - /// The packages that matched the search query. - /// - [JsonPropertyName("data")] - public IReadOnlyList Data { get; set; } - } -} + /// + /// The packages that matched the search query. + /// + [JsonPropertyName("data")] + public IReadOnlyList Data { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchResult.cs b/src/BaGet.Protocol/Models/SearchResult.cs index 4d2cd5769..ea18ec3e5 100644 --- a/src/BaGet.Protocol/Models/SearchResult.cs +++ b/src/BaGet.Protocol/Models/SearchResult.cs @@ -2,123 +2,122 @@ using System.Text.Json.Serialization; using BaGet.Protocol.Internal; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A package that matched a search query. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result +/// +public class SearchResult { /// - /// A package that matched a search query. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result - /// - public class SearchResult - { - /// - /// The ID of the matched package. - /// - [JsonPropertyName("id")] - public string PackageId { get; set; } - - /// - /// The latest version of the matched pacakge. This is the full NuGet version after normalization, - /// including any SemVer 2.0.0 build metadata. - /// - [JsonPropertyName("version")] - public string Version { get; set; } - - /// - /// The description of the matched package. - /// - [JsonPropertyName("description")] - public string Description { get; set; } - - /// - /// The authors of the matched package. - /// - [JsonPropertyName("authors")] - [JsonConverter(typeof(StringOrStringArrayJsonConverter))] - public IReadOnlyList Authors { get; set; } - - /// - /// The URL of the matched package's icon. - /// - [JsonPropertyName("iconUrl")] - public string IconUrl { get; set; } - - /// - /// The URL of the matched package's license. - /// - [JsonPropertyName("licenseUrl")] - public string LicenseUrl { get; set; } - - /// - /// The package types defined by the package author. - /// - [JsonPropertyName("packageTypes")] - public IReadOnlyList PackageTypes { get; set; } - - /// - /// The URL of the matched package's homepage. - /// - [JsonPropertyName("projectUrl")] - public string ProjectUrl { get; set; } - - /// - /// The URL for the matched package's registration index. - /// - [JsonPropertyName("registration")] - public string RegistrationIndexUrl { get; set; } - - /// - /// The summary of the matched package. - /// - [JsonPropertyName("summary")] - public string Summary { get; set; } - - /// - /// The tags of the matched package. - /// - [JsonPropertyName("tags")] - public IReadOnlyList Tags { get; set; } - - /// - /// The title of the matched package. - /// - [JsonPropertyName("title")] - public string Title { get; set; } - - /// - /// The total downloads for all versions of the matched package. - /// - [JsonPropertyName("totalDownloads")] - public long TotalDownloads { get; set; } - - /// - /// The versions of the matched package. - /// - [JsonPropertyName("versions")] - public IReadOnlyList Versions { get; set; } - - /// - /// The latest version's deprecation, or null if it is not deprecated. - /// - [JsonPropertyName("deprecation")] - public PackageDeprecation Deprecation { get; set; } - - /// - /// The latest version's known vulnerabilities, or null if it has none. - /// - [JsonPropertyName("vulnerabilities")] - public IReadOnlyList Vulnerabilities { get; set; } - - /// - /// The package's owners, or null if it has none. - /// - [JsonPropertyName("owners")] - public IReadOnlyList Owners { get; set; } - - /// - /// Whether the package ID is reserved for its owners. Null if it has no owners. - /// - [JsonPropertyName("verified")] - public bool? Verified { get; set; } - } -} + /// The ID of the matched package. + /// + [JsonPropertyName("id")] + public string PackageId { get; set; } + + /// + /// The latest version of the matched pacakge. This is the full NuGet version after normalization, + /// including any SemVer 2.0.0 build metadata. + /// + [JsonPropertyName("version")] + public string Version { get; set; } + + /// + /// The description of the matched package. + /// + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// The authors of the matched package. + /// + [JsonPropertyName("authors")] + [JsonConverter(typeof(StringOrStringArrayJsonConverter))] + public IReadOnlyList Authors { get; set; } + + /// + /// The URL of the matched package's icon. + /// + [JsonPropertyName("iconUrl")] + public string IconUrl { get; set; } + + /// + /// The URL of the matched package's license. + /// + [JsonPropertyName("licenseUrl")] + public string LicenseUrl { get; set; } + + /// + /// The package types defined by the package author. + /// + [JsonPropertyName("packageTypes")] + public IReadOnlyList PackageTypes { get; set; } + + /// + /// The URL of the matched package's homepage. + /// + [JsonPropertyName("projectUrl")] + public string ProjectUrl { get; set; } + + /// + /// The URL for the matched package's registration index. + /// + [JsonPropertyName("registration")] + public string RegistrationIndexUrl { get; set; } + + /// + /// The summary of the matched package. + /// + [JsonPropertyName("summary")] + public string Summary { get; set; } + + /// + /// The tags of the matched package. + /// + [JsonPropertyName("tags")] + public IReadOnlyList Tags { get; set; } + + /// + /// The title of the matched package. + /// + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// The total downloads for all versions of the matched package. + /// + [JsonPropertyName("totalDownloads")] + public long TotalDownloads { get; set; } + + /// + /// The versions of the matched package. + /// + [JsonPropertyName("versions")] + public IReadOnlyList Versions { get; set; } + + /// + /// The latest version's deprecation, or null if it is not deprecated. + /// + [JsonPropertyName("deprecation")] + public PackageDeprecation Deprecation { get; set; } + + /// + /// The latest version's known vulnerabilities, or null if it has none. + /// + [JsonPropertyName("vulnerabilities")] + public IReadOnlyList Vulnerabilities { get; set; } + + /// + /// The package's owners, or null if it has none. + /// + [JsonPropertyName("owners")] + public IReadOnlyList Owners { get; set; } + + /// + /// Whether the package ID is reserved for its owners. Null if it has no owners. + /// + [JsonPropertyName("verified")] + public bool? Verified { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchResultPackageType.cs b/src/BaGet.Protocol/Models/SearchResultPackageType.cs index aa353b7cc..7bddbdf86 100644 --- a/src/BaGet.Protocol/Models/SearchResultPackageType.cs +++ b/src/BaGet.Protocol/Models/SearchResultPackageType.cs @@ -1,18 +1,17 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A single package type from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result +/// +public class SearchResultPackageType { /// - /// A single package type from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + /// The name of the package type. /// - public class SearchResultPackageType - { - /// - /// The name of the package type. - /// - [JsonPropertyName("name")] - public string Name { get; set; } - } -} + [JsonPropertyName("name")] + public string Name { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/SearchResultVersion.cs b/src/BaGet.Protocol/Models/SearchResultVersion.cs index a3a2cb237..9145fbb84 100644 --- a/src/BaGet.Protocol/Models/SearchResultVersion.cs +++ b/src/BaGet.Protocol/Models/SearchResultVersion.cs @@ -1,30 +1,29 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A single version from a . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result +/// +public class SearchResultVersion { /// - /// A single version from a . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-result + /// The registration leaf URL for this single version of the matched package. /// - public class SearchResultVersion - { - /// - /// The registration leaf URL for this single version of the matched package. - /// - [JsonPropertyName("@id")] - public string RegistrationLeafUrl { get; set; } + [JsonPropertyName("@id")] + public string RegistrationLeafUrl { get; set; } - /// - /// The package's full NuGet version after normalization, including any SemVer 2.0.0 build metadata. - /// - [JsonPropertyName("version")] - public string Version { get; set; } + /// + /// The package's full NuGet version after normalization, including any SemVer 2.0.0 build metadata. + /// + [JsonPropertyName("version")] + public string Version { get; set; } - /// - /// The downloads for this single version of the matched package. - /// - [JsonPropertyName("downloads")] - public long Downloads { get; set; } - } -} + /// + /// The downloads for this single version of the matched package. + /// + [JsonPropertyName("downloads")] + public long Downloads { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/ServiceIndexItem.cs b/src/BaGet.Protocol/Models/ServiceIndexItem.cs index 36ba43881..f984117a3 100644 --- a/src/BaGet.Protocol/Models/ServiceIndexItem.cs +++ b/src/BaGet.Protocol/Models/ServiceIndexItem.cs @@ -1,30 +1,29 @@ using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// A resource in the . +/// +/// See https://docs.microsoft.com/en-us/nuget/api/service-index#resources +/// +public class ServiceIndexItem { /// - /// A resource in the . - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index#resources + /// The resource's base URL. /// - public class ServiceIndexItem - { - /// - /// The resource's base URL. - /// - [JsonPropertyName("@id")] - public string ResourceUrl { get; set; } + [JsonPropertyName("@id")] + public string ResourceUrl { get; set; } - /// - /// The resource's type. - /// - [JsonPropertyName("@type")] - public string Type { get; set; } + /// + /// The resource's type. + /// + [JsonPropertyName("@type")] + public string Type { get; set; } - /// - /// Human readable comments about the resource. - /// - [JsonPropertyName("comment")] - public string Comment { get; set; } - } -} + /// + /// Human readable comments about the resource. + /// + [JsonPropertyName("comment")] + public string Comment { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Models/ServiceIndexResponse.cs b/src/BaGet.Protocol/Models/ServiceIndexResponse.cs index 4b0327124..bae43b457 100644 --- a/src/BaGet.Protocol/Models/ServiceIndexResponse.cs +++ b/src/BaGet.Protocol/Models/ServiceIndexResponse.cs @@ -1,25 +1,24 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -namespace BaGet.Protocol.Models +namespace BaGet.Protocol.Models; + +/// +/// The entry point for a NuGet package source used by the client to discover NuGet APIs. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/overview +/// +public class ServiceIndexResponse { /// - /// The entry point for a NuGet package source used by the client to discover NuGet APIs. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/overview + /// The service index's version. /// - public class ServiceIndexResponse - { - /// - /// The service index's version. - /// - [JsonPropertyName("version")] - public string Version { get; set; } + [JsonPropertyName("version")] + public string Version { get; set; } - /// - /// The resources declared by this service index. - /// - [JsonPropertyName("resources")] - public IReadOnlyList Resources { get; set; } - } -} + /// + /// The resources declared by this service index. + /// + [JsonPropertyName("resources")] + public IReadOnlyList Resources { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Protocol/NuGetClient.cs b/src/BaGet.Protocol/NuGetClient.cs index 07cf1bf78..8605789bd 100644 --- a/src/BaGet.Protocol/NuGetClient.cs +++ b/src/BaGet.Protocol/NuGetClient.cs @@ -9,492 +9,491 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The client to interact with a NuGet server. +/// +public class NuGetClient { + private readonly IPackageContentClient _contentClient; + private readonly IPackageMetadataClient _metadataClient; + private readonly ISearchClient _searchClient; + private readonly IAutocompleteClient _autocompleteClient; + /// - /// The client to interact with a NuGet server. + /// Initializes a new instance of the class + /// for mocking. /// - public class NuGetClient + protected NuGetClient() { - private readonly IPackageContentClient _contentClient; - private readonly IPackageMetadataClient _metadataClient; - private readonly ISearchClient _searchClient; - private readonly IAutocompleteClient _autocompleteClient; - - /// - /// Initializes a new instance of the class - /// for mocking. - /// - protected NuGetClient() - { - } + } - /// - /// Initializes a new instance of the class. - /// - /// - /// The NuGet Service Index resource URL. - /// - /// For NuGet.org, use https://api.nuget.org/v3/index.json - /// - public NuGetClient(string serviceIndexUrl) + /// + /// Initializes a new instance of the class. + /// + /// + /// The NuGet Service Index resource URL. + /// + /// For NuGet.org, use https://api.nuget.org/v3/index.json + /// + public NuGetClient(string serviceIndexUrl) + { + var httpClient = new HttpClient(new HttpClientHandler { - var httpClient = new HttpClient(new HttpClientHandler - { - AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, - }); + AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, + }); - var clientFactory = new NuGetClientFactory(httpClient, serviceIndexUrl); + var clientFactory = new NuGetClientFactory(httpClient, serviceIndexUrl); - _contentClient = clientFactory.CreatePackageContentClient(); - _metadataClient = clientFactory.CreatePackageMetadataClient(); - _searchClient = clientFactory.CreateSearchClient(); - _autocompleteClient = clientFactory.CreateAutocompleteClient(); - } + _contentClient = clientFactory.CreatePackageContentClient(); + _metadataClient = clientFactory.CreatePackageMetadataClient(); + _searchClient = clientFactory.CreateSearchClient(); + _autocompleteClient = clientFactory.CreateAutocompleteClient(); + } - /// - /// Initializes a new instance of the class. - /// - /// The factory used to create NuGet clients. - public NuGetClient(NuGetClientFactory clientFactory) - { - if (clientFactory == null) throw new ArgumentNullException(nameof(clientFactory)); + /// + /// Initializes a new instance of the class. + /// + /// The factory used to create NuGet clients. + public NuGetClient(NuGetClientFactory clientFactory) + { + if (clientFactory == null) throw new ArgumentNullException(nameof(clientFactory)); - _contentClient = clientFactory.CreatePackageContentClient(); - _metadataClient = clientFactory.CreatePackageMetadataClient(); - _searchClient = clientFactory.CreateSearchClient(); - _autocompleteClient = clientFactory.CreateAutocompleteClient(); - } + _contentClient = clientFactory.CreatePackageContentClient(); + _metadataClient = clientFactory.CreatePackageMetadataClient(); + _searchClient = clientFactory.CreateSearchClient(); + _autocompleteClient = clientFactory.CreateAutocompleteClient(); + } - /// - /// Check if a package exists. - /// - /// The package ID. - /// A token to cancel the task. - /// Whether the package exists. - public virtual async Task ExistsAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var versions = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + /// + /// Check if a package exists. + /// + /// The package ID. + /// A token to cancel the task. + /// Whether the package exists. + public virtual async Task ExistsAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var versions = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); - return (versions != null && versions.Versions.Any()); - } + return (versions != null && versions.Versions.Any()); + } + + /// + /// Check if a package exists. + /// + /// The package ID. + /// The package version. + /// A token to cancel the task. + /// Whether the package exists. + public virtual async Task ExistsAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + var versions = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); - /// - /// Check if a package exists. - /// - /// The package ID. - /// The package version. - /// A token to cancel the task. - /// Whether the package exists. - public virtual async Task ExistsAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) + if (versions == null) { - var versions = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + return false; + } - if (versions == null) - { - return false; - } + return versions + .ParseVersions() + .Any(v => v == packageVersion); + } - return versions - .ParseVersions() - .Any(v => v == packageVersion); - } + /// + /// Download a package (.nupkg), or throws if the package does not exist. + /// + /// The package ID. + /// The package version. + /// A token to cancel the task. + /// The package's content stream. The stream may be unseekable and may be unbuffered. + /// + /// The package could not be found. + /// + public virtual async Task DownloadPackageAsync(string packageId, NuGetVersion packageVersion, CancellationToken cancellationToken = default) + { + var stream = await _contentClient.DownloadPackageOrNullAsync(packageId, packageVersion, cancellationToken); - /// - /// Download a package (.nupkg), or throws if the package does not exist. - /// - /// The package ID. - /// The package version. - /// A token to cancel the task. - /// The package's content stream. The stream may be unseekable and may be unbuffered. - /// - /// The package could not be found. - /// - public virtual async Task DownloadPackageAsync(string packageId, NuGetVersion packageVersion, CancellationToken cancellationToken = default) + if (stream == null) { - var stream = await _contentClient.DownloadPackageOrNullAsync(packageId, packageVersion, cancellationToken); + throw new PackageNotFoundException(packageId, packageVersion); + } - if (stream == null) - { - throw new PackageNotFoundException(packageId, packageVersion); - } + return stream; + } - return stream; - } + /// + /// Download a package's manifest (.nuspec), or throws if the package does not exist. + /// + /// The package ID. + /// The package version. + /// A token to cancel the task. + /// The package's manifest stream. The stream may not be seekable. + /// + /// The package could not be found. + /// + public virtual async Task DownloadPackageManifestAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + var stream = await _contentClient.DownloadPackageManifestOrNullAsync(packageId, packageVersion, cancellationToken); - /// - /// Download a package's manifest (.nuspec), or throws if the package does not exist. - /// - /// The package ID. - /// The package version. - /// A token to cancel the task. - /// The package's manifest stream. The stream may not be seekable. - /// - /// The package could not be found. - /// - public virtual async Task DownloadPackageManifestAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) + if (stream == null) { - var stream = await _contentClient.DownloadPackageManifestOrNullAsync(packageId, packageVersion, cancellationToken); + throw new PackageNotFoundException(packageId, packageVersion); + } - if (stream == null) - { - throw new PackageNotFoundException(packageId, packageVersion); - } + return stream; + } - return stream; - } + /// + /// Find all versions of a package, excluding unlisted versions. + /// + /// The package ID. + /// A token to cancel the task. + /// The package's listed versions, if any. + public virtual async Task> ListPackageVersionsAsync( + string packageId, + CancellationToken cancellationToken = default) + { + // The registration metadata is read instead of the Autocomplete resource's enumerate + // versions endpoint, even though the latter is cheaper: that endpoint is optional, and + // a server may advertise the Autocomplete resource without supporting it - Sleet, whose + // feed is static files, is the known case. There is no advertised capability that says + // which, so choosing it would mean fingerprinting the server and silently returning an + // empty version list when the guess is wrong. Registration metadata is always present. + var packages = await GetPackageMetadataAsync(packageId, cancellationToken); + + return packages + .Where(p => p.IsListed()) + .Select(p => p.ParseVersion()) + .ToList(); + } - /// - /// Find all versions of a package, excluding unlisted versions. - /// - /// The package ID. - /// A token to cancel the task. - /// The package's listed versions, if any. - public virtual async Task> ListPackageVersionsAsync( - string packageId, - CancellationToken cancellationToken = default) + /// + /// Find all versions of a package. + /// + /// The package ID. + /// Whether to include unlisted versions. + /// A token to cancel the task. + /// The package's versions, or an empty list if the package does not exist. + public virtual async Task> ListPackageVersionsAsync( + string packageId, + bool includeUnlisted, + CancellationToken cancellationToken = default) + { + if (!includeUnlisted) { - // The registration metadata is read instead of the Autocomplete resource's enumerate - // versions endpoint, even though the latter is cheaper: that endpoint is optional, and - // a server may advertise the Autocomplete resource without supporting it - Sleet, whose - // feed is static files, is the known case. There is no advertised capability that says - // which, so choosing it would mean fingerprinting the server and silently returning an - // empty version list when the guess is wrong. Registration metadata is always present. - var packages = await GetPackageMetadataAsync(packageId, cancellationToken); - - return packages - .Where(p => p.IsListed()) - .Select(p => p.ParseVersion()) - .ToList(); + return await ListPackageVersionsAsync(packageId, cancellationToken); } - /// - /// Find all versions of a package. - /// - /// The package ID. - /// Whether to include unlisted versions. - /// A token to cancel the task. - /// The package's versions, or an empty list if the package does not exist. - public virtual async Task> ListPackageVersionsAsync( - string packageId, - bool includeUnlisted, - CancellationToken cancellationToken = default) + var response = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + + if (response == null) { - if (!includeUnlisted) - { - return await ListPackageVersionsAsync(packageId, cancellationToken); - } + return new List(); + } - var response = await _contentClient.GetPackageVersionsOrNullAsync(packageId, cancellationToken); + return response.ParseVersions(); + } - if (response == null) - { - return new List(); - } + /// + /// Find the metadata for all versions of a package, including unlisted versions. + /// + /// The package ID. + /// A token to cancel the task. + /// The package's metadata, or an empty list if the package does not exist. + public virtual async Task> GetPackageMetadataAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var result = new List(); - return response.ParseVersions(); - } + var registrationIndex = await _metadataClient.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); - /// - /// Find the metadata for all versions of a package, including unlisted versions. - /// - /// The package ID. - /// A token to cancel the task. - /// The package's metadata, or an empty list if the package does not exist. - public virtual async Task> GetPackageMetadataAsync( - string packageId, - CancellationToken cancellationToken = default) + if (registrationIndex == null) { - var result = new List(); - - var registrationIndex = await _metadataClient.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + return result; + } - if (registrationIndex == null) + foreach (var registrationIndexPage in registrationIndex.Pages) + { + // If the package's registration index is too big, it will be split into registration + // pages stored at different URLs. We will need to fetch each page's items individually. + // We can detect this case as the registration index will have "null" items. + var items = registrationIndexPage.ItemsOrNull; + if (items == null) { - return result; - } + var externalRegistrationPage = await _metadataClient.GetRegistrationPageAsync( + registrationIndexPage.RegistrationPageUrl, + cancellationToken); - foreach (var registrationIndexPage in registrationIndex.Pages) - { - // If the package's registration index is too big, it will be split into registration - // pages stored at different URLs. We will need to fetch each page's items individually. - // We can detect this case as the registration index will have "null" items. - var items = registrationIndexPage.ItemsOrNull; - if (items == null) - { - var externalRegistrationPage = await _metadataClient.GetRegistrationPageAsync( - registrationIndexPage.RegistrationPageUrl, - cancellationToken); - - // Skip malformed external pages. - if (externalRegistrationPage?.ItemsOrNull == null) continue; - - items = externalRegistrationPage.ItemsOrNull; - } - - result.AddRange(items.Select(i => i.PackageMetadata)); + // Skip malformed external pages. + if (externalRegistrationPage?.ItemsOrNull == null) continue; + + items = externalRegistrationPage.ItemsOrNull; } - return result; + result.AddRange(items.Select(i => i.PackageMetadata)); } - /// - /// Find the metadata for a single version of a package, or throws if the package does not exist. - /// - /// The package ID. - /// The package version. - /// A token to cancel the task. - /// The package's metadata. - /// - /// The package could not be found. - /// - public virtual async Task GetPackageMetadataAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) + return result; + } + + /// + /// Find the metadata for a single version of a package, or throws if the package does not exist. + /// + /// The package ID. + /// The package version. + /// A token to cancel the task. + /// The package's metadata. + /// + /// The package could not be found. + /// + public virtual async Task GetPackageMetadataAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + var registrationIndex = await _metadataClient.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + + if (registrationIndex == null) { - var registrationIndex = await _metadataClient.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + throw new PackageNotFoundException(packageId, packageVersion); + } - if (registrationIndex == null) + foreach (var registrationIndexPage in registrationIndex.Pages) + { + // Skip pages that do not contain the desired package version. + var pageLowerVersion = registrationIndexPage.ParseLower(); + var pageUpperVersion = registrationIndexPage.ParseUpper(); + + if (pageLowerVersion > packageVersion) continue; + if (pageUpperVersion < packageVersion) continue; + + // If the package's registration index is too big, it will be split into registration + // pages stored at different URLs. We will need to fetch each page's items individually. + // We can detect this case as the registration index will have "null" items. + var items = registrationIndexPage.ItemsOrNull; + if (items == null) { - throw new PackageNotFoundException(packageId, packageVersion); + var externalRegistrationPage = await _metadataClient.GetRegistrationPageAsync( + registrationIndexPage.RegistrationPageUrl, + cancellationToken); + + // Skip malformed external pages. + if (externalRegistrationPage?.ItemsOrNull == null) continue; + + items = externalRegistrationPage.ItemsOrNull; } - foreach (var registrationIndexPage in registrationIndex.Pages) + // We've found the registration items that should cover the desired package. + var result = items.SingleOrDefault(i => i.PackageMetadata.ParseVersion() == packageVersion); + if (result == null) { - // Skip pages that do not contain the desired package version. - var pageLowerVersion = registrationIndexPage.ParseLower(); - var pageUpperVersion = registrationIndexPage.ParseUpper(); - - if (pageLowerVersion > packageVersion) continue; - if (pageUpperVersion < packageVersion) continue; - - // If the package's registration index is too big, it will be split into registration - // pages stored at different URLs. We will need to fetch each page's items individually. - // We can detect this case as the registration index will have "null" items. - var items = registrationIndexPage.ItemsOrNull; - if (items == null) - { - var externalRegistrationPage = await _metadataClient.GetRegistrationPageAsync( - registrationIndexPage.RegistrationPageUrl, - cancellationToken); - - // Skip malformed external pages. - if (externalRegistrationPage?.ItemsOrNull == null) continue; - - items = externalRegistrationPage.ItemsOrNull; - } - - // We've found the registration items that should cover the desired package. - var result = items.SingleOrDefault(i => i.PackageMetadata.ParseVersion() == packageVersion); - if (result == null) - { - break; - } - - return result.PackageMetadata; + break; } - // No registration pages contained the desired version. - throw new PackageNotFoundException(packageId, packageVersion); + return result.PackageMetadata; } - /// - /// Search for packages. Includes prerelease packages. - /// - /// - /// The search query. If , gets default search results. - /// - /// A token to cancel the task. - /// The search results, including prerelease packages. - public virtual async Task> SearchAsync( - string query = null, - CancellationToken cancellationToken = default) - { - var response = await _searchClient.SearchAsync(query, cancellationToken: cancellationToken); + // No registration pages contained the desired version. + throw new PackageNotFoundException(packageId, packageVersion); + } - return response.Data; - } + /// + /// Search for packages. Includes prerelease packages. + /// + /// + /// The search query. If , gets default search results. + /// + /// A token to cancel the task. + /// The search results, including prerelease packages. + public virtual async Task> SearchAsync( + string query = null, + CancellationToken cancellationToken = default) + { + var response = await _searchClient.SearchAsync(query, cancellationToken: cancellationToken); - /// - /// Search for packages. Includes prerelease packages. - /// - /// - /// The search query. If , gets default search results. - /// - /// The number of results to skip. - /// The number of results to include. - /// A token to cancel the task. - /// The search results, including prerelease packages. - public virtual async Task> SearchAsync( - string query, - int skip, - int take, - CancellationToken cancellationToken = default) - { - var response = await _searchClient.SearchAsync( - query, - skip, - take, - includePrerelease: true, - includeSemVer2: true, - cancellationToken: cancellationToken); - - return response.Data; - } + return response.Data; + } - /// - /// Search for packages. - /// - /// - /// The search query. If , gets default search results. - /// - /// Whether to include prerelease packages. - /// A token to cancel the task. - /// The search results. - public virtual async Task> SearchAsync( - string query, - bool includePrerelease, - CancellationToken cancellationToken = default) - { - var response = await _searchClient.SearchAsync( - query, - includePrerelease: includePrerelease, - cancellationToken: cancellationToken); + /// + /// Search for packages. Includes prerelease packages. + /// + /// + /// The search query. If , gets default search results. + /// + /// The number of results to skip. + /// The number of results to include. + /// A token to cancel the task. + /// The search results, including prerelease packages. + public virtual async Task> SearchAsync( + string query, + int skip, + int take, + CancellationToken cancellationToken = default) + { + var response = await _searchClient.SearchAsync( + query, + skip, + take, + includePrerelease: true, + includeSemVer2: true, + cancellationToken: cancellationToken); + + return response.Data; + } - return response.Data; - } + /// + /// Search for packages. + /// + /// + /// The search query. If , gets default search results. + /// + /// Whether to include prerelease packages. + /// A token to cancel the task. + /// The search results. + public virtual async Task> SearchAsync( + string query, + bool includePrerelease, + CancellationToken cancellationToken = default) + { + var response = await _searchClient.SearchAsync( + query, + includePrerelease: includePrerelease, + cancellationToken: cancellationToken); - /// - /// Search for packages. - /// - /// - /// The search query. If , gets default search results. - /// - /// The number of results to skip. - /// The number of results to include. - /// Whether to include prerelease packages. - /// A token to cancel the task. - /// The search results, including prerelease packages. - public virtual async Task> SearchAsync( - string query, - int skip, - int take, - bool includePrerelease, - CancellationToken cancellationToken = default) - { - var response = await _searchClient.SearchAsync( - query, - skip, - take, - includePrerelease, - includeSemVer2: true, - cancellationToken); - - return response.Data; - } + return response.Data; + } - /// - /// Search for package IDs. Includes prerelease packages. - /// - /// - /// The search query. If , gets default autocomplete results. - /// - /// A token to cancel the task. - /// The package IDs that matched the query. - public virtual async Task> AutocompleteAsync( - string query = null, - CancellationToken cancellationToken = default) - { - var response = await _autocompleteClient.AutocompleteAsync(query, cancellationToken: cancellationToken); + /// + /// Search for packages. + /// + /// + /// The search query. If , gets default search results. + /// + /// The number of results to skip. + /// The number of results to include. + /// Whether to include prerelease packages. + /// A token to cancel the task. + /// The search results, including prerelease packages. + public virtual async Task> SearchAsync( + string query, + int skip, + int take, + bool includePrerelease, + CancellationToken cancellationToken = default) + { + var response = await _searchClient.SearchAsync( + query, + skip, + take, + includePrerelease, + includeSemVer2: true, + cancellationToken); + + return response.Data; + } - return response.Data; - } + /// + /// Search for package IDs. Includes prerelease packages. + /// + /// + /// The search query. If , gets default autocomplete results. + /// + /// A token to cancel the task. + /// The package IDs that matched the query. + public virtual async Task> AutocompleteAsync( + string query = null, + CancellationToken cancellationToken = default) + { + var response = await _autocompleteClient.AutocompleteAsync(query, cancellationToken: cancellationToken); - /// - /// Search for package IDs. Includes prerelease packages. - /// - /// - /// The search query. If , gets default autocomplete results. - /// - /// The number of results to skip. - /// The number of results to include. - /// A token to cancel the task. - /// The package IDs that matched the query. - public virtual async Task> AutocompleteAsync( - string query, - int skip, - int take, - CancellationToken cancellationToken = default) - { - var response = await _autocompleteClient.AutocompleteAsync( - query, - skip, - take, - includePrerelease: true, - includeSemVer2: true, - cancellationToken); - - return response.Data; - } + return response.Data; + } - /// - /// Search for package IDs. - /// - /// - /// The search query. If , gets default autocomplete results. - /// - /// Whether to include prerelease packages. - /// A token to cancel the task. - /// The package IDs that matched the query. - public virtual async Task> AutocompleteAsync( - string query, - bool includePrerelease, - CancellationToken cancellationToken = default) - { - var response = await _autocompleteClient.AutocompleteAsync( - query, - includePrerelease: includePrerelease, - cancellationToken: cancellationToken); + /// + /// Search for package IDs. Includes prerelease packages. + /// + /// + /// The search query. If , gets default autocomplete results. + /// + /// The number of results to skip. + /// The number of results to include. + /// A token to cancel the task. + /// The package IDs that matched the query. + public virtual async Task> AutocompleteAsync( + string query, + int skip, + int take, + CancellationToken cancellationToken = default) + { + var response = await _autocompleteClient.AutocompleteAsync( + query, + skip, + take, + includePrerelease: true, + includeSemVer2: true, + cancellationToken); + + return response.Data; + } - return response.Data; - } + /// + /// Search for package IDs. + /// + /// + /// The search query. If , gets default autocomplete results. + /// + /// Whether to include prerelease packages. + /// A token to cancel the task. + /// The package IDs that matched the query. + public virtual async Task> AutocompleteAsync( + string query, + bool includePrerelease, + CancellationToken cancellationToken = default) + { + var response = await _autocompleteClient.AutocompleteAsync( + query, + includePrerelease: includePrerelease, + cancellationToken: cancellationToken); - /// - /// Search for package IDs. - /// - /// - /// The search query. If , gets default autocomplete results. - /// - /// The number of results to skip. - /// The number of results to include. - /// Whether to include prerelease packages. - /// A token to cancel the task. - /// The package IDs that matched the query. - public virtual async Task> AutocompleteAsync( - string query, - int skip, - int take, - bool includePrerelease, - CancellationToken cancellationToken = default) - { - var response = await _autocompleteClient.AutocompleteAsync( - query, - skip, - take, - includePrerelease, - includeSemVer2: true, - cancellationToken); - - return response.Data; - } + return response.Data; + } + + /// + /// Search for package IDs. + /// + /// + /// The search query. If , gets default autocomplete results. + /// + /// The number of results to skip. + /// The number of results to include. + /// Whether to include prerelease packages. + /// A token to cancel the task. + /// The package IDs that matched the query. + public virtual async Task> AutocompleteAsync( + string query, + int skip, + int take, + bool includePrerelease, + CancellationToken cancellationToken = default) + { + var response = await _autocompleteClient.AutocompleteAsync( + query, + skip, + take, + includePrerelease, + includeSemVer2: true, + cancellationToken); + + return response.Data; } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/NuGetClientFactory.cs b/src/BaGet.Protocol/NuGetClientFactory.cs index cc3eb021c..2e9be0a27 100644 --- a/src/BaGet.Protocol/NuGetClientFactory.cs +++ b/src/BaGet.Protocol/NuGetClientFactory.cs @@ -7,262 +7,261 @@ using BaGet.Protocol.Internal; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The creates clients to interact with a NuGet server. +/// Use this for advanced scenarios. For most scenarios, consider using instead. +/// +public partial class NuGetClientFactory { /// - /// The creates clients to interact with a NuGet server. - /// Use this for advanced scenarios. For most scenarios, consider using instead. + /// How long a service index response is reused before it is fetched again. A long-lived + /// factory therefore picks up resources the server adds, moves or removes, without + /// re-fetching the index on every request. NuGet's own client caches the service index + /// for the same reason and for the same duration; see NuGet.Protocol's + /// ServiceIndexResourceV3Provider.MaxCacheDuration. /// - public partial class NuGetClientFactory - { - /// - /// How long a service index response is reused before it is fetched again. A long-lived - /// factory therefore picks up resources the server adds, moves or removes, without - /// re-fetching the index on every request. NuGet's own client caches the service index - /// for the same reason and for the same duration; see NuGet.Protocol's - /// ServiceIndexResourceV3Provider.MaxCacheDuration. - /// - internal static readonly TimeSpan DefaultServiceIndexCacheDuration = TimeSpan.FromMinutes(40); + internal static readonly TimeSpan DefaultServiceIndexCacheDuration = TimeSpan.FromMinutes(40); - private readonly HttpClient _httpClient; - private readonly string _serviceIndexUrl; + private readonly HttpClient _httpClient; + private readonly string _serviceIndexUrl; - private readonly TimeSpan _serviceIndexCacheDuration = DefaultServiceIndexCacheDuration; - private readonly Func _clock = () => DateTimeOffset.UtcNow; + private readonly TimeSpan _serviceIndexCacheDuration = DefaultServiceIndexCacheDuration; + private readonly Func _clock = () => DateTimeOffset.UtcNow; - private readonly SemaphoreSlim _mutex; - private volatile NuGetClients _clients; + private readonly SemaphoreSlim _mutex; + private volatile NuGetClients _clients; - /// - /// Initializes a new instance of the class - /// for mocking. - /// - protected NuGetClientFactory() - { - } + /// + /// Initializes a new instance of the class + /// for mocking. + /// + protected NuGetClientFactory() + { + } - /// - /// Initializes a new instance of the class. - /// - /// The client used for HTTP requests. - /// - /// The NuGet Service Index resource URL. - /// - /// For NuGet.org, use https://api.nuget.org/v3/index.json - /// - public NuGetClientFactory(HttpClient httpClient, string serviceIndexUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _serviceIndexUrl = serviceIndexUrl ?? throw new ArgumentNullException(nameof(serviceIndexUrl)); + /// + /// Initializes a new instance of the class. + /// + /// The client used for HTTP requests. + /// + /// The NuGet Service Index resource URL. + /// + /// For NuGet.org, use https://api.nuget.org/v3/index.json + /// + public NuGetClientFactory(HttpClient httpClient, string serviceIndexUrl) + { + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _serviceIndexUrl = serviceIndexUrl ?? throw new ArgumentNullException(nameof(serviceIndexUrl)); - _mutex = new SemaphoreSlim(1, 1); - _clients = null; - } + _mutex = new SemaphoreSlim(1, 1); + _clients = null; + } - /// - /// Initializes a new instance of the class with a - /// service index cache duration and a clock of its own, so that the expiry can be tested. - /// - internal NuGetClientFactory( - HttpClient httpClient, - string serviceIndexUrl, - TimeSpan serviceIndexCacheDuration, - Func clock) - : this(httpClient, serviceIndexUrl) + /// + /// Initializes a new instance of the class with a + /// service index cache duration and a clock of its own, so that the expiry can be tested. + /// + internal NuGetClientFactory( + HttpClient httpClient, + string serviceIndexUrl, + TimeSpan serviceIndexCacheDuration, + Func clock) + : this(httpClient, serviceIndexUrl) + { + if (serviceIndexCacheDuration < TimeSpan.Zero) { - if (serviceIndexCacheDuration < TimeSpan.Zero) - { - throw new ArgumentOutOfRangeException(nameof(serviceIndexCacheDuration)); - } - - _serviceIndexCacheDuration = serviceIndexCacheDuration; - _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + throw new ArgumentOutOfRangeException(nameof(serviceIndexCacheDuration)); } - /// - /// Create a client to interact with the NuGet Service Index resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index - /// - /// A client to interact with the NuGet Service Index resource. - public virtual IServiceIndexClient CreateServiceIndexClient() - { - return new ServiceIndexClient(this); - } + _serviceIndexCacheDuration = serviceIndexCacheDuration; + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + } - /// - /// Create a client to interact with the NuGet Package Content resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource - /// - /// A client to interact with the NuGet Package Content resource. - public virtual IPackageContentClient CreatePackageContentClient() - { - return new PackageContentClient(this); - } + /// + /// Create a client to interact with the NuGet Service Index resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/service-index + /// + /// A client to interact with the NuGet Service Index resource. + public virtual IServiceIndexClient CreateServiceIndexClient() + { + return new ServiceIndexClient(this); + } - /// - /// Create a client to interact with the NuGet Package Metadata resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource - /// - /// A client to interact with the NuGet Package Metadata resource. - public virtual IPackageMetadataClient CreatePackageMetadataClient() - { - return new PackageMetadataClient(this); - } + /// + /// Create a client to interact with the NuGet Package Content resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource + /// + /// A client to interact with the NuGet Package Content resource. + public virtual IPackageContentClient CreatePackageContentClient() + { + return new PackageContentClient(this); + } - /// - /// Create a client to interact with the NuGet Search resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource - /// - /// A client to interact with the NuGet Search resource. - public virtual ISearchClient CreateSearchClient() - { - return new SearchClient(this); - } + /// + /// Create a client to interact with the NuGet Package Metadata resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource + /// + /// A client to interact with the NuGet Package Metadata resource. + public virtual IPackageMetadataClient CreatePackageMetadataClient() + { + return new PackageMetadataClient(this); + } - /// - /// Create a client to interact with the NuGet Autocomplete resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource - /// - /// A client to interact with the NuGet Autocomplete resource. - public virtual IAutocompleteClient CreateAutocompleteClient() - { - return new AutocompleteClient(this); - } + /// + /// Create a client to interact with the NuGet Search resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// + /// A client to interact with the NuGet Search resource. + public virtual ISearchClient CreateSearchClient() + { + return new SearchClient(this); + } - /// - /// Create a client to interact with the NuGet catalog resource. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource - /// - /// A client to interact with the Catalog resource. - public virtual ICatalogClient CreateCatalogClient() - { - return new CatalogClient(this); - } + /// + /// Create a client to interact with the NuGet Autocomplete resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource + /// + /// A client to interact with the NuGet Autocomplete resource. + public virtual IAutocompleteClient CreateAutocompleteClient() + { + return new AutocompleteClient(this); + } + /// + /// Create a client to interact with the NuGet catalog resource. + /// + /// See https://docs.microsoft.com/en-us/nuget/api/catalog-resource + /// + /// A client to interact with the Catalog resource. + public virtual ICatalogClient CreateCatalogClient() + { + return new CatalogClient(this); + } - private Task GetServiceIndexAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.ServiceIndex, cancellationToken); - } - private Task GetPackageContentClientAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.PackageContentClient, cancellationToken); - } + private Task GetServiceIndexAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.ServiceIndex, cancellationToken); + } - private Task GetPackageMetadataClientAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.PackageMetadataClient, cancellationToken); - } + private Task GetPackageContentClientAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.PackageContentClient, cancellationToken); + } - private Task> GetSearchClientsAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.SearchClients, cancellationToken); - } + private Task GetPackageMetadataClientAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.PackageMetadataClient, cancellationToken); + } - private Task> GetAutocompleteClientsAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.AutocompleteClients, cancellationToken); - } + private Task> GetSearchClientsAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.SearchClients, cancellationToken); + } - private Task GetCatalogClientAsync(CancellationToken cancellationToken = default) - { - return GetAsync(c => c.CatalogClient, cancellationToken); - } + private Task> GetAutocompleteClientsAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.AutocompleteClients, cancellationToken); + } - private async Task GetAsync(Func clientFactory, CancellationToken cancellationToken) - { - var clients = _clients; + private Task GetCatalogClientAsync(CancellationToken cancellationToken = default) + { + return GetAsync(c => c.CatalogClient, cancellationToken); + } - if (clients == null || _clock() >= clients.ExpiresAt) - { - await _mutex.WaitAsync(cancellationToken); + private async Task GetAsync(Func clientFactory, CancellationToken cancellationToken) + { + var clients = _clients; - try - { - // Another caller may have refreshed the service index while this one waited. - if (_clients == null || _clock() >= _clients.ExpiresAt) - { - _clients = await BuildClientsAsync(cancellationToken); - } + if (clients == null || _clock() >= clients.ExpiresAt) + { + await _mutex.WaitAsync(cancellationToken); - clients = _clients; - } - finally + try + { + // Another caller may have refreshed the service index while this one waited. + if (_clients == null || _clock() >= _clients.ExpiresAt) { - _mutex.Release(); + _clients = await BuildClientsAsync(cancellationToken); } - } - return clientFactory(clients); + clients = _clients; + } + finally + { + _mutex.Release(); + } } - private async Task BuildClientsAsync(CancellationToken cancellationToken) - { - var serviceIndexClient = new RawServiceIndexClient(_httpClient, _serviceIndexUrl); - - var serviceIndex = await serviceIndexClient.GetAsync(cancellationToken); + return clientFactory(clients); + } - var contentResourceUrl = serviceIndex.GetPackageContentResourceUrl(); - var metadataResourceUrl = serviceIndex.GetPackageMetadataResourceUrl(); - var catalogResourceUrl = serviceIndex.GetCatalogResourceUrl(); + private async Task BuildClientsAsync(CancellationToken cancellationToken) + { + var serviceIndexClient = new RawServiceIndexClient(_httpClient, _serviceIndexUrl); + + var serviceIndex = await serviceIndexClient.GetAsync(cancellationToken); + + var contentResourceUrl = serviceIndex.GetPackageContentResourceUrl(); + var metadataResourceUrl = serviceIndex.GetPackageMetadataResourceUrl(); + var catalogResourceUrl = serviceIndex.GetCatalogResourceUrl(); + + // The service index may advertise several endpoints for the search and autocomplete + // resources. Keep one client per endpoint, in the order they should be tried. + var searchResourceUrls = serviceIndex.GetSearchQueryResourceUrls(); + var autocompleteResourceUrls = serviceIndex.GetSearchAutocompleteResourceUrls(); + + // Create clients for required resources. + var contentClient = new RawPackageContentClient(_httpClient, contentResourceUrl); + var metadataClient = new RawPackageMetadataClient(_httpClient, metadataResourceUrl); + var searchClients = searchResourceUrls + .Select(url => (ISearchClient)new RawSearchClient(_httpClient, url)) + .ToList(); + + // Create clients for optional resources. + var catalogClient = catalogResourceUrl == null + ? new NullCatalogClient() as ICatalogClient + : new RawCatalogClient(_httpClient, catalogResourceUrl); + var autocompleteClients = autocompleteResourceUrls.Count == 0 + ? new List { new NullAutocompleteClient() } + : autocompleteResourceUrls + .Select(url => (IAutocompleteClient)new RawAutocompleteClient(_httpClient, url)) + .ToList(); - // The service index may advertise several endpoints for the search and autocomplete - // resources. Keep one client per endpoint, in the order they should be tried. - var searchResourceUrls = serviceIndex.GetSearchQueryResourceUrls(); - var autocompleteResourceUrls = serviceIndex.GetSearchAutocompleteResourceUrls(); + return new NuGetClients + { + ServiceIndex = serviceIndex, + ExpiresAt = _clock() + _serviceIndexCacheDuration, + + PackageContentClient = contentClient, + PackageMetadataClient = metadataClient, + SearchClients = searchClients, + AutocompleteClients = autocompleteClients, + CatalogClient = catalogClient, + }; + } - // Create clients for required resources. - var contentClient = new RawPackageContentClient(_httpClient, contentResourceUrl); - var metadataClient = new RawPackageMetadataClient(_httpClient, metadataResourceUrl); - var searchClients = searchResourceUrls - .Select(url => (ISearchClient)new RawSearchClient(_httpClient, url)) - .ToList(); + private class NuGetClients + { + public ServiceIndexResponse ServiceIndex { get; set; } - // Create clients for optional resources. - var catalogClient = catalogResourceUrl == null - ? new NullCatalogClient() as ICatalogClient - : new RawCatalogClient(_httpClient, catalogResourceUrl); - var autocompleteClients = autocompleteResourceUrls.Count == 0 - ? new List { new NullAutocompleteClient() } - : autocompleteResourceUrls - .Select(url => (IAutocompleteClient)new RawAutocompleteClient(_httpClient, url)) - .ToList(); - - return new NuGetClients - { - ServiceIndex = serviceIndex, - ExpiresAt = _clock() + _serviceIndexCacheDuration, - - PackageContentClient = contentClient, - PackageMetadataClient = metadataClient, - SearchClients = searchClients, - AutocompleteClients = autocompleteClients, - CatalogClient = catalogClient, - }; - } + /// + /// When these clients stop being used, and the service index is fetched again. + /// It lives on the snapshot so that reading it needs no synchronization. + /// + public DateTimeOffset ExpiresAt { get; set; } - private class NuGetClients - { - public ServiceIndexResponse ServiceIndex { get; set; } - - /// - /// When these clients stop being used, and the service index is fetched again. - /// It lives on the snapshot so that reading it needs no synchronization. - /// - public DateTimeOffset ExpiresAt { get; set; } - - public IPackageContentClient PackageContentClient { get; set; } - public IPackageMetadataClient PackageMetadataClient { get; set; } - public IReadOnlyList SearchClients { get; set; } - public IReadOnlyList AutocompleteClients { get; set; } - public ICatalogClient CatalogClient { get; set; } - } + public IPackageContentClient PackageContentClient { get; set; } + public IPackageMetadataClient PackageMetadataClient { get; set; } + public IReadOnlyList SearchClients { get; set; } + public IReadOnlyList AutocompleteClients { get; set; } + public ICatalogClient CatalogClient { get; set; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageContent/IPackageContentClient.cs b/src/BaGet.Protocol/PackageContent/IPackageContentClient.cs index 33422254c..191da95ea 100644 --- a/src/BaGet.Protocol/PackageContent/IPackageContentClient.cs +++ b/src/BaGet.Protocol/PackageContent/IPackageContentClient.cs @@ -4,54 +4,53 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The Package Content resource, used to download NuGet packages and to fetch other metadata. +/// +/// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource +/// +public interface IPackageContentClient { /// - /// The Package Content resource, used to download NuGet packages and to fetch other metadata. - /// - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource + /// Get a package's versions, or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions /// - public interface IPackageContentClient - { - /// - /// Get a package's versions, or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#enumerate-package-versions - /// - /// The package ID. - /// A token to cancel the task. - /// The package's versions, or null if the package does not exist. - Task GetPackageVersionsOrNullAsync( - string packageId, - CancellationToken cancellationToken = default); + /// The package ID. + /// A token to cancel the task. + /// The package's versions, or null if the package does not exist. + Task GetPackageVersionsOrNullAsync( + string packageId, + CancellationToken cancellationToken = default); - /// - /// Download a package, or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg - /// - /// The package ID. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's content stream, or null if the package does not exist. The stream may not be seekable. - /// - Task DownloadPackageOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default); + /// + /// Download a package, or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-content-nupkg + /// + /// The package ID. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's content stream, or null if the package does not exist. The stream may not be seekable. + /// + Task DownloadPackageOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default); - /// - /// Download a package's manifest (nuspec), or null if the package does not exist. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec - /// - /// The package id. - /// The package's version. - /// A token to cancel the task. - /// - /// The package's manifest stream, or null if the package does not exist. The stream may not be seekable. - /// - Task DownloadPackageManifestOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default); - } -} + /// + /// Download a package's manifest (nuspec), or null if the package does not exist. + /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource#download-package-manifest-nuspec + /// + /// The package id. + /// The package's version. + /// A token to cancel the task. + /// + /// The package's manifest stream, or null if the package does not exist. The stream may not be seekable. + /// + Task DownloadPackageManifestOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageContent/PackageContentClient.cs b/src/BaGet.Protocol/PackageContent/PackageContentClient.cs index a42c00fd2..6bad5b916 100644 --- a/src/BaGet.Protocol/PackageContent/PackageContentClient.cs +++ b/src/BaGet.Protocol/PackageContent/PackageContentClient.cs @@ -5,47 +5,46 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class PackageContentClient : IPackageContentClient { - private class PackageContentClient : IPackageContentClient + private readonly NuGetClientFactory _clientfactory; + + public PackageContentClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } + + public async Task DownloadPackageOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); + + return await client.DownloadPackageOrNullAsync(packageId, packageVersion, cancellationToken); + } + + public async Task DownloadPackageManifestOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) { - private readonly NuGetClientFactory _clientfactory; - - public PackageContentClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } - - public async Task DownloadPackageOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); - - return await client.DownloadPackageOrNullAsync(packageId, packageVersion, cancellationToken); - } - - public async Task DownloadPackageManifestOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); - - return await client.DownloadPackageManifestOrNullAsync(packageId, packageVersion, cancellationToken); - } - - public async Task GetPackageVersionsOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); - - return await client.GetPackageVersionsOrNullAsync(packageId, cancellationToken); - } + var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); + + return await client.DownloadPackageManifestOrNullAsync(packageId, packageVersion, cancellationToken); + } + + public async Task GetPackageVersionsOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetPackageContentClientAsync(cancellationToken); + + return await client.GetPackageVersionsOrNullAsync(packageId, cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageContent/RawPackageContentClient.cs b/src/BaGet.Protocol/PackageContent/RawPackageContentClient.cs index 1d172844f..e931443f7 100644 --- a/src/BaGet.Protocol/PackageContent/RawPackageContentClient.cs +++ b/src/BaGet.Protocol/PackageContent/RawPackageContentClient.cs @@ -7,79 +7,78 @@ using BaGet.Protocol.Models; using NuGet.Versioning; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The client to interact with an upstream source's Package Content resource. +/// +public class RawPackageContentClient : IPackageContentClient { + private readonly HttpClient _httpClient; + private readonly string _packageContentUrl; + /// - /// The client to interact with an upstream source's Package Content resource. + /// Create a new Package Content client. /// - public class RawPackageContentClient : IPackageContentClient + /// The HTTP client used to send requests. + /// The NuGet Server's package content URL. + public RawPackageContentClient(HttpClient httpClient, string packageContentUrl) { - private readonly HttpClient _httpClient; - private readonly string _packageContentUrl; - - /// - /// Create a new Package Content client. - /// - /// The HTTP client used to send requests. - /// The NuGet Server's package content URL. - public RawPackageContentClient(HttpClient httpClient, string packageContentUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _packageContentUrl = packageContentUrl?.TrimEnd('/') - ?? throw new ArgumentNullException(nameof(packageContentUrl)); - } - - /// - public async Task GetPackageVersionsOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var id = packageId.ToLowerInvariant(); - var url = $"{_packageContentUrl}/{id}/index.json"; + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _packageContentUrl = packageContentUrl?.TrimEnd('/') + ?? throw new ArgumentNullException(nameof(packageContentUrl)); + } - return await _httpClient.GetFromJsonOrDefaultAsync(url, cancellationToken); - } + /// + public async Task GetPackageVersionsOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var id = packageId.ToLowerInvariant(); + var url = $"{_packageContentUrl}/{id}/index.json"; - /// - public async Task DownloadPackageOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) - { - var id = packageId.ToLowerInvariant(); - var version = packageVersion.ToNormalizedString().ToLowerInvariant(); + return await _httpClient.GetFromJsonOrDefaultAsync(url, cancellationToken); + } - // The response will be disposed when the returned content stream is disposed. - var url = $"{_packageContentUrl}/{id}/{version}/{id}.{version}.nupkg"; - var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + /// + public async Task DownloadPackageOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + var id = packageId.ToLowerInvariant(); + var version = packageVersion.ToNormalizedString().ToLowerInvariant(); - if (response.StatusCode == HttpStatusCode.NotFound) - { - return null; - } + // The response will be disposed when the returned content stream is disposed. + var url = $"{_packageContentUrl}/{id}/{version}/{id}.{version}.nupkg"; + var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); - return await response.Content.ReadAsStreamAsync(); + if (response.StatusCode == HttpStatusCode.NotFound) + { + return null; } - /// - public async Task DownloadPackageManifestOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken = default) - { - var id = packageId.ToLowerInvariant(); - var version = packageVersion.ToNormalizedString().ToLowerInvariant(); + return await response.Content.ReadAsStreamAsync(); + } - // The response will be disposed when the returned content stream is disposed. - var url = $"{_packageContentUrl}/{id}/{version}/{id}.nuspec"; - var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + /// + public async Task DownloadPackageManifestOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken = default) + { + var id = packageId.ToLowerInvariant(); + var version = packageVersion.ToNormalizedString().ToLowerInvariant(); - if (response.StatusCode == HttpStatusCode.NotFound) - { - return null; - } + // The response will be disposed when the returned content stream is disposed. + var url = $"{_packageContentUrl}/{id}/{version}/{id}.nuspec"; + var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); - return await response.Content.ReadAsStreamAsync(); + if (response.StatusCode == HttpStatusCode.NotFound) + { + return null; } + + return await response.Content.ReadAsStreamAsync(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageMetadata/IPackageMetadataClient.cs b/src/BaGet.Protocol/PackageMetadata/IPackageMetadataClient.cs index fb3e06f86..51b514604 100644 --- a/src/BaGet.Protocol/PackageMetadata/IPackageMetadataClient.cs +++ b/src/BaGet.Protocol/PackageMetadata/IPackageMetadataClient.cs @@ -2,43 +2,42 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The Package Metadata client, used to fetch packages' metadata. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource +/// +public interface IPackageMetadataClient { /// - /// The Package Metadata client, used to fetch packages' metadata. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource + /// Attempt to get a package's registration index, if it exists. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page /// - public interface IPackageMetadataClient - { - /// - /// Attempt to get a package's registration index, if it exists. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - /// The package's ID. - /// A token to cancel the task. - /// The package's registration index, or null if the package does not exist - Task GetRegistrationIndexOrNullAsync(string packageId, CancellationToken cancellationToken = default); + /// The package's ID. + /// A token to cancel the task. + /// The package's registration index, or null if the package does not exist + Task GetRegistrationIndexOrNullAsync(string packageId, CancellationToken cancellationToken = default); - /// - /// Get a page that was linked from the package's registration index. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page - /// - /// The URL of the page, from the . - /// A token to cancel the task. - /// The registration index page. - Task GetRegistrationPageAsync( - string pageUrl, - CancellationToken cancellationToken = default); + /// + /// Get a page that was linked from the package's registration index. + /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource#registration-page + /// + /// The URL of the page, from the . + /// A token to cancel the task. + /// The registration index page. + Task GetRegistrationPageAsync( + string pageUrl, + CancellationToken cancellationToken = default); - /// - /// Get the metadata for a single package version. - /// - /// The URL of the leaf, from the . - /// A token to cancel the task. - /// The registration leaf. - Task GetRegistrationLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default); - } -} + /// + /// Get the metadata for a single package version. + /// + /// The URL of the leaf, from the . + /// A token to cancel the task. + /// The registration leaf. + Task GetRegistrationLeafAsync( + string leafUrl, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageMetadata/PackageMetadataClient.cs b/src/BaGet.Protocol/PackageMetadata/PackageMetadataClient.cs index 9d338bc23..56abc9119 100644 --- a/src/BaGet.Protocol/PackageMetadata/PackageMetadataClient.cs +++ b/src/BaGet.Protocol/PackageMetadata/PackageMetadataClient.cs @@ -3,45 +3,44 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class PackageMetadataClient : IPackageMetadataClient { - private class PackageMetadataClient : IPackageMetadataClient + private readonly NuGetClientFactory _clientfactory; + + public PackageMetadataClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } + + public async Task GetRegistrationIndexOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); + + return await client.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); + } + + public async Task GetRegistrationPageAsync( + string pageUrl, + CancellationToken cancellationToken = default) { - private readonly NuGetClientFactory _clientfactory; - - public PackageMetadataClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } - - public async Task GetRegistrationIndexOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); - - return await client.GetRegistrationIndexOrNullAsync(packageId, cancellationToken); - } - - public async Task GetRegistrationPageAsync( - string pageUrl, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); - - return await client.GetRegistrationPageAsync(pageUrl, cancellationToken); - } - - public async Task GetRegistrationLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default) - { - var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); - - return await client.GetRegistrationLeafAsync(leafUrl, cancellationToken); - } + var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); + + return await client.GetRegistrationPageAsync(pageUrl, cancellationToken); + } + + public async Task GetRegistrationLeafAsync( + string leafUrl, + CancellationToken cancellationToken = default) + { + var client = await _clientfactory.GetPackageMetadataClientAsync(cancellationToken); + + return await client.GetRegistrationLeafAsync(leafUrl, cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/PackageMetadata/RawPackageMetadataClient.cs b/src/BaGet.Protocol/PackageMetadata/RawPackageMetadataClient.cs index 75f7071f9..66aacc02f 100644 --- a/src/BaGet.Protocol/PackageMetadata/RawPackageMetadataClient.cs +++ b/src/BaGet.Protocol/PackageMetadata/RawPackageMetadataClient.cs @@ -4,51 +4,50 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The client to interact with an upstream source's Package Metadata resource. +/// +public class RawPackageMetadataClient : IPackageMetadataClient { + private readonly HttpClient _httpClient; + private readonly string _packageMetadataUrl; + /// - /// The client to interact with an upstream source's Package Metadata resource. + /// Create a new Package Metadata client. /// - public class RawPackageMetadataClient : IPackageMetadataClient + /// The HTTP client used to send requests. + /// The NuGet server's registration resource URL. + public RawPackageMetadataClient(HttpClient httpClient, string registrationBaseUrl) { - private readonly HttpClient _httpClient; - private readonly string _packageMetadataUrl; - - /// - /// Create a new Package Metadata client. - /// - /// The HTTP client used to send requests. - /// The NuGet server's registration resource URL. - public RawPackageMetadataClient(HttpClient httpClient, string registrationBaseUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _packageMetadataUrl = registrationBaseUrl ?? throw new ArgumentNullException(nameof(registrationBaseUrl)); - } + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _packageMetadataUrl = registrationBaseUrl ?? throw new ArgumentNullException(nameof(registrationBaseUrl)); + } - /// - public async Task GetRegistrationIndexOrNullAsync( - string packageId, - CancellationToken cancellationToken = default) - { - var url = $"{_packageMetadataUrl}/{packageId.ToLowerInvariant()}/index.json"; + /// + public async Task GetRegistrationIndexOrNullAsync( + string packageId, + CancellationToken cancellationToken = default) + { + var url = $"{_packageMetadataUrl}/{packageId.ToLowerInvariant()}/index.json"; - return await _httpClient.GetFromJsonOrDefaultAsync(url, cancellationToken); - } + return await _httpClient.GetFromJsonOrDefaultAsync(url, cancellationToken); + } - /// - public async Task GetRegistrationPageAsync( - string pageUrl, - CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync(pageUrl, cancellationToken); - } + /// + public async Task GetRegistrationPageAsync( + string pageUrl, + CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync(pageUrl, cancellationToken); + } - /// - public async Task GetRegistrationLeafAsync( - string leafUrl, - CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync(leafUrl, cancellationToken); - } + /// + public async Task GetRegistrationLeafAsync( + string leafUrl, + CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync(leafUrl, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/AutocompleteClient.cs b/src/BaGet.Protocol/Search/AutocompleteClient.cs index 93dc1ede8..f80a8b162 100644 --- a/src/BaGet.Protocol/Search/AutocompleteClient.cs +++ b/src/BaGet.Protocol/Search/AutocompleteClient.cs @@ -4,52 +4,51 @@ using BaGet.Protocol.Internal; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class AutocompleteClient : IAutocompleteClient { - private class AutocompleteClient : IAutocompleteClient - { - private readonly NuGetClientFactory _clientfactory; + private readonly NuGetClientFactory _clientfactory; - public AutocompleteClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } + public AutocompleteClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } - public async Task AutocompleteAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - // The service index may advertise several autocomplete endpoints. Try them in order. - // See: https://github.com/loic-sharma/BaGet/issues/314 - var clients = await _clientfactory.GetAutocompleteClientsAsync(cancellationToken); + public async Task AutocompleteAsync( + string query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + // The service index may advertise several autocomplete endpoints. Try them in order. + // See: https://github.com/loic-sharma/BaGet/issues/314 + var clients = await _clientfactory.GetAutocompleteClientsAsync(cancellationToken); - return await EndpointFailover.ExecuteAsync( - clients, - (client, token) => client.AutocompleteAsync(query, skip, take, includePrerelease, includeSemVer2, token), - cancellationToken); - } + return await EndpointFailover.ExecuteAsync( + clients, + (client, token) => client.AutocompleteAsync(query, skip, take, includePrerelease, includeSemVer2, token), + cancellationToken); + } - public async Task ListPackageVersionsAsync( - string packageId, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - // The service index may advertise several autocomplete endpoints. Try them in order. - // See: https://github.com/loic-sharma/BaGet/issues/314 - var clients = await _clientfactory.GetAutocompleteClientsAsync(cancellationToken); + public async Task ListPackageVersionsAsync( + string packageId, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + // The service index may advertise several autocomplete endpoints. Try them in order. + // See: https://github.com/loic-sharma/BaGet/issues/314 + var clients = await _clientfactory.GetAutocompleteClientsAsync(cancellationToken); - return await EndpointFailover.ExecuteAsync( - clients, - (client, token) => client.ListPackageVersionsAsync(packageId, includePrerelease, includeSemVer2, token), - cancellationToken); - } + return await EndpointFailover.ExecuteAsync( + clients, + (client, token) => client.ListPackageVersionsAsync(packageId, includePrerelease, includeSemVer2, token), + cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/IAutocompleteClient.cs b/src/BaGet.Protocol/Search/IAutocompleteClient.cs index 5afbb4a5d..003ea2e5d 100644 --- a/src/BaGet.Protocol/Search/IAutocompleteClient.cs +++ b/src/BaGet.Protocol/Search/IAutocompleteClient.cs @@ -2,47 +2,46 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The client used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource +/// +public interface IAutocompleteClient { /// - /// The client used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource + /// Perform an autocomplete query on package IDs. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids /// - public interface IAutocompleteClient - { - /// - /// Perform an autocomplete query on package IDs. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#search-for-package-ids - /// - /// The autocomplete query. - /// How many results to skip. - /// How many results to return. - /// Whether pre-release packages should be returned. - /// Whether packages that require SemVer 2.0.0 compatibility should be returned. - /// A token to cancel the task. - /// The autocomplete response. - Task AutocompleteAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default); + /// The autocomplete query. + /// How many results to skip. + /// How many results to return. + /// Whether pre-release packages should be returned. + /// Whether packages that require SemVer 2.0.0 compatibility should be returned. + /// A token to cancel the task. + /// The autocomplete response. + Task AutocompleteAsync( + string query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default); - /// - /// Enumerate listed package versions. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#enumerate-package-versions - /// - /// The package ID. - /// Whether pre-release packages should be returned. - /// Whether packages that require SemVer 2.0.0 compatibility should be returned. - /// A token to cancel the task. - /// The package versions that matched the request. - Task ListPackageVersionsAsync( - string packageId, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default); - } -} + /// + /// Enumerate listed package versions. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource#enumerate-package-versions + /// + /// The package ID. + /// Whether pre-release packages should be returned. + /// Whether packages that require SemVer 2.0.0 compatibility should be returned. + /// A token to cancel the task. + /// The package versions that matched the request. + Task ListPackageVersionsAsync( + string packageId, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/ISearchClient.cs b/src/BaGet.Protocol/Search/ISearchClient.cs index 6b21029b0..6d0bbd8f7 100644 --- a/src/BaGet.Protocol/Search/ISearchClient.cs +++ b/src/BaGet.Protocol/Search/ISearchClient.cs @@ -2,32 +2,31 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The client used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource +/// +public interface ISearchClient { /// - /// The client used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// Perform a search query. + /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages /// - public interface ISearchClient - { - /// - /// Perform a search query. - /// See: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource#search-for-packages - /// - /// The search query. - /// How many results to skip. - /// How many results to return. - /// Whether pre-release packages should be returned. - /// Whether packages that require SemVer 2.0.0 compatibility should be returned. - /// A token to cancel the task. - /// The search response. - Task SearchAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default); - } -} + /// The search query. + /// How many results to skip. + /// How many results to return. + /// Whether pre-release packages should be returned. + /// Whether packages that require SemVer 2.0.0 compatibility should be returned. + /// A token to cancel the task. + /// The search response. + Task SearchAsync( + string query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/NullAutocompleteClient.cs b/src/BaGet.Protocol/Search/NullAutocompleteClient.cs index 326193880..f7022d1de 100644 --- a/src/BaGet.Protocol/Search/NullAutocompleteClient.cs +++ b/src/BaGet.Protocol/Search/NullAutocompleteClient.cs @@ -3,26 +3,25 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +public class NullAutocompleteClient : IAutocompleteClient { - public class NullAutocompleteClient : IAutocompleteClient + public Task AutocompleteAsync(string query = null, int skip = 0, int take = 20, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) { - public Task AutocompleteAsync(string query = null, int skip = 0, int take = 20, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) + return Task.FromResult(new AutocompleteResponse { - return Task.FromResult(new AutocompleteResponse - { - TotalHits = 0, - Data = new List() - }); - } + TotalHits = 0, + Data = new List() + }); + } - public Task ListPackageVersionsAsync(string packageId, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) + public Task ListPackageVersionsAsync(string packageId, bool includePrerelease = true, bool includeSemVer2 = true, CancellationToken cancellationToken = default) + { + return Task.FromResult(new AutocompleteResponse { - return Task.FromResult(new AutocompleteResponse - { - TotalHits = 0, - Data = new List() - }); - } + TotalHits = 0, + Data = new List() + }); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/RawAutocompleteClient.cs b/src/BaGet.Protocol/Search/RawAutocompleteClient.cs index 26f63be00..f650dbbb3 100644 --- a/src/BaGet.Protocol/Search/RawAutocompleteClient.cs +++ b/src/BaGet.Protocol/Search/RawAutocompleteClient.cs @@ -4,65 +4,64 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The client used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource +/// +public class RawAutocompleteClient : IAutocompleteClient { + private readonly HttpClient _httpClient; + private readonly string _autocompleteUrl; + /// - /// The client used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-autocomplete-service-resource + /// Create a new Search client. /// - public class RawAutocompleteClient : IAutocompleteClient + /// The HTTP client used to send requests. + /// The NuGet server's autocomplete URL. + public RawAutocompleteClient(HttpClient httpClient, string autocompleteUrl) { - private readonly HttpClient _httpClient; - private readonly string _autocompleteUrl; - - /// - /// Create a new Search client. - /// - /// The HTTP client used to send requests. - /// The NuGet server's autocomplete URL. - public RawAutocompleteClient(HttpClient httpClient, string autocompleteUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _autocompleteUrl = autocompleteUrl ?? throw new ArgumentNullException(nameof(autocompleteUrl)); - } + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _autocompleteUrl = autocompleteUrl ?? throw new ArgumentNullException(nameof(autocompleteUrl)); + } - public async Task AutocompleteAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - var url = RawSearchClient.AddSearchQueryString( - _autocompleteUrl, - query, - skip, - take, - includePrerelease, - includeSemVer2, - "q"); + public async Task AutocompleteAsync( + string query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + var url = RawSearchClient.AddSearchQueryString( + _autocompleteUrl, + query, + skip, + take, + includePrerelease, + includeSemVer2, + "q"); - return await _httpClient.GetFromJsonAsync(url, cancellationToken); - } + return await _httpClient.GetFromJsonAsync(url, cancellationToken); + } - public async Task ListPackageVersionsAsync( - string packageId, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - var url = RawSearchClient.AddSearchQueryString( - _autocompleteUrl, - packageId, - skip: null, - take: null, - includePrerelease, - includeSemVer2, - "id"); + public async Task ListPackageVersionsAsync( + string packageId, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + var url = RawSearchClient.AddSearchQueryString( + _autocompleteUrl, + packageId, + skip: null, + take: null, + includePrerelease, + includeSemVer2, + "id"); - return await _httpClient.GetFromJsonAsync(url, cancellationToken); - } + return await _httpClient.GetFromJsonAsync(url, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/RawSearchClient.cs b/src/BaGet.Protocol/Search/RawSearchClient.cs index 914b08b41..1950b750c 100644 --- a/src/BaGet.Protocol/Search/RawSearchClient.cs +++ b/src/BaGet.Protocol/Search/RawSearchClient.cs @@ -6,85 +6,84 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The client used to search for packages. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource +/// +public class RawSearchClient : ISearchClient { + private readonly HttpClient _httpClient; + private readonly string _searchUrl; + /// - /// The client used to search for packages. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource + /// Create a new Search client. /// - public class RawSearchClient : ISearchClient + /// The HTTP client used to send requests. + /// The NuGet server's search URL. + public RawSearchClient(HttpClient httpClient, string searchUrl) { - private readonly HttpClient _httpClient; - private readonly string _searchUrl; - - /// - /// Create a new Search client. - /// - /// The HTTP client used to send requests. - /// The NuGet server's search URL. - public RawSearchClient(HttpClient httpClient, string searchUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _searchUrl = searchUrl ?? throw new ArgumentNullException(nameof(searchUrl)); - } - - public async Task SearchAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - var url = AddSearchQueryString(_searchUrl, query, skip, take, includePrerelease, includeSemVer2, "q"); + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _searchUrl = searchUrl ?? throw new ArgumentNullException(nameof(searchUrl)); + } - return await _httpClient.GetFromJsonAsync(url, cancellationToken); - } + public async Task SearchAsync( + string query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + var url = AddSearchQueryString(_searchUrl, query, skip, take, includePrerelease, includeSemVer2, "q"); - internal static string AddSearchQueryString( - string uri, - string query, - int? skip, - int? take, - bool includePrerelease, - bool includeSemVer2, - string queryParamName) - { - var queryString = new Dictionary(); + return await _httpClient.GetFromJsonAsync(url, cancellationToken); + } - if (skip.HasValue && skip.Value > 0) queryString["skip"] = skip.ToString(); - if (take.HasValue) queryString["take"] = take.ToString(); - if (includePrerelease) queryString["prerelease"] = true.ToString(); - if (includeSemVer2) queryString["semVerLevel"] = "2.0.0"; + internal static string AddSearchQueryString( + string uri, + string query, + int? skip, + int? take, + bool includePrerelease, + bool includeSemVer2, + string queryParamName) + { + var queryString = new Dictionary(); - if (!string.IsNullOrEmpty(query)) - { - queryString[queryParamName] = query; - } + if (skip.HasValue && skip.Value > 0) queryString["skip"] = skip.ToString(); + if (take.HasValue) queryString["take"] = take.ToString(); + if (includePrerelease) queryString["prerelease"] = true.ToString(); + if (includeSemVer2) queryString["semVerLevel"] = "2.0.0"; - return AddQueryString(uri, queryString); + if (!string.IsNullOrEmpty(query)) + { + queryString[queryParamName] = query; } - // See: https://github.com/aspnet/AspNetCore/blob/8c02467b4a218df3b1b0a69bceb50f5b64f482b1/src/Http/WebUtilities/src/QueryHelpers.cs#L63 - private static string AddQueryString(string uri, Dictionary queryString) - { - if (uri.IndexOf('#') != -1) throw new InvalidOperationException("URL anchors are not supported"); - if (uri.IndexOf('?') != -1) throw new InvalidOperationException("Adding query strings to URL with query strings is not supported"); + return AddQueryString(uri, queryString); + } - var builder = new StringBuilder(uri); - var hasQuery = false; + // See: https://github.com/aspnet/AspNetCore/blob/8c02467b4a218df3b1b0a69bceb50f5b64f482b1/src/Http/WebUtilities/src/QueryHelpers.cs#L63 + private static string AddQueryString(string uri, Dictionary queryString) + { + if (uri.IndexOf('#') != -1) throw new InvalidOperationException("URL anchors are not supported"); + if (uri.IndexOf('?') != -1) throw new InvalidOperationException("Adding query strings to URL with query strings is not supported"); - foreach (var parameter in queryString) - { - builder.Append(hasQuery ? '&' : '?'); - builder.Append(Uri.EscapeDataString(parameter.Key)); - builder.Append('='); - builder.Append(Uri.EscapeDataString(parameter.Value)); - hasQuery = true; - } + var builder = new StringBuilder(uri); + var hasQuery = false; - return builder.ToString(); + foreach (var parameter in queryString) + { + builder.Append(hasQuery ? '&' : '?'); + builder.Append(Uri.EscapeDataString(parameter.Key)); + builder.Append('='); + builder.Append(Uri.EscapeDataString(parameter.Value)); + hasQuery = true; } + + return builder.ToString(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/Search/SearchClient.cs b/src/BaGet.Protocol/Search/SearchClient.cs index 1379e26a4..9b792c04d 100644 --- a/src/BaGet.Protocol/Search/SearchClient.cs +++ b/src/BaGet.Protocol/Search/SearchClient.cs @@ -4,36 +4,35 @@ using BaGet.Protocol.Internal; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class SearchClient : ISearchClient { - private class SearchClient : ISearchClient - { - private readonly NuGetClientFactory _clientfactory; + private readonly NuGetClientFactory _clientfactory; - public SearchClient(NuGetClientFactory clientFactory) - { - _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } + public SearchClient(NuGetClientFactory clientFactory) + { + _clientfactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } - public async Task SearchAsync( - string query = null, - int skip = 0, - int take = 20, - bool includePrerelease = true, - bool includeSemVer2 = true, - CancellationToken cancellationToken = default) - { - // The service index may advertise several search endpoints. Try them in order. - // See: https://github.com/loic-sharma/BaGet/issues/314 - var clients = await _clientfactory.GetSearchClientsAsync(cancellationToken); + public async Task SearchAsync( + string query = null, + int skip = 0, + int take = 20, + bool includePrerelease = true, + bool includeSemVer2 = true, + CancellationToken cancellationToken = default) + { + // The service index may advertise several search endpoints. Try them in order. + // See: https://github.com/loic-sharma/BaGet/issues/314 + var clients = await _clientfactory.GetSearchClientsAsync(cancellationToken); - return await EndpointFailover.ExecuteAsync( - clients, - (client, token) => client.SearchAsync(query, skip, take, includePrerelease, includeSemVer2, token), - cancellationToken); - } + return await EndpointFailover.ExecuteAsync( + clients, + (client, token) => client.SearchAsync(query, skip, take, includePrerelease, includeSemVer2, token), + cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/ServiceIndex/IServiceIndexClient.cs b/src/BaGet.Protocol/ServiceIndex/IServiceIndexClient.cs index 73fc2cfbc..56ecd021b 100644 --- a/src/BaGet.Protocol/ServiceIndex/IServiceIndexClient.cs +++ b/src/BaGet.Protocol/ServiceIndex/IServiceIndexClient.cs @@ -2,20 +2,19 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +/// +/// The NuGet Service Index client, used to discover other resources. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/service-index +/// +public interface IServiceIndexClient { /// - /// The NuGet Service Index client, used to discover other resources. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index + /// Get the resources available on this package feed. + /// See: https://docs.microsoft.com/en-us/nuget/api/service-index#resources /// - public interface IServiceIndexClient - { - /// - /// Get the resources available on this package feed. - /// See: https://docs.microsoft.com/en-us/nuget/api/service-index#resources - /// - /// The resources available on this package feed. - Task GetAsync(CancellationToken cancellationToken = default); - } -} + /// The resources available on this package feed. + Task GetAsync(CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/BaGet.Protocol/ServiceIndex/RawServiceIndexClient.cs b/src/BaGet.Protocol/ServiceIndex/RawServiceIndexClient.cs index 70d85669c..46151ec28 100644 --- a/src/BaGet.Protocol/ServiceIndex/RawServiceIndexClient.cs +++ b/src/BaGet.Protocol/ServiceIndex/RawServiceIndexClient.cs @@ -4,35 +4,34 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol.Internal +namespace BaGet.Protocol.Internal; + +/// +/// The NuGet Service Index client, used to discover other resources. +/// +/// See https://docs.microsoft.com/en-us/nuget/api/service-index +/// +public class RawServiceIndexClient : IServiceIndexClient { + private readonly HttpClient _httpClient; + private readonly string _serviceIndexUrl; + /// - /// The NuGet Service Index client, used to discover other resources. - /// - /// See https://docs.microsoft.com/en-us/nuget/api/service-index + /// Create a service index for the upstream source. /// - public class RawServiceIndexClient : IServiceIndexClient + /// The HTTP client used to send requests. + /// The NuGet server's service index URL. + public RawServiceIndexClient(HttpClient httpClient, string serviceIndexUrl) { - private readonly HttpClient _httpClient; - private readonly string _serviceIndexUrl; - - /// - /// Create a service index for the upstream source. - /// - /// The HTTP client used to send requests. - /// The NuGet server's service index URL. - public RawServiceIndexClient(HttpClient httpClient, string serviceIndexUrl) - { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - _serviceIndexUrl = serviceIndexUrl ?? throw new ArgumentNullException(nameof(serviceIndexUrl)); - } + _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); + _serviceIndexUrl = serviceIndexUrl ?? throw new ArgumentNullException(nameof(serviceIndexUrl)); + } - /// - public async Task GetAsync(CancellationToken cancellationToken = default) - { - return await _httpClient.GetFromJsonAsync( - _serviceIndexUrl, - cancellationToken); - } + /// + public async Task GetAsync(CancellationToken cancellationToken = default) + { + return await _httpClient.GetFromJsonAsync( + _serviceIndexUrl, + cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Protocol/ServiceIndex/ServiceIndexClient.cs b/src/BaGet.Protocol/ServiceIndex/ServiceIndexClient.cs index a429b60f6..408634a8d 100644 --- a/src/BaGet.Protocol/ServiceIndex/ServiceIndexClient.cs +++ b/src/BaGet.Protocol/ServiceIndex/ServiceIndexClient.cs @@ -3,23 +3,22 @@ using System.Threading.Tasks; using BaGet.Protocol.Models; -namespace BaGet.Protocol +namespace BaGet.Protocol; + +public partial class NuGetClientFactory { - public partial class NuGetClientFactory + private class ServiceIndexClient : IServiceIndexClient { - private class ServiceIndexClient : IServiceIndexClient - { - private readonly NuGetClientFactory _clientFactory; + private readonly NuGetClientFactory _clientFactory; - public ServiceIndexClient(NuGetClientFactory clientFactory) - { - _clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); - } + public ServiceIndexClient(NuGetClientFactory clientFactory) + { + _clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory)); + } - public async Task GetAsync(CancellationToken cancellationToken = default) - { - return await _clientFactory.GetServiceIndexAsync(cancellationToken); - } + public async Task GetAsync(CancellationToken cancellationToken = default) + { + return await _clientFactory.GetServiceIndexAsync(cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Validation/IPackageValidator.cs b/src/BaGet.Validation/IPackageValidator.cs index 6fddeb251..9dbb0815f 100644 --- a/src/BaGet.Validation/IPackageValidator.cs +++ b/src/BaGet.Validation/IPackageValidator.cs @@ -5,65 +5,64 @@ using NuGet.Packaging; using NuGet.Versioning; -namespace BaGet.Validation +namespace BaGet.Validation; + +/// +/// Decides whether a pushed package may be served. Register any number, for example a +/// malware scanner; every one must pass. A validator that throws fails the package. +/// +public interface IPackageValidator { /// - /// Decides whether a pushed package may be served. Register any number, for example a - /// malware scanner; every one must pass. A validator that throws fails the package. + /// Recorded as the validation step's type, so it must be stable and unique. /// - public interface IPackageValidator - { - /// - /// Recorded as the validation step's type, so it must be stable and unique. - /// - string Name { get; } + string Name { get; } - Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken); - } + Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken); +} - public sealed class PackageValidationContext +public sealed class PackageValidationContext +{ + public PackageValidationContext(string packageId, NuGetVersion packageVersion, Stream package, PackageArchiveReader reader) { - public PackageValidationContext(string packageId, NuGetVersion packageVersion, Stream package, PackageArchiveReader reader) - { - PackageId = packageId; - PackageVersion = packageVersion; - Package = package; - Reader = reader; - } + PackageId = packageId; + PackageVersion = packageVersion; + Package = package; + Reader = reader; + } - public string PackageId { get; } + public string PackageId { get; } - public NuGetVersion PackageVersion { get; } + public NuGetVersion PackageVersion { get; } - /// - /// The raw package. Seekable; a validator must not dispose it. - /// - public Stream Package { get; } + /// + /// The raw package. Seekable; a validator must not dispose it. + /// + public Stream Package { get; } - /// - /// A reader over . A validator must not dispose it. - /// - public PackageArchiveReader Reader { get; } - } + /// + /// A reader over . A validator must not dispose it. + /// + public PackageArchiveReader Reader { get; } +} - public sealed class PackageValidatorResult - { - public static readonly PackageValidatorResult Valid = new PackageValidatorResult(true, null); +public sealed class PackageValidatorResult +{ + public static readonly PackageValidatorResult Valid = new PackageValidatorResult(true, null); - private PackageValidatorResult(bool isValid, string message) - { - IsValid = isValid; - Message = message; - } + private PackageValidatorResult(bool isValid, string message) + { + IsValid = isValid; + Message = message; + } - public bool IsValid { get; } + public bool IsValid { get; } - /// - /// Why the package is invalid. Shown to the package's owners. - /// - public string Message { get; } + /// + /// Why the package is invalid. Shown to the package's owners. + /// + public string Message { get; } - public static PackageValidatorResult Invalid(string message) - => new PackageValidatorResult(false, message ?? throw new ArgumentNullException(nameof(message))); - } -} + public static PackageValidatorResult Invalid(string message) + => new PackageValidatorResult(false, message ?? throw new ArgumentNullException(nameof(message))); +} \ No newline at end of file diff --git a/src/BaGet.Validation/PackageValidationRunner.cs b/src/BaGet.Validation/PackageValidationRunner.cs index ea9621386..33227062e 100644 --- a/src/BaGet.Validation/PackageValidationRunner.cs +++ b/src/BaGet.Validation/PackageValidationRunner.cs @@ -10,180 +10,179 @@ using Microsoft.Extensions.Options; using NuGet.Packaging; -namespace BaGet.Validation +namespace BaGet.Validation; + +/// +/// Runs one submission: every validator, then, if all passed, repository signing and +/// indexing. A package that fails stays staged, quarantined, for its owners to inspect. +/// +public class PackageValidationRunner { - /// - /// Runs one submission: every validator, then, if all passed, repository signing and - /// indexing. A package that fails stays staged, quarantined, for its owners to inspect. - /// - public class PackageValidationRunner + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IPackageIndexingService _indexer; + private readonly IPackageDatabase _packages; + private readonly IEnumerable _validators; + private readonly RepositorySigner _signer; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + private readonly ILogger _logger; + + public PackageValidationRunner( + IContext context, + IStorageService storage, + IPackageIndexingService indexer, + IPackageDatabase packages, + IEnumerable validators, + RepositorySigner signer, + SystemTime time, + IOptionsSnapshot options, + ILogger logger) { - private readonly IContext _context; - private readonly IStorageService _storage; - private readonly IPackageIndexingService _indexer; - private readonly IPackageDatabase _packages; - private readonly IEnumerable _validators; - private readonly RepositorySigner _signer; - private readonly SystemTime _time; - private readonly IOptionsSnapshot _options; - private readonly ILogger _logger; - - public PackageValidationRunner( - IContext context, - IStorageService storage, - IPackageIndexingService indexer, - IPackageDatabase packages, - IEnumerable validators, - RepositorySigner signer, - SystemTime time, - IOptionsSnapshot options, - ILogger logger) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _validators = validators ?? throw new ArgumentNullException(nameof(validators)); - _signer = signer ?? throw new ArgumentNullException(nameof(signer)); - _time = time ?? throw new ArgumentNullException(nameof(time)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _validators = validators ?? throw new ArgumentNullException(nameof(validators)); + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task> GetPendingSubmissionIdsAsync(CancellationToken cancellationToken) + { + return await _context.PackageValidations + .Where(v => v.State == PackageValidationState.Pending) + .Select(v => v.SubmissionId) + .Distinct() + .ToListAsync(cancellationToken); + } - public async Task> GetPendingSubmissionIdsAsync(CancellationToken cancellationToken) + public async Task RunAsync(string submissionId, CancellationToken cancellationToken) + { + var steps = await _context.PackageValidations + .Where(v => v.SubmissionId == submissionId) + .ToListAsync(cancellationToken); + + var index = steps.SingleOrDefault(s => s.Type == PackageValidation.IndexType); + if (index == null || index.State != PackageValidationState.Pending) { - return await _context.PackageValidations - .Where(v => v.State == PackageValidationState.Pending) - .Select(v => v.SubmissionId) - .Distinct() - .ToListAsync(cancellationToken); + return; } - public async Task RunAsync(string submissionId, CancellationToken cancellationToken) + using var package = new MemoryStream(); + using (var staged = await _storage.GetAsync(ValidatingPackageSubmissionService.StagedPath(submissionId), cancellationToken)) { - var steps = await _context.PackageValidations - .Where(v => v.SubmissionId == submissionId) - .ToListAsync(cancellationToken); - - var index = steps.SingleOrDefault(s => s.Type == PackageValidation.IndexType); - if (index == null || index.State != PackageValidationState.Pending) - { - return; - } + await staged.CopyToAsync(package, cancellationToken); + } - using var package = new MemoryStream(); - using (var staged = await _storage.GetAsync(ValidatingPackageSubmissionService.StagedPath(submissionId), cancellationToken)) - { - await staged.CopyToAsync(package, cancellationToken); - } + package.Position = 0; - package.Position = 0; + using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) + { + var identity = await reader.GetIdentityAsync(cancellationToken); + var context = new PackageValidationContext(identity.Id, identity.Version, package, reader); - using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) + foreach (var validator in _validators) { - var identity = await reader.GetIdentityAsync(cancellationToken); - var context = new PackageValidationContext(identity.Id, identity.Version, package, reader); + var step = steps.FirstOrDefault(s => s.Type == validator.Name); + if (step == null || step.State != PackageValidationState.Pending) continue; - foreach (var validator in _validators) + PackageValidatorResult result; + try { - var step = steps.FirstOrDefault(s => s.Type == validator.Name); - if (step == null || step.State != PackageValidationState.Pending) continue; - - PackageValidatorResult result; - try - { - package.Position = 0; - result = await validator.ValidateAsync(context, cancellationToken); - } - catch (Exception e) when (!(e is OperationCanceledException)) - { - _logger.LogError(e, "Validator {Validator} failed on submission {SubmissionId}", validator.Name, submissionId); - result = PackageValidatorResult.Invalid($"The {validator.Name} validator failed: {e.Message}"); - } - - Complete(step, result.IsValid, result.Message); + package.Position = 0; + result = await validator.ValidateAsync(context, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogError(e, "Validator {Validator} failed on submission {SubmissionId}", validator.Name, submissionId); + result = PackageValidatorResult.Invalid($"The {validator.Name} validator failed: {e.Message}"); } - } - // A step whose validator is no longer registered cannot pass. - foreach (var orphan in steps.Where(s => s.State == PackageValidationState.Pending && s != index)) - { - Complete(orphan, succeeded: false, $"The {orphan.Type} validator is no longer registered."); + Complete(step, result.IsValid, result.Message); } + } - if (steps.Any(s => s.State == PackageValidationState.Failed)) - { - Complete(index, succeeded: false, "Quarantined: the package failed validation."); - await _context.SaveChangesAsync(cancellationToken); + // A step whose validator is no longer registered cannot pass. + foreach (var orphan in steps.Where(s => s.State == PackageValidationState.Pending && s != index)) + { + Complete(orphan, succeeded: false, $"The {orphan.Type} validator is no longer registered."); + } - _logger.LogWarning("Submission {SubmissionId} failed validation and is quarantined", submissionId); - return; - } + if (steps.Any(s => s.State == PackageValidationState.Failed)) + { + Complete(index, succeeded: false, "Quarantined: the package failed validation."); + await _context.SaveChangesAsync(cancellationToken); - var indexError = await IndexAsync(package, _options.Value.RepositorySigningServiceIndexUrl, cancellationToken); - Complete(index, indexError == null, indexError); + _logger.LogWarning("Submission {SubmissionId} failed validation and is quarantined", submissionId); + return; + } - if (indexError == null) + var indexError = await IndexAsync(package, _options.Value.RepositorySigningServiceIndexUrl, cancellationToken); + Complete(index, indexError == null, indexError); + + if (indexError == null) + { + var version = NuGet.Versioning.NuGetVersion.Parse(index.PackageVersion); + var indexed = await _packages.FindOrNullAsync(index.PackageId, version, includeUnlisted: true, cancellationToken); + foreach (var step in steps) { - var version = NuGet.Versioning.NuGetVersion.Parse(index.PackageVersion); - var indexed = await _packages.FindOrNullAsync(index.PackageId, version, includeUnlisted: true, cancellationToken); - foreach (var step in steps) - { - step.PackageKey = indexed?.Key; - } + step.PackageKey = indexed?.Key; } + } - await _context.SaveChangesAsync(cancellationToken); + await _context.SaveChangesAsync(cancellationToken); - if (indexError == null) - { - await _storage.DeleteAsync(ValidatingPackageSubmissionService.StagedPath(submissionId), cancellationToken); - } + if (indexError == null) + { + await _storage.DeleteAsync(ValidatingPackageSubmissionService.StagedPath(submissionId), cancellationToken); } + } - /// Null on success, otherwise why indexing failed. - private async Task IndexAsync(Stream package, string serviceIndexUrl, CancellationToken cancellationToken) + /// Null on success, otherwise why indexing failed. + private async Task IndexAsync(Stream package, string serviceIndexUrl, CancellationToken cancellationToken) + { + Stream toIndex = package; + try { - Stream toIndex = package; - try + if (_signer.IsConfigured) { - if (_signer.IsConfigured) + // NuGet only accepts a repository signature that names an https source. + if (!Uri.TryCreate(serviceIndexUrl, UriKind.Absolute, out var url) || url.Scheme != Uri.UriSchemeHttps) { - // NuGet only accepts a repository signature that names an https source. - if (!Uri.TryCreate(serviceIndexUrl, UriKind.Absolute, out var url) || url.Scheme != Uri.UriSchemeHttps) - { - return "Repository signing needs Validation:RepositorySigningServiceIndexUrl to be an absolute https URL."; - } - - toIndex = await _signer.SignAsync(package, serviceIndexUrl, cancellationToken); + return "Repository signing needs Validation:RepositorySigningServiceIndexUrl to be an absolute https URL."; } - toIndex.Position = 0; - var result = await _indexer.IndexAsync(toIndex, cancellationToken); - - return result == PackageIndexingResult.Success ? null : $"Indexing failed: {result}."; + toIndex = await _signer.SignAsync(package, serviceIndexUrl, cancellationToken); } - catch (Exception e) when (!(e is OperationCanceledException)) - { - _logger.LogError(e, "Failed to index a validated package"); - return $"Indexing failed: {e.Message}"; - } - finally + + toIndex.Position = 0; + var result = await _indexer.IndexAsync(toIndex, cancellationToken); + + return result == PackageIndexingResult.Success ? null : $"Indexing failed: {result}."; + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogError(e, "Failed to index a validated package"); + return $"Indexing failed: {e.Message}"; + } + finally + { + if (!ReferenceEquals(toIndex, package)) { - if (!ReferenceEquals(toIndex, package)) - { - toIndex.Dispose(); - } + toIndex.Dispose(); } } + } - private void Complete(PackageValidation step, bool succeeded, string message) - { - step.State = succeeded ? PackageValidationState.Succeeded : PackageValidationState.Failed; - step.Message = message?.Length > AbstractContext.DefaultMaxStringLength - ? message.Substring(0, AbstractContext.DefaultMaxStringLength) - : message; - step.Completed = _time.UtcNow; - } + private void Complete(PackageValidation step, bool succeeded, string message) + { + step.State = succeeded ? PackageValidationState.Succeeded : PackageValidationState.Failed; + step.Message = message?.Length > AbstractContext.DefaultMaxStringLength + ? message.Substring(0, AbstractContext.DefaultMaxStringLength) + : message; + step.Completed = _time.UtcNow; } -} +} \ No newline at end of file diff --git a/src/BaGet.Validation/RepositorySignaturesController.cs b/src/BaGet.Validation/RepositorySignaturesController.cs index eb46b64b9..7850a2af8 100644 --- a/src/BaGet.Validation/RepositorySignaturesController.cs +++ b/src/BaGet.Validation/RepositorySignaturesController.cs @@ -11,215 +11,214 @@ using Microsoft.EntityFrameworkCore; using NuGet.Versioning; -namespace BaGet.Validation +namespace BaGet.Validation; + +/// +/// The RepositorySignatures/5.0.0 resource, and each submission's validation status. +/// +public class RepositorySignaturesController : Controller { - /// - /// The RepositorySignatures/5.0.0 resource, and each submission's validation status. - /// - public class RepositorySignaturesController : Controller - { - // The OID the protocol keys a SHA-256 fingerprint by. - internal const string Sha256Oid = "2.16.840.1.101.3.4.2.1"; + // The OID the protocol keys a SHA-256 fingerprint by. + internal const string Sha256Oid = "2.16.840.1.101.3.4.2.1"; - private readonly RepositorySigner _signer; - private readonly IUrlGenerator _url; + private readonly RepositorySigner _signer; + private readonly IUrlGenerator _url; - public RepositorySignaturesController(RepositorySigner signer, IUrlGenerator url) - { - _signer = signer ?? throw new ArgumentNullException(nameof(signer)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public RepositorySignaturesController(RepositorySigner signer, IUrlGenerator url) + { + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - [HttpGet] - public IActionResult Index() - { - using var certificate = _signer.GetPublicCertificateOrNull(); - if (certificate == null) return NotFound(); + [HttpGet] + public IActionResult Index() + { + using var certificate = _signer.GetPublicCertificateOrNull(); + if (certificate == null) return NotFound(); - var fingerprint = Fingerprint(certificate.RawData); + var fingerprint = Fingerprint(certificate.RawData); - return Json(new RepositorySignaturesResponse + return Json(new RepositorySignaturesResponse + { + // Packages pushed before signing was configured, and mirrored ones, are not + // repository signed, so a client must not insist that every package is. + AllRepositorySigned = false, + SigningCertificates = new[] { - // Packages pushed before signing was configured, and mirrored ones, are not - // repository signed, so a client must not insist that every package is. - AllRepositorySigned = false, - SigningCertificates = new[] + new RepositorySigningCertificate { - new RepositorySigningCertificate - { - Fingerprints = new Dictionary { [Sha256Oid] = fingerprint }, - Subject = certificate.Subject, - Issuer = certificate.Issuer, - NotBefore = certificate.NotBefore.ToUniversalTime(), - NotAfter = certificate.NotAfter.ToUniversalTime(), - ContentUrl = _url.GetRepositorySigningCertificateUrl(fingerprint), - }, + Fingerprints = new Dictionary { [Sha256Oid] = fingerprint }, + Subject = certificate.Subject, + Issuer = certificate.Issuer, + NotBefore = certificate.NotBefore.ToUniversalTime(), + NotAfter = certificate.NotAfter.ToUniversalTime(), + ContentUrl = _url.GetRepositorySigningCertificateUrl(fingerprint), }, - }); - } + }, + }); + } - [HttpGet] - public IActionResult Certificate(string fingerprint) + [HttpGet] + public IActionResult Certificate(string fingerprint) + { + using var certificate = _signer.GetPublicCertificateOrNull(); + if (certificate == null || !string.Equals(Fingerprint(certificate.RawData), fingerprint, StringComparison.OrdinalIgnoreCase)) { - using var certificate = _signer.GetPublicCertificateOrNull(); - if (certificate == null || !string.Equals(Fingerprint(certificate.RawData), fingerprint, StringComparison.OrdinalIgnoreCase)) - { - return NotFound(); - } - - return File(certificate.RawData, "application/pkix-cert"); + return NotFound(); } - internal static string Fingerprint(byte[] certificate) - => Convert.ToHexString(SHA256.HashData(certificate)).ToLowerInvariant(); + return File(certificate.RawData, "application/pkix-cert"); } - /// - /// A package version's validation, for its owners: whether it is pending, available - /// or quarantined, and why. - /// - public class ValidationStatusController : Controller + internal static string Fingerprint(byte[] certificate) + => Convert.ToHexString(SHA256.HashData(certificate)).ToLowerInvariant(); +} + +/// +/// A package version's validation, for its owners: whether it is pending, available +/// or quarantined, and why. +/// +public class ValidationStatusController : Controller +{ + private readonly IContext _context; + private readonly Core.IAuthenticationService _authentication; + private readonly IPackageAuthorizationService _authorization; + + public ValidationStatusController( + IContext context, + Core.IAuthenticationService authentication, + IPackageAuthorizationService authorization) { - private readonly IContext _context; - private readonly Core.IAuthenticationService _authentication; - private readonly IPackageAuthorizationService _authorization; - - public ValidationStatusController( - IContext context, - Core.IAuthenticationService authentication, - IPackageAuthorizationService authorization) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); - _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); - } + _context = context ?? throw new ArgumentNullException(nameof(context)); + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + } - [HttpGet] - public async Task Get(string id, string version, CancellationToken cancellationToken) - { - if (!NuGetVersion.TryParse(version, out var nugetVersion)) return NotFound(); + [HttpGet] + public async Task Get(string id, string version, CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var nugetVersion)) return NotFound(); - var principal = await _authentication.AuthenticatePrincipalAsync(Request.Headers["X-NuGet-ApiKey"], cancellationToken); - if (principal == null) return Unauthorized(); - if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, id, cancellationToken) - && !await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken)) - { - return StatusCode(403); - } + var principal = await _authentication.AuthenticatePrincipalAsync(Request.Headers["X-NuGet-ApiKey"], cancellationToken); + if (principal == null) return Unauthorized(); + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, id, cancellationToken) + && !await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken)) + { + return StatusCode(403); + } - if (_context is NullContext) return NotFound(); + if (_context is NullContext) return NotFound(); - var lowerId = id.ToLowerInvariant(); - var normalized = nugetVersion.ToNormalizedString(); - var steps = await _context.PackageValidations - .AsNoTracking() - .Where(v => v.PackageId.ToLower() == lowerId && v.PackageVersion == normalized) - .OrderByDescending(v => v.Key) - .ToListAsync(cancellationToken); + var lowerId = id.ToLowerInvariant(); + var normalized = nugetVersion.ToNormalizedString(); + var steps = await _context.PackageValidations + .AsNoTracking() + .Where(v => v.PackageId.ToLower() == lowerId && v.PackageVersion == normalized) + .OrderByDescending(v => v.Key) + .ToListAsync(cancellationToken); - if (steps.Count == 0) return NotFound(); + if (steps.Count == 0) return NotFound(); - // The newest submission is the one that matters. - var latest = steps[0].SubmissionId; - var submission = steps.Where(s => s.SubmissionId == latest).OrderBy(s => s.Key).ToList(); - var index = submission.Single(s => s.Type == PackageValidation.IndexType); + // The newest submission is the one that matters. + var latest = steps[0].SubmissionId; + var submission = steps.Where(s => s.SubmissionId == latest).OrderBy(s => s.Key).ToList(); + var index = submission.Single(s => s.Type == PackageValidation.IndexType); - return Json(new ValidationStatusResponse + return Json(new ValidationStatusResponse + { + SubmissionId = latest, + Status = index.State switch { - SubmissionId = latest, - Status = index.State switch - { - PackageValidationState.Succeeded => "Available", - PackageValidationState.Failed => "Quarantined", - _ => "Validating", - }, - Steps = submission - .Select(s => new ValidationStep { Type = s.Type, State = s.State.ToString(), Message = s.Message }) - .ToList(), - }); - } + PackageValidationState.Succeeded => "Available", + PackageValidationState.Failed => "Quarantined", + _ => "Validating", + }, + Steps = submission + .Select(s => new ValidationStep { Type = s.Type, State = s.State.ToString(), Message = s.Message }) + .ToList(), + }); } +} - public class RepositorySignaturesResponse - { - [JsonPropertyName("allRepositorySigned")] - public bool AllRepositorySigned { get; set; } +public class RepositorySignaturesResponse +{ + [JsonPropertyName("allRepositorySigned")] + public bool AllRepositorySigned { get; set; } - [JsonPropertyName("signingCertificates")] - public IReadOnlyList SigningCertificates { get; set; } - } + [JsonPropertyName("signingCertificates")] + public IReadOnlyList SigningCertificates { get; set; } +} - public class RepositorySigningCertificate - { - [JsonPropertyName("fingerprints")] - public IReadOnlyDictionary Fingerprints { get; set; } +public class RepositorySigningCertificate +{ + [JsonPropertyName("fingerprints")] + public IReadOnlyDictionary Fingerprints { get; set; } - [JsonPropertyName("subject")] - public string Subject { get; set; } + [JsonPropertyName("subject")] + public string Subject { get; set; } - [JsonPropertyName("issuer")] - public string Issuer { get; set; } + [JsonPropertyName("issuer")] + public string Issuer { get; set; } - [JsonPropertyName("notBefore")] - public DateTime NotBefore { get; set; } + [JsonPropertyName("notBefore")] + public DateTime NotBefore { get; set; } - [JsonPropertyName("notAfter")] - public DateTime NotAfter { get; set; } + [JsonPropertyName("notAfter")] + public DateTime NotAfter { get; set; } - [JsonPropertyName("contentUrl")] - public string ContentUrl { get; set; } - } + [JsonPropertyName("contentUrl")] + public string ContentUrl { get; set; } +} - public class ValidationStatusResponse - { - [JsonPropertyName("submissionId")] - public string SubmissionId { get; set; } +public class ValidationStatusResponse +{ + [JsonPropertyName("submissionId")] + public string SubmissionId { get; set; } - /// - /// "Validating", "Available" or "Quarantined". - /// - [JsonPropertyName("status")] - public string Status { get; set; } + /// + /// "Validating", "Available" or "Quarantined". + /// + [JsonPropertyName("status")] + public string Status { get; set; } - [JsonPropertyName("steps")] - public IReadOnlyList Steps { get; set; } - } + [JsonPropertyName("steps")] + public IReadOnlyList Steps { get; set; } +} - public class ValidationStep - { - [JsonPropertyName("type")] - public string Type { get; set; } +public class ValidationStep +{ + [JsonPropertyName("type")] + public string Type { get; set; } - [JsonPropertyName("state")] - public string State { get; set; } + [JsonPropertyName("state")] + public string State { get; set; } - [JsonPropertyName("message")] - public string Message { get; set; } - } + [JsonPropertyName("message")] + public string Message { get; set; } +} - /// - /// Advertises RepositorySignatures/5.0.0 while a signing certificate is configured. - /// - public class RepositorySignaturesServiceIndexProvider : IServiceIndexResourceProvider +/// +/// Advertises RepositorySignatures/5.0.0 while a signing certificate is configured. +/// +public class RepositorySignaturesServiceIndexProvider : IServiceIndexResourceProvider +{ + private readonly RepositorySigner _signer; + private readonly IUrlGenerator _url; + + public RepositorySignaturesServiceIndexProvider(RepositorySigner signer, IUrlGenerator url) { - private readonly RepositorySigner _signer; - private readonly IUrlGenerator _url; + _signer = signer ?? throw new ArgumentNullException(nameof(signer)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - public RepositorySignaturesServiceIndexProvider(RepositorySigner signer, IUrlGenerator url) - { - _signer = signer ?? throw new ArgumentNullException(nameof(signer)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public IEnumerable GetResources() + { + if (!_signer.IsConfigured) yield break; - public IEnumerable GetResources() + yield return new ServiceIndexItem { - if (!_signer.IsConfigured) yield break; - - yield return new ServiceIndexItem - { - ResourceUrl = _url.GetRepositorySignaturesUrl(), - Type = "RepositorySignatures/5.0.0", - }; - } + ResourceUrl = _url.GetRepositorySignaturesUrl(), + Type = "RepositorySignatures/5.0.0", + }; } -} +} \ No newline at end of file diff --git a/src/BaGet.Validation/RepositorySigner.cs b/src/BaGet.Validation/RepositorySigner.cs index 5cd1d5f34..37785deda 100644 --- a/src/BaGet.Validation/RepositorySigner.cs +++ b/src/BaGet.Validation/RepositorySigner.cs @@ -9,104 +9,103 @@ using NuGet.Common; using NuGet.Packaging.Signing; -namespace BaGet.Validation +namespace BaGet.Validation; + +/// +/// Repository-signs validated packages with the configured certificate, so a client can +/// tell a package came through this server. See: +/// https://learn.microsoft.com/en-us/nuget/api/repository-signatures-resource +/// +public class RepositorySigner { + private readonly IOptionsSnapshot _options; + + public RepositorySigner(IOptionsSnapshot options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public bool IsConfigured => !string.IsNullOrEmpty(_options.Value.RepositorySigningCertificatePath); + /// - /// Repository-signs validated packages with the configured certificate, so a client can - /// tell a package came through this server. See: - /// https://learn.microsoft.com/en-us/nuget/api/repository-signatures-resource + /// The configured certificate, without its private key, or null if none is. /// - public class RepositorySigner + public X509Certificate2 GetPublicCertificateOrNull() { - private readonly IOptionsSnapshot _options; + if (!IsConfigured) return null; - public RepositorySigner(IOptionsSnapshot options) - { - _options = options ?? throw new ArgumentNullException(nameof(options)); - } + using var certificate = LoadCertificate(); - public bool IsConfigured => !string.IsNullOrEmpty(_options.Value.RepositorySigningCertificatePath); - - /// - /// The configured certificate, without its private key, or null if none is. - /// - public X509Certificate2 GetPublicCertificateOrNull() - { - if (!IsConfigured) return null; + return X509CertificateLoader.LoadCertificate(certificate.RawData); + } - using var certificate = LoadCertificate(); + /// + /// Sign a package, returning the signed copy. A package that already has a + /// repository signature is returned as it is. + /// + /// + /// This server's service index. The signature records it, and a client checks that + /// it matches the source the package came from. + /// + public async Task SignAsync(Stream package, string serviceIndexUrl, CancellationToken cancellationToken) + { + var directory = Path.Combine(Path.GetTempPath(), "BaGetSigning", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); - return X509CertificateLoader.LoadCertificate(certificate.RawData); - } + var input = Path.Combine(directory, "input.nupkg"); + var output = Path.Combine(directory, "output.nupkg"); - /// - /// Sign a package, returning the signed copy. A package that already has a - /// repository signature is returned as it is. - /// - /// - /// This server's service index. The signature records it, and a client checks that - /// it matches the source the package came from. - /// - public async Task SignAsync(Stream package, string serviceIndexUrl, CancellationToken cancellationToken) + try { - var directory = Path.Combine(Path.GetTempPath(), "BaGetSigning", Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(directory); - - var input = Path.Combine(directory, "input.nupkg"); - var output = Path.Combine(directory, "output.nupkg"); - - try + using (var file = File.Create(input)) { - using (var file = File.Create(input)) - { - package.Position = 0; - await package.CopyToAsync(file, cancellationToken); - } + package.Position = 0; + await package.CopyToAsync(file, cancellationToken); + } - using (var certificate = LoadCertificate()) - using (var request = new RepositorySignPackageRequest( - certificate, - NuGet.Common.HashAlgorithmName.SHA256, - NuGet.Common.HashAlgorithmName.SHA256, - new Uri(serviceIndexUrl), - packageOwners: null)) - using (var options = SigningOptions.CreateFromFilePaths( - input, - output, - overwrite: true, - signatureProvider: new X509SignatureProvider(timestampProvider: null), - logger: NullLogger.Instance)) - { - await SigningUtility.SignAsync(options, request, cancellationToken); - } + using (var certificate = LoadCertificate()) + using (var request = new RepositorySignPackageRequest( + certificate, + NuGet.Common.HashAlgorithmName.SHA256, + NuGet.Common.HashAlgorithmName.SHA256, + new Uri(serviceIndexUrl), + packageOwners: null)) + using (var options = SigningOptions.CreateFromFilePaths( + input, + output, + overwrite: true, + signatureProvider: new X509SignatureProvider(timestampProvider: null), + logger: NullLogger.Instance)) + { + await SigningUtility.SignAsync(options, request, cancellationToken); + } - var signed = new MemoryStream(); - using (var file = File.OpenRead(output)) - { - await file.CopyToAsync(signed, cancellationToken); - } + var signed = new MemoryStream(); + using (var file = File.OpenRead(output)) + { + await file.CopyToAsync(signed, cancellationToken); + } - signed.Position = 0; + signed.Position = 0; - return signed; + return signed; + } + finally + { + try + { + Directory.Delete(directory, recursive: true); } - finally + catch (IOException) { - try - { - Directory.Delete(directory, recursive: true); - } - catch (IOException) - { - // A temporary file left behind is not worth failing the push for. - } + // A temporary file left behind is not worth failing the push for. } } - - private X509Certificate2 LoadCertificate() - => X509CertificateLoader.LoadPkcs12FromFile( - _options.Value.RepositorySigningCertificatePath, - _options.Value.RepositorySigningCertificatePassword, - X509KeyStorageFlags.EphemeralKeySet); } -} + + private X509Certificate2 LoadCertificate() + => X509CertificateLoader.LoadPkcs12FromFile( + _options.Value.RepositorySigningCertificatePath, + _options.Value.RepositorySigningCertificatePassword, + X509KeyStorageFlags.EphemeralKeySet); +} \ No newline at end of file diff --git a/src/BaGet.Validation/ValidatingPackageSubmissionService.cs b/src/BaGet.Validation/ValidatingPackageSubmissionService.cs index 31e88841b..659b44ccf 100644 --- a/src/BaGet.Validation/ValidatingPackageSubmissionService.cs +++ b/src/BaGet.Validation/ValidatingPackageSubmissionService.cs @@ -10,122 +10,121 @@ using Microsoft.Extensions.Options; using NuGet.Packaging; -namespace BaGet.Validation +namespace BaGet.Validation; + +/// +/// With validation on, stages a pushed package and queues it; otherwise indexes it at +/// once, exactly as before. +/// +public class ValidatingPackageSubmissionService : IPackageSubmissionService { - /// - /// With validation on, stages a pushed package and queues it; otherwise indexes it at - /// once, exactly as before. - /// - public class ValidatingPackageSubmissionService : IPackageSubmissionService + private readonly IPackageIndexingService _indexer; + private readonly IPackageDatabase _packages; + private readonly IContext _context; + private readonly IStorageService _storage; + private readonly IValidationQueue _queue; + private readonly IEnumerable _validators; + private readonly SystemTime _time; + private readonly IOptionsSnapshot _options; + private readonly IOptionsSnapshot _validation; + private readonly ILogger _logger; + + public ValidatingPackageSubmissionService( + IPackageIndexingService indexer, + IPackageDatabase packages, + IContext context, + IStorageService storage, + IValidationQueue queue, + IEnumerable validators, + SystemTime time, + IOptionsSnapshot options, + IOptionsSnapshot validation, + ILogger logger) { - private readonly IPackageIndexingService _indexer; - private readonly IPackageDatabase _packages; - private readonly IContext _context; - private readonly IStorageService _storage; - private readonly IValidationQueue _queue; - private readonly IEnumerable _validators; - private readonly SystemTime _time; - private readonly IOptionsSnapshot _options; - private readonly IOptionsSnapshot _validation; - private readonly ILogger _logger; + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _validators = validators ?? throw new ArgumentNullException(nameof(validators)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _validation = validation ?? throw new ArgumentNullException(nameof(validation)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + internal static string StagedPath(string submissionId) => $"validation/{submissionId}.nupkg"; - public ValidatingPackageSubmissionService( - IPackageIndexingService indexer, - IPackageDatabase packages, - IContext context, - IStorageService storage, - IValidationQueue queue, - IEnumerable validators, - SystemTime time, - IOptionsSnapshot options, - IOptionsSnapshot validation, - ILogger logger) + public async Task SubmitAsync(Stream package, CancellationToken cancellationToken) + { + if (!_validation.Value.Enabled) { - _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _context = context ?? throw new ArgumentNullException(nameof(context)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _queue = queue ?? throw new ArgumentNullException(nameof(queue)); - _validators = validators ?? throw new ArgumentNullException(nameof(validators)); - _time = time ?? throw new ArgumentNullException(nameof(time)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _validation = validation ?? throw new ArgumentNullException(nameof(validation)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + return await _indexer.IndexAsync(package, cancellationToken); } - internal static string StagedPath(string submissionId) => $"validation/{submissionId}.nupkg"; - - public async Task SubmitAsync(Stream package, CancellationToken cancellationToken) + string id; + string version; + try { - if (!_validation.Value.Enabled) + using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) { - return await _indexer.IndexAsync(package, cancellationToken); - } - - string id; - string version; - try - { - using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) - { - var identity = reader.GetIdentity(); - id = identity.Id; - version = identity.Version.ToNormalizedString(); - } - } - catch (Exception e) - { - _logger.LogError(e, "Uploaded package is invalid"); - return PackageIndexingResult.InvalidPackage; + var identity = reader.GetIdentity(); + id = identity.Id; + version = identity.Version.ToNormalizedString(); } + } + catch (Exception e) + { + _logger.LogError(e, "Uploaded package is invalid"); + return PackageIndexingResult.InvalidPackage; + } - if (!_options.Value.AllowPackageOverwrites - && await _packages.ExistsAsync(id, NuGet.Versioning.NuGetVersion.Parse(version), cancellationToken)) - { - return PackageIndexingResult.PackageAlreadyExists; - } + if (!_options.Value.AllowPackageOverwrites + && await _packages.ExistsAsync(id, NuGet.Versioning.NuGetVersion.Parse(version), cancellationToken)) + { + return PackageIndexingResult.PackageAlreadyExists; + } - // The same version cannot be validated twice at once. - var lowerId = id.ToLowerInvariant(); - if (await _context.PackageValidations.AnyAsync( + // The same version cannot be validated twice at once. + var lowerId = id.ToLowerInvariant(); + if (await _context.PackageValidations.AnyAsync( v => v.PackageId.ToLower() == lowerId - && v.PackageVersion == version - && v.State == PackageValidationState.Pending, + && v.PackageVersion == version + && v.State == PackageValidationState.Pending, cancellationToken)) - { - return PackageIndexingResult.PackageAlreadyExists; - } + { + return PackageIndexingResult.PackageAlreadyExists; + } - var submissionId = Guid.NewGuid().ToString("D"); + var submissionId = Guid.NewGuid().ToString("D"); - package.Position = 0; - await _storage.PutAsync(StagedPath(submissionId), package, "application/octet-stream", cancellationToken); + package.Position = 0; + await _storage.PutAsync(StagedPath(submissionId), package, "application/octet-stream", cancellationToken); - var now = _time.UtcNow; - var steps = _validators.Select(v => v.Name).Append(PackageValidation.IndexType); - foreach (var step in steps) + var now = _time.UtcNow; + var steps = _validators.Select(v => v.Name).Append(PackageValidation.IndexType); + foreach (var step in steps) + { + _context.PackageValidations.Add(new PackageValidation { - _context.PackageValidations.Add(new PackageValidation - { - SubmissionId = submissionId, - PackageId = id, - PackageVersion = version, - Type = step, - State = PackageValidationState.Pending, - Created = now, - }); - } + SubmissionId = submissionId, + PackageId = id, + PackageVersion = version, + Type = step, + State = PackageValidationState.Pending, + Created = now, + }); + } - await _context.SaveChangesAsync(cancellationToken); - await _queue.EnqueueAsync(submissionId, cancellationToken); + await _context.SaveChangesAsync(cancellationToken); + await _queue.EnqueueAsync(submissionId, cancellationToken); - _logger.LogInformation( - "Queued package {PackageId} {PackageVersion} for validation as {SubmissionId}", - id, - version, - submissionId); + _logger.LogInformation( + "Queued package {PackageId} {PackageVersion} for validation as {SubmissionId}", + id, + version, + submissionId); - return PackageIndexingResult.Accepted; - } + return PackageIndexingResult.Accepted; } -} +} \ No newline at end of file diff --git a/src/BaGet.Validation/ValidationQueue.cs b/src/BaGet.Validation/ValidationQueue.cs index ed2e3a583..493bc351c 100644 --- a/src/BaGet.Validation/ValidationQueue.cs +++ b/src/BaGet.Validation/ValidationQueue.cs @@ -3,29 +3,28 @@ using System.Threading.Channels; using System.Threading.Tasks; -namespace BaGet.Validation +namespace BaGet.Validation; + +/// +/// Hands submissions to the validation worker. The submissions themselves are in the +/// database, so a queue only has to say which to run next; the default one is in +/// memory, and on startup the worker re-queues whatever is still pending. +/// +public interface IValidationQueue { - /// - /// Hands submissions to the validation worker. The submissions themselves are in the - /// database, so a queue only has to say which to run next; the default one is in - /// memory, and on startup the worker re-queues whatever is still pending. - /// - public interface IValidationQueue - { - ValueTask EnqueueAsync(string submissionId, CancellationToken cancellationToken); + ValueTask EnqueueAsync(string submissionId, CancellationToken cancellationToken); - IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken); - } + IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken); +} - public class InMemoryValidationQueue : IValidationQueue - { - private readonly Channel _channel = Channel.CreateUnbounded( - new UnboundedChannelOptions { SingleReader = true }); +public class InMemoryValidationQueue : IValidationQueue +{ + private readonly Channel _channel = Channel.CreateUnbounded( + new UnboundedChannelOptions { SingleReader = true }); - public ValueTask EnqueueAsync(string submissionId, CancellationToken cancellationToken) - => _channel.Writer.WriteAsync(submissionId, cancellationToken); + public ValueTask EnqueueAsync(string submissionId, CancellationToken cancellationToken) + => _channel.Writer.WriteAsync(submissionId, cancellationToken); - public IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken) - => _channel.Reader.ReadAllAsync(cancellationToken); - } -} + public IAsyncEnumerable DequeueAllAsync(CancellationToken cancellationToken) + => _channel.Reader.ReadAllAsync(cancellationToken); +} \ No newline at end of file diff --git a/src/BaGet.Validation/ValidationServiceCollectionExtensions.cs b/src/BaGet.Validation/ValidationServiceCollectionExtensions.cs index 87a8f22db..ffa2d8519 100644 --- a/src/BaGet.Validation/ValidationServiceCollectionExtensions.cs +++ b/src/BaGet.Validation/ValidationServiceCollectionExtensions.cs @@ -2,29 +2,28 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace BaGet.Validation +namespace BaGet.Validation; + +public static class ValidationServiceCollectionExtensions { - public static class ValidationServiceCollectionExtensions + /// + /// Always registered; whether a push is validated is read from "Validation:Enabled" + /// on every push, so with it off the only difference is an idle worker. + /// + public static IServiceCollection AddBaGetValidation(this IServiceCollection services) { - /// - /// Always registered; whether a push is validated is read from "Validation:Enabled" - /// on every push, so with it off the only difference is an idle worker. - /// - public static IServiceCollection AddBaGetValidation(this IServiceCollection services) - { - services.Replace(ServiceDescriptor.Transient()); + services.Replace(ServiceDescriptor.Transient()); - services.TryAddSingleton(); - services.TryAddScoped(); - services.TryAddScoped(); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(); - services.TryAddEnumerable(ServiceDescriptor.Scoped()); - services.TryAddEnumerable(ServiceDescriptor.Scoped()); - services.TryAddEnumerable(ServiceDescriptor.Transient()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Transient()); - services.AddHostedService(); + services.AddHostedService(); - return services; - } + return services; } -} +} \ No newline at end of file diff --git a/src/BaGet.Validation/ValidationWorker.cs b/src/BaGet.Validation/ValidationWorker.cs index 21b7f4e02..fa45b72b2 100644 --- a/src/BaGet.Validation/ValidationWorker.cs +++ b/src/BaGet.Validation/ValidationWorker.cs @@ -7,72 +7,71 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace BaGet.Validation +namespace BaGet.Validation; + +/// +/// Runs queued submissions one at a time. On startup it re-queues every submission still +/// pending, so a restart delays validation but loses nothing. +/// +public class ValidationWorker : BackgroundService { - /// - /// Runs queued submissions one at a time. On startup it re-queues every submission still - /// pending, so a restart delays validation but loses nothing. - /// - public class ValidationWorker : BackgroundService - { - private readonly IServiceScopeFactory _scopes; - private readonly IValidationQueue _queue; - private readonly ILogger _logger; + private readonly IServiceScopeFactory _scopes; + private readonly IValidationQueue _queue; + private readonly ILogger _logger; - public ValidationWorker(IServiceScopeFactory scopes, IValidationQueue queue, ILogger logger) - { - _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); - _queue = queue ?? throw new ArgumentNullException(nameof(queue)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public ValidationWorker(IServiceScopeFactory scopes, IValidationQueue queue, ILogger logger) + { + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _queue = queue ?? throw new ArgumentNullException(nameof(queue)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - // Yield so that host startup does not wait on the database. - await Task.Yield(); + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + // Yield so that host startup does not wait on the database. + await Task.Yield(); - await RequeuePendingAsync(stoppingToken); + await RequeuePendingAsync(stoppingToken); - await foreach (var submissionId in _queue.DequeueAllAsync(stoppingToken)) + await foreach (var submissionId in _queue.DequeueAllAsync(stoppingToken)) + { + try { - try - { - using var scope = _scopes.CreateScope(); - var runner = scope.ServiceProvider.GetRequiredService(); + using var scope = _scopes.CreateScope(); + var runner = scope.ServiceProvider.GetRequiredService(); - await runner.RunAsync(submissionId, stoppingToken); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - return; - } - catch (Exception e) - { - // Left pending, so the next start retries it. - _logger.LogError(e, "Validation of submission {SubmissionId} failed", submissionId); - } + await runner.RunAsync(submissionId, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception e) + { + // Left pending, so the next start retries it. + _logger.LogError(e, "Validation of submission {SubmissionId} failed", submissionId); } } + } - private async Task RequeuePendingAsync(CancellationToken cancellationToken) + private async Task RequeuePendingAsync(CancellationToken cancellationToken) + { + try { - try - { - using var scope = _scopes.CreateScope(); - if (!scope.ServiceProvider.GetRequiredService>().Value.Enabled) return; - if (scope.ServiceProvider.GetRequiredService() is NullContext) return; + using var scope = _scopes.CreateScope(); + if (!scope.ServiceProvider.GetRequiredService>().Value.Enabled) return; + if (scope.ServiceProvider.GetRequiredService() is NullContext) return; - var runner = scope.ServiceProvider.GetRequiredService(); - foreach (var submissionId in await runner.GetPendingSubmissionIdsAsync(cancellationToken)) - { - await _queue.EnqueueAsync(submissionId, cancellationToken); - } - } - catch (Exception e) when (!(e is OperationCanceledException)) + var runner = scope.ServiceProvider.GetRequiredService(); + foreach (var submissionId in await runner.GetPendingSubmissionIdsAsync(cancellationToken)) { - // The database may not be migrated yet on a first start. - _logger.LogWarning(e, "Could not re-queue pending validations"); + await _queue.EnqueueAsync(submissionId, cancellationToken); } } + catch (Exception e) when (!(e is OperationCanceledException)) + { + // The database may not be migrated yet on a first start. + _logger.LogWarning(e, "Could not re-queue pending validations"); + } } -} +} \ No newline at end of file diff --git a/src/BaGet.Validation/Validators.cs b/src/BaGet.Validation/Validators.cs index b91e99ecc..09c46e59b 100644 --- a/src/BaGet.Validation/Validators.cs +++ b/src/BaGet.Validation/Validators.cs @@ -7,90 +7,89 @@ using NuGet.Common; using NuGet.Packaging.Signing; -namespace BaGet.Validation +namespace BaGet.Validation; + +/// +/// Every entry's path must be safe to extract: none may escape the package's folder. +/// +public class PackageEntriesValidator : IPackageValidator { - /// - /// Every entry's path must be safe to extract: none may escape the package's folder. - /// - public class PackageEntriesValidator : IPackageValidator - { - public string Name => "PackageEntries"; + public string Name => "PackageEntries"; - public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + { + try { - try - { - await context.Reader.ValidatePackageEntriesAsync(cancellationToken); + await context.Reader.ValidatePackageEntriesAsync(cancellationToken); - return PackageValidatorResult.Valid; - } - catch (NuGet.Packaging.Core.PackagingException e) - { - return PackageValidatorResult.Invalid(e.Message); - } + return PackageValidatorResult.Valid; + } + catch (NuGet.Packaging.Core.PackagingException e) + { + return PackageValidatorResult.Invalid(e.Message); } } +} + +/// +/// A signed package must have an intact, valid signature; an unsigned one is rejected +/// only when is set. Whether the +/// signing certificate is trusted is not checked: that is the client's policy to apply. +/// +public class PackageSignatureValidator : IPackageValidator +{ + private readonly IOptionsSnapshot _options; - /// - /// A signed package must have an intact, valid signature; an unsigned one is rejected - /// only when is set. Whether the - /// signing certificate is trusted is not checked: that is the client's policy to apply. - /// - public class PackageSignatureValidator : IPackageValidator + public PackageSignatureValidator(IOptionsSnapshot options) { - private readonly IOptionsSnapshot _options; + _options = options ?? throw new ArgumentNullException(nameof(options)); + } - public PackageSignatureValidator(IOptionsSnapshot options) + public string Name => "PackageSignature"; + + public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + { + if (!await context.Reader.IsSignedAsync(cancellationToken)) { - _options = options ?? throw new ArgumentNullException(nameof(options)); + return _options.Value.RequireSignedPackages + ? PackageValidatorResult.Invalid("The package must be signed.") + : PackageValidatorResult.Valid; } - public string Name => "PackageSignature"; - - public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + var verifier = new PackageSignatureVerifier(new ISignatureVerificationProvider[] { - if (!await context.Reader.IsSignedAsync(cancellationToken)) - { - return _options.Value.RequireSignedPackages - ? PackageValidatorResult.Invalid("The package must be signed.") - : PackageValidatorResult.Valid; - } - - var verifier = new PackageSignatureVerifier(new ISignatureVerificationProvider[] - { - new IntegrityVerificationProvider(), - new SignatureTrustAndValidityVerificationProvider(), - }); + new IntegrityVerificationProvider(), + new SignatureTrustAndValidityVerificationProvider(), + }); - // Untrusted roots are allowed: a private feed's packages are often signed with - // an internal certificate the server's machine does not trust. - var settings = new SignedPackageVerifierSettings( - allowUnsigned: false, - allowIllegal: false, - allowUntrusted: true, - allowIgnoreTimestamp: true, - allowMultipleTimestamps: true, - allowNoTimestamp: true, - allowUnknownRevocation: true, - reportUnknownRevocation: false, - verificationTarget: VerificationTarget.All, - signaturePlacement: SignaturePlacement.Any, - repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.IfExistsAndIsNecessary, - revocationMode: RevocationMode.Offline); + // Untrusted roots are allowed: a private feed's packages are often signed with + // an internal certificate the server's machine does not trust. + var settings = new SignedPackageVerifierSettings( + allowUnsigned: false, + allowIllegal: false, + allowUntrusted: true, + allowIgnoreTimestamp: true, + allowMultipleTimestamps: true, + allowNoTimestamp: true, + allowUnknownRevocation: true, + reportUnknownRevocation: false, + verificationTarget: VerificationTarget.All, + signaturePlacement: SignaturePlacement.Any, + repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.IfExistsAndIsNecessary, + revocationMode: RevocationMode.Offline); - var result = await verifier.VerifySignaturesAsync(context.Reader, settings, cancellationToken); - if (result.IsValid) - { - return PackageValidatorResult.Valid; - } + var result = await verifier.VerifySignaturesAsync(context.Reader, settings, cancellationToken); + if (result.IsValid) + { + return PackageValidatorResult.Valid; + } - var errors = result.Results - .SelectMany(r => r.GetErrorIssues()) - .Select(i => $"{i.Code}: {i.Message}") - .ToList(); + var errors = result.Results + .SelectMany(r => r.GetErrorIssues()) + .Select(i => $"{i.Code}: {i.Message}") + .ToList(); - return PackageValidatorResult.Invalid( - errors.Count == 0 ? "The package's signature is invalid." : string.Join(" ", errors)); - } + return PackageValidatorResult.Invalid( + errors.Count == 0 ? "The package's signature is invalid." : string.Join(" ", errors)); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web.V2/V2FeedController.cs b/src/BaGet.Web.V2/V2FeedController.cs index fd50eab7a..4a06d6a96 100644 --- a/src/BaGet.Web.V2/V2FeedController.cs +++ b/src/BaGet.Web.V2/V2FeedController.cs @@ -9,286 +9,285 @@ using Microsoft.Extensions.Options; using NuGet.Versioning; -namespace BaGet.Web.V2 +namespace BaGet.Web.V2; + +/// +/// The NuGet V2 (OData) feed, for clients that cannot speak V3: "nuget list", +/// older Install-Package, and PowerShellGet. +/// +/// +/// This is a deliberately partial OData implementation. The endpoints NuGet's own V2 +/// client calls are served fully, but the OData query options are not interpreted: +/// "$filter", "$orderby", "$select" and "$expand" are ignored rather than applied. +/// "$skip" and "$top" are honoured, because that is how a client pages. +/// +public class V2FeedController : Controller { + private const int DefaultPageSize = 100; + private const int MaxPageSize = 1000; + + private readonly IPackageDatabase _packages; + private readonly ISearchService _search; + private readonly IUrlGenerator _url; + private readonly IOptionsSnapshot _feeds; + + public V2FeedController( + IPackageDatabase packages, + ISearchService search, + IUrlGenerator url, + IOptionsSnapshot feeds) + { + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _search = search ?? throw new ArgumentNullException(nameof(search)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + _feeds = feeds ?? throw new ArgumentNullException(nameof(feeds)); + } + /// - /// The NuGet V2 (OData) feed, for clients that cannot speak V3: "nuget list", - /// older Install-Package, and PowerShellGet. + /// When the V2 feed is switched off the whole surface answers as though it does not + /// exist, rather than each action checking for itself. /// - /// - /// This is a deliberately partial OData implementation. The endpoints NuGet's own V2 - /// client calls are served fully, but the OData query options are not interpreted: - /// "$filter", "$orderby", "$select" and "$expand" are ignored rather than applied. - /// "$skip" and "$top" are honoured, because that is how a client pages. - /// - public class V2FeedController : Controller + public override void OnActionExecuting(ActionExecutingContext context) { - private const int DefaultPageSize = 100; - private const int MaxPageSize = 1000; - - private readonly IPackageDatabase _packages; - private readonly ISearchService _search; - private readonly IUrlGenerator _url; - private readonly IOptionsSnapshot _feeds; - - public V2FeedController( - IPackageDatabase packages, - ISearchService search, - IUrlGenerator url, - IOptionsSnapshot feeds) + if (!_feeds.Value.EnableV2) { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _search = search ?? throw new ArgumentNullException(nameof(search)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - _feeds = feeds ?? throw new ArgumentNullException(nameof(feeds)); + context.Result = NotFound(); + return; } - /// - /// When the V2 feed is switched off the whole surface answers as though it does not - /// exist, rather than each action checking for itself. - /// - public override void OnActionExecuting(ActionExecutingContext context) - { - if (!_feeds.Value.EnableV2) - { - context.Result = NotFound(); - return; - } + base.OnActionExecuting(context); + } - base.OnActionExecuting(context); - } + /// + /// The service document. A V2 client reads this to discover the "Packages" set. + /// + public IActionResult Root() + { + var document = + "" + + "" + + "Default" + + "Packages" + + ""; + + return Content(document, "application/xml; charset=utf-8"); + } - /// - /// The service document. A V2 client reads this to discover the "Packages" set. - /// - public IActionResult Root() - { - var document = - "" + - "" + - "Default" + - "Packages" + - ""; - - return Content(document, "application/xml; charset=utf-8"); - } + public IActionResult Metadata() + { + return Content(V2FeedWriter.WriteMetadata(), "application/xml; charset=utf-8"); + } - public IActionResult Metadata() - { - return Content(V2FeedWriter.WriteMetadata(), "application/xml; charset=utf-8"); - } + /// + /// Every version of one package. This is the endpoint NuGet's V2 + /// FindPackageByIdResource uses to resolve a dependency. + /// + public async Task FindPackagesById( + [FromQuery] string id, + CancellationToken cancellationToken) + { + // The id arrives as an OData string literal: id='Newtonsoft.Json'. + id = TrimLiteral(id); - /// - /// Every version of one package. This is the endpoint NuGet's V2 - /// FindPackageByIdResource uses to resolve a dependency. - /// - public async Task FindPackagesById( - [FromQuery] string id, - CancellationToken cancellationToken) + if (string.IsNullOrWhiteSpace(id)) { - // The id arrives as an OData string literal: id='Newtonsoft.Json'. - id = TrimLiteral(id); + return Feed(new List(), "FindPackagesById"); + } - if (string.IsNullOrWhiteSpace(id)) - { - return Feed(new List(), "FindPackagesById"); - } + var packages = await _packages.FindAsync(id, includeUnlisted: true, cancellationToken); - var packages = await _packages.FindAsync(id, includeUnlisted: true, cancellationToken); + return Feed(Project(packages), "FindPackagesById"); + } - return Feed(Project(packages), "FindPackagesById"); - } + /// + /// The package collection. Without a search term this lists what the feed holds. + /// + public async Task Packages( + [FromQuery] string id, + [FromQuery(Name = "$skip")] int? skip, + [FromQuery(Name = "$top")] int? top, + [FromQuery] string semVerLevel, + CancellationToken cancellationToken) + { + id = TrimLiteral(id); - /// - /// The package collection. Without a search term this lists what the feed holds. - /// - public async Task Packages( - [FromQuery] string id, - [FromQuery(Name = "$skip")] int? skip, - [FromQuery(Name = "$top")] int? top, - [FromQuery] string semVerLevel, - CancellationToken cancellationToken) + // Packages(Id='X',Version='Y') is routed here with both key values. + if (!string.IsNullOrWhiteSpace(id)) { - id = TrimLiteral(id); + var packages = await _packages.FindAsync(id, includeUnlisted: true, cancellationToken); - // Packages(Id='X',Version='Y') is routed here with both key values. - if (!string.IsNullOrWhiteSpace(id)) - { - var packages = await _packages.FindAsync(id, includeUnlisted: true, cancellationToken); - - return Feed(Project(packages), "Packages"); - } - - return await SearchFeed( - query: null, - skip: skip, - top: top, - includePrerelease: true, - semVerLevel: semVerLevel, - title: "Packages", - cancellationToken: cancellationToken); + return Feed(Project(packages), "Packages"); } - /// - /// A single package by its key. "nuget install" resolves an exact version here. - /// - public async Task PackagesByKey( - string id, - string version, - CancellationToken cancellationToken) - { - id = TrimLiteral(id); - version = TrimLiteral(version); - - if (!NuGetVersion.TryParse(version, out var parsed)) - { - return NotFound(); - } - - var package = await _packages.FindOrNullAsync(id, parsed, includeUnlisted: true, cancellationToken); - if (package == null) - { - return NotFound(); - } - - // The latest-version flags are relative to the other versions, so the whole - // set has to be projected even when only one entry is returned. - var siblings = await _packages.FindAsync(id, includeUnlisted: true, cancellationToken); - var projected = Project(siblings) - .FirstOrDefault(p => p.NormalizedVersion == parsed.ToNormalizedString()); + return await SearchFeed( + query: null, + skip: skip, + top: top, + includePrerelease: true, + semVerLevel: semVerLevel, + title: "Packages", + cancellationToken: cancellationToken); + } - if (projected == null) - { - return NotFound(); - } + /// + /// A single package by its key. "nuget install" resolves an exact version here. + /// + public async Task PackagesByKey( + string id, + string version, + CancellationToken cancellationToken) + { + id = TrimLiteral(id); + version = TrimLiteral(version); - return Content( - V2FeedWriter.WriteEntry(projected, FeedBaseUrl()), - "application/atom+xml; type=entry; charset=utf-8"); + if (!NuGetVersion.TryParse(version, out var parsed)) + { + return NotFound(); } - /// - /// The search endpoint "nuget list" calls. - /// - public async Task Search( - [FromQuery] string searchTerm, - [FromQuery(Name = "$skip")] int? skip, - [FromQuery(Name = "$top")] int? top, - [FromQuery] bool includePrerelease, - [FromQuery] string semVerLevel, - CancellationToken cancellationToken) + var package = await _packages.FindOrNullAsync(id, parsed, includeUnlisted: true, cancellationToken); + if (package == null) { - return await SearchFeed( - query: TrimLiteral(searchTerm), - skip: skip, - top: top, - includePrerelease: includePrerelease, - semVerLevel: semVerLevel, - title: "Search", - cancellationToken: cancellationToken); + return NotFound(); } - private async Task SearchFeed( - string query, - int? skip, - int? top, - bool includePrerelease, - string semVerLevel, - string title, - CancellationToken cancellationToken) + // The latest-version flags are relative to the other versions, so the whole + // set has to be projected even when only one entry is returned. + var siblings = await _packages.FindAsync(id, includeUnlisted: true, cancellationToken); + var projected = Project(siblings) + .FirstOrDefault(p => p.NormalizedVersion == parsed.ToNormalizedString()); + + if (projected == null) { - var take = Math.Clamp(top ?? DefaultPageSize, 1, MaxPageSize); - var offset = Math.Max(skip ?? 0, 0); - - var response = await _search.SearchAsync( - new SearchRequest - { - Skip = offset, - Take = take, - IncludePrerelease = includePrerelease, - IncludeSemVer2 = IsSemVer2(semVerLevel), - Query = query, - }, - cancellationToken); - - // Search returns one result per package id, each carrying its versions. V2 - // lists one entry per version, so the ids are re-read to get full metadata. - var result = new List(); - - foreach (var match in response.Data) - { - var packages = await _packages.FindAsync(match.PackageId, includeUnlisted: false, cancellationToken); + return NotFound(); + } - result.AddRange(Project(packages)); - } + return Content( + V2FeedWriter.WriteEntry(projected, FeedBaseUrl()), + "application/atom+xml; type=entry; charset=utf-8"); + } - return Feed(result, title); - } + /// + /// The search endpoint "nuget list" calls. + /// + public async Task Search( + [FromQuery] string searchTerm, + [FromQuery(Name = "$skip")] int? skip, + [FromQuery(Name = "$top")] int? top, + [FromQuery] bool includePrerelease, + [FromQuery] string semVerLevel, + CancellationToken cancellationToken) + { + return await SearchFeed( + query: TrimLiteral(searchTerm), + skip: skip, + top: top, + includePrerelease: includePrerelease, + semVerLevel: semVerLevel, + title: "Search", + cancellationToken: cancellationToken); + } - private List Project(IEnumerable packages) - { - return V2FeedPackage.FromPackages( - packages, - p => _url.GetPackageDownloadUrl(p.Id, p.Version)); - } + private async Task SearchFeed( + string query, + int? skip, + int? top, + bool includePrerelease, + string semVerLevel, + string title, + CancellationToken cancellationToken) + { + var take = Math.Clamp(top ?? DefaultPageSize, 1, MaxPageSize); + var offset = Math.Max(skip ?? 0, 0); - private IActionResult Feed(IReadOnlyList packages, string title) + var response = await _search.SearchAsync( + new SearchRequest + { + Skip = offset, + Take = take, + IncludePrerelease = includePrerelease, + IncludeSemVer2 = IsSemVer2(semVerLevel), + Query = query, + }, + cancellationToken); + + // Search returns one result per package id, each carrying its versions. V2 + // lists one entry per version, so the ids are re-read to get full metadata. + var result = new List(); + + foreach (var match in response.Data) { - var baseUrl = FeedBaseUrl(); - var selfUrl = baseUrl.TrimEnd('/') + "/" + title; - - // The feed's own timestamp is the newest package it contains, so the document - // is stable for the same content rather than changing on every request. - var updated = packages.Count == 0 - ? DateTime.UnixEpoch - : packages.Max(p => p.LastUpdated); - - var document = V2FeedWriter.WriteFeed( - packages, - feedId: selfUrl, - feedTitle: title, - selfUrl: selfUrl, - baseUrl: baseUrl, - updated: updated); - - return Content(document, "application/atom+xml; type=feed; charset=utf-8"); + var packages = await _packages.FindAsync(match.PackageId, includeUnlisted: false, cancellationToken); + + result.AddRange(Project(packages)); } - private string FeedBaseUrl() - { - var request = HttpContext.Request; + return Feed(result, title); + } - return request.Scheme - + "://" - + request.Host.ToUriComponent() - + request.PathBase.ToUriComponent() - + "/api/v2"; - } + private List Project(IEnumerable packages) + { + return V2FeedPackage.FromPackages( + packages, + p => _url.GetPackageDownloadUrl(p.Id, p.Version)); + } - /// - /// Strip the single quotes around an OData string literal. A client may send - /// id='X' or a bare X, and both have to work. - /// - internal static string TrimLiteral(string value) - { - if (string.IsNullOrEmpty(value)) return value; + private IActionResult Feed(IReadOnlyList packages, string title) + { + var baseUrl = FeedBaseUrl(); + var selfUrl = baseUrl.TrimEnd('/') + "/" + title; + + // The feed's own timestamp is the newest package it contains, so the document + // is stable for the same content rather than changing on every request. + var updated = packages.Count == 0 + ? DateTime.UnixEpoch + : packages.Max(p => p.LastUpdated); + + var document = V2FeedWriter.WriteFeed( + packages, + feedId: selfUrl, + feedTitle: title, + selfUrl: selfUrl, + baseUrl: baseUrl, + updated: updated); + + return Content(document, "application/atom+xml; type=feed; charset=utf-8"); + } - var trimmed = value.Trim(); + private string FeedBaseUrl() + { + var request = HttpContext.Request; - if (trimmed.Length >= 2 && trimmed[0] == '\'' && trimmed[trimmed.Length - 1] == '\'') - { - // An OData literal escapes an embedded quote by doubling it. - return trimmed.Substring(1, trimmed.Length - 2).Replace("''", "'"); - } + return request.Scheme + + "://" + + request.Host.ToUriComponent() + + request.PathBase.ToUriComponent() + + "/api/v2"; + } - return trimmed; - } + /// + /// Strip the single quotes around an OData string literal. A client may send + /// id='X' or a bare X, and both have to work. + /// + internal static string TrimLiteral(string value) + { + if (string.IsNullOrEmpty(value)) return value; + + var trimmed = value.Trim(); - private static bool IsSemVer2(string semVerLevel) + if (trimmed.Length >= 2 && trimmed[0] == '\'' && trimmed[trimmed.Length - 1] == '\'') { - return NuGetVersion.TryParse(semVerLevel, out var version) && version.Major >= 2; + // An OData literal escapes an embedded quote by doubling it. + return trimmed.Substring(1, trimmed.Length - 2).Replace("''", "'"); } + + return trimmed; + } + + private static bool IsSemVer2(string semVerLevel) + { + return NuGetVersion.TryParse(semVerLevel, out var version) && version.Major >= 2; } -} +} \ No newline at end of file diff --git a/src/BaGet.Web.V2/V2FeedPackage.cs b/src/BaGet.Web.V2/V2FeedPackage.cs index aae748005..2f3c5019c 100644 --- a/src/BaGet.Web.V2/V2FeedPackage.cs +++ b/src/BaGet.Web.V2/V2FeedPackage.cs @@ -3,107 +3,106 @@ using System.Linq; using BaGet.Core; -namespace BaGet.Web.V2 +namespace BaGet.Web.V2; + +/// +/// A package as the V2 protocol describes it. The V2 entity carries a flatter set of +/// properties than , and some of them - "IsLatestVersion" above +/// all - only have an answer in the context of the other versions returned alongside. +/// +internal class V2FeedPackage { + public string Id { get; set; } + public string Version { get; set; } + public string NormalizedVersion { get; set; } + public string Authors { get; set; } + public string Description { get; set; } + public string Summary { get; set; } + public string Title { get; set; } + public string Tags { get; set; } + public string Language { get; set; } + public string ReleaseNotes { get; set; } + public string MinClientVersion { get; set; } + public string Dependencies { get; set; } + public string IconUrl { get; set; } + public string LicenseUrl { get; set; } + public string ProjectUrl { get; set; } + public long DownloadCount { get; set; } + public bool RequireLicenseAcceptance { get; set; } + public bool Listed { get; set; } + public bool IsPrerelease { get; set; } + public bool IsLatestVersion { get; set; } + public bool IsAbsoluteLatestVersion { get; set; } + public DateTime Published { get; set; } + public DateTime LastUpdated { get; set; } + public string DownloadUrl { get; set; } + /// - /// A package as the V2 protocol describes it. The V2 entity carries a flatter set of - /// properties than , and some of them - "IsLatestVersion" above - /// all - only have an answer in the context of the other versions returned alongside. + /// Project a set of versions of one package. The whole set is needed at once + /// because the latest-version flags are relative to it. /// - internal class V2FeedPackage + public static List FromPackages( + IEnumerable packages, + Func downloadUrl) { - public string Id { get; set; } - public string Version { get; set; } - public string NormalizedVersion { get; set; } - public string Authors { get; set; } - public string Description { get; set; } - public string Summary { get; set; } - public string Title { get; set; } - public string Tags { get; set; } - public string Language { get; set; } - public string ReleaseNotes { get; set; } - public string MinClientVersion { get; set; } - public string Dependencies { get; set; } - public string IconUrl { get; set; } - public string LicenseUrl { get; set; } - public string ProjectUrl { get; set; } - public long DownloadCount { get; set; } - public bool RequireLicenseAcceptance { get; set; } - public bool Listed { get; set; } - public bool IsPrerelease { get; set; } - public bool IsLatestVersion { get; set; } - public bool IsAbsoluteLatestVersion { get; set; } - public DateTime Published { get; set; } - public DateTime LastUpdated { get; set; } - public string DownloadUrl { get; set; } - - /// - /// Project a set of versions of one package. The whole set is needed at once - /// because the latest-version flags are relative to it. - /// - public static List FromPackages( - IEnumerable packages, - Func downloadUrl) - { - var ordered = packages - .OrderByDescending(p => p.Version) - .ToList(); + var ordered = packages + .OrderByDescending(p => p.Version) + .ToList(); - // "IsAbsoluteLatestVersion" is the newest version of all; "IsLatestVersion" - // is the newest stable one. An id with only prereleases has no latest version. - var absoluteLatest = ordered.FirstOrDefault(p => p.Listed); - var latest = ordered.FirstOrDefault(p => p.Listed && !p.IsPrerelease); + // "IsAbsoluteLatestVersion" is the newest version of all; "IsLatestVersion" + // is the newest stable one. An id with only prereleases has no latest version. + var absoluteLatest = ordered.FirstOrDefault(p => p.Listed); + var latest = ordered.FirstOrDefault(p => p.Listed && !p.IsPrerelease); - return ordered - .Select(p => FromPackage(p, downloadUrl(p), ReferenceEquals(p, latest), ReferenceEquals(p, absoluteLatest))) - .ToList(); - } + return ordered + .Select(p => FromPackage(p, downloadUrl(p), ReferenceEquals(p, latest), ReferenceEquals(p, absoluteLatest))) + .ToList(); + } - private static V2FeedPackage FromPackage( - Package package, - string downloadUrl, - bool isLatestVersion, - bool isAbsoluteLatestVersion) + private static V2FeedPackage FromPackage( + Package package, + string downloadUrl, + bool isLatestVersion, + bool isAbsoluteLatestVersion) + { + return new V2FeedPackage { - return new V2FeedPackage - { - Id = package.Id, - Version = package.OriginalVersionString ?? package.NormalizedVersionString, - NormalizedVersion = package.NormalizedVersionString, - Authors = string.Join(", ", package.Authors ?? Array.Empty()), - Description = package.Description ?? string.Empty, - Summary = package.Summary ?? string.Empty, - Title = package.Title ?? string.Empty, - Tags = string.Join(" ", package.Tags ?? Array.Empty()), - Language = package.Language ?? string.Empty, - ReleaseNotes = package.ReleaseNotes ?? string.Empty, - MinClientVersion = package.MinClientVersion ?? string.Empty, - Dependencies = FormatDependencies(package.Dependencies), - IconUrl = package.IconUrlString ?? string.Empty, - LicenseUrl = package.LicenseUrlString ?? string.Empty, - ProjectUrl = package.ProjectUrlString ?? string.Empty, - DownloadCount = package.Downloads, - RequireLicenseAcceptance = package.RequireLicenseAcceptance, - Listed = package.Listed, - IsPrerelease = package.IsPrerelease, - IsLatestVersion = isLatestVersion, - IsAbsoluteLatestVersion = isAbsoluteLatestVersion, - Published = package.Published, - LastUpdated = package.Published, - DownloadUrl = downloadUrl, - }; - } + Id = package.Id, + Version = package.OriginalVersionString ?? package.NormalizedVersionString, + NormalizedVersion = package.NormalizedVersionString, + Authors = string.Join(", ", package.Authors ?? Array.Empty()), + Description = package.Description ?? string.Empty, + Summary = package.Summary ?? string.Empty, + Title = package.Title ?? string.Empty, + Tags = string.Join(" ", package.Tags ?? Array.Empty()), + Language = package.Language ?? string.Empty, + ReleaseNotes = package.ReleaseNotes ?? string.Empty, + MinClientVersion = package.MinClientVersion ?? string.Empty, + Dependencies = FormatDependencies(package.Dependencies), + IconUrl = package.IconUrlString ?? string.Empty, + LicenseUrl = package.LicenseUrlString ?? string.Empty, + ProjectUrl = package.ProjectUrlString ?? string.Empty, + DownloadCount = package.Downloads, + RequireLicenseAcceptance = package.RequireLicenseAcceptance, + Listed = package.Listed, + IsPrerelease = package.IsPrerelease, + IsLatestVersion = isLatestVersion, + IsAbsoluteLatestVersion = isAbsoluteLatestVersion, + Published = package.Published, + LastUpdated = package.Published, + DownloadUrl = downloadUrl, + }; + } - /// - /// V2 flattens dependencies into one string: groups separated by "|", each entry - /// "id:range:framework". A group with no packages contributes "::framework". - /// - internal static string FormatDependencies(IEnumerable dependencies) - { - if (dependencies == null) return string.Empty; + /// + /// V2 flattens dependencies into one string: groups separated by "|", each entry + /// "id:range:framework". A group with no packages contributes "::framework". + /// + internal static string FormatDependencies(IEnumerable dependencies) + { + if (dependencies == null) return string.Empty; - return string.Join("|", dependencies.Select(d => - $"{d.Id}:{d.VersionRange}:{d.TargetFramework}")); - } + return string.Join("|", dependencies.Select(d => + $"{d.Id}:{d.VersionRange}:{d.TargetFramework}")); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web.V2/V2FeedWriter.cs b/src/BaGet.Web.V2/V2FeedWriter.cs index c381c9df0..e6a211014 100644 --- a/src/BaGet.Web.V2/V2FeedWriter.cs +++ b/src/BaGet.Web.V2/V2FeedWriter.cs @@ -6,261 +6,260 @@ using System.Xml; using System.Xml.Linq; -namespace BaGet.Web.V2 +namespace BaGet.Web.V2; + +/// +/// Writes the Atom documents the NuGet V2 protocol is built on. +/// +/// +/// Written by hand rather than with an OData library: only a handful of endpoints are +/// needed and the shape is fixed. The cost is that the OData query options are not +/// interpreted - see . +/// +internal static class V2FeedWriter { + private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom"; + private static readonly XNamespace DataServices = "http://schemas.microsoft.com/ado/2007/08/dataservices"; + private static readonly XNamespace Metadata = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; + private static readonly XNamespace Edm = "http://schemas.microsoft.com/ado/2009/11/edm"; + private static readonly XNamespace Edmx = "http://schemas.microsoft.com/ado/2007/06/edmx"; + /// - /// Writes the Atom documents the NuGet V2 protocol is built on. + /// The properties the feed publishes, with their EDM types. One list drives both the + /// metadata document and the entries, so the two cannot drift apart. /// - /// - /// Written by hand rather than with an OData library: only a handful of endpoints are - /// needed and the shape is fixed. The cost is that the OData query options are not - /// interpreted - see . - /// - internal static class V2FeedWriter + private static readonly (string Name, string Type, bool Nullable)[] Properties = { - private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom"; - private static readonly XNamespace DataServices = "http://schemas.microsoft.com/ado/2007/08/dataservices"; - private static readonly XNamespace Metadata = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; - private static readonly XNamespace Edm = "http://schemas.microsoft.com/ado/2009/11/edm"; - private static readonly XNamespace Edmx = "http://schemas.microsoft.com/ado/2007/06/edmx"; + ("Version", "Edm.String", false), + ("NormalizedVersion", "Edm.String", true), + ("Authors", "Edm.String", true), + ("Description", "Edm.String", true), + ("Summary", "Edm.String", true), + ("Title", "Edm.String", true), + ("Tags", "Edm.String", true), + ("Language", "Edm.String", true), + ("ReleaseNotes", "Edm.String", true), + ("MinClientVersion", "Edm.String", true), + ("Dependencies", "Edm.String", true), + ("IconUrl", "Edm.String", true), + ("LicenseUrl", "Edm.String", true), + ("ProjectUrl", "Edm.String", true), + ("DownloadCount", "Edm.Int64", false), + ("RequireLicenseAcceptance", "Edm.Boolean", false), + ("Listed", "Edm.Boolean", false), + ("IsPrerelease", "Edm.Boolean", false), + ("IsLatestVersion", "Edm.Boolean", false), + ("IsAbsoluteLatestVersion", "Edm.Boolean", false), + ("Published", "Edm.DateTime", false), + ("LastUpdated", "Edm.DateTime", false), + }; - /// - /// The properties the feed publishes, with their EDM types. One list drives both the - /// metadata document and the entries, so the two cannot drift apart. - /// - private static readonly (string Name, string Type, bool Nullable)[] Properties = - { - ("Version", "Edm.String", false), - ("NormalizedVersion", "Edm.String", true), - ("Authors", "Edm.String", true), - ("Description", "Edm.String", true), - ("Summary", "Edm.String", true), - ("Title", "Edm.String", true), - ("Tags", "Edm.String", true), - ("Language", "Edm.String", true), - ("ReleaseNotes", "Edm.String", true), - ("MinClientVersion", "Edm.String", true), - ("Dependencies", "Edm.String", true), - ("IconUrl", "Edm.String", true), - ("LicenseUrl", "Edm.String", true), - ("ProjectUrl", "Edm.String", true), - ("DownloadCount", "Edm.Int64", false), - ("RequireLicenseAcceptance", "Edm.Boolean", false), - ("Listed", "Edm.Boolean", false), - ("IsPrerelease", "Edm.Boolean", false), - ("IsLatestVersion", "Edm.Boolean", false), - ("IsAbsoluteLatestVersion", "Edm.Boolean", false), - ("Published", "Edm.DateTime", false), - ("LastUpdated", "Edm.DateTime", false), - }; + public static string WriteMetadata() + { + var entityType = new XElement( + Edm + "EntityType", + new XAttribute("Name", "V2FeedPackage"), + new XElement( + Edm + "Key", + new XElement(Edm + "PropertyRef", new XAttribute("Name", "Id")), + new XElement(Edm + "PropertyRef", new XAttribute("Name", "Version"))), + new XElement( + Edm + "Property", + new XAttribute("Name", "Id"), + new XAttribute("Type", "Edm.String"), + new XAttribute("Nullable", "false"))); - public static string WriteMetadata() + foreach (var (name, type, nullable) in Properties) { - var entityType = new XElement( - Edm + "EntityType", - new XAttribute("Name", "V2FeedPackage"), - new XElement( - Edm + "Key", - new XElement(Edm + "PropertyRef", new XAttribute("Name", "Id")), - new XElement(Edm + "PropertyRef", new XAttribute("Name", "Version"))), - new XElement( - Edm + "Property", - new XAttribute("Name", "Id"), - new XAttribute("Type", "Edm.String"), - new XAttribute("Nullable", "false"))); - - foreach (var (name, type, nullable) in Properties) - { - // Version is part of the key, so it is never nullable. - var isNullable = name != "Version" && nullable; + // Version is part of the key, so it is never nullable. + var isNullable = name != "Version" && nullable; - entityType.Add(new XElement( - Edm + "Property", - new XAttribute("Name", name), - new XAttribute("Type", type), - new XAttribute("Nullable", isNullable ? "true" : "false"))); - } + entityType.Add(new XElement( + Edm + "Property", + new XAttribute("Name", name), + new XAttribute("Type", type), + new XAttribute("Nullable", isNullable ? "true" : "false"))); + } - var document = new XDocument( + var document = new XDocument( + new XElement( + Edmx + "Edmx", + new XAttribute("Version", "1.0"), + new XAttribute(XNamespace.Xmlns + "edmx", Edmx.NamespaceName), new XElement( - Edmx + "Edmx", - new XAttribute("Version", "1.0"), - new XAttribute(XNamespace.Xmlns + "edmx", Edmx.NamespaceName), + Edmx + "DataServices", + new XAttribute(Metadata + "DataServiceVersion", "2.0"), + new XAttribute(Metadata + "MaxDataServiceVersion", "3.0"), + new XAttribute(XNamespace.Xmlns + "m", Metadata.NamespaceName), new XElement( - Edmx + "DataServices", - new XAttribute(Metadata + "DataServiceVersion", "2.0"), - new XAttribute(Metadata + "MaxDataServiceVersion", "3.0"), - new XAttribute(XNamespace.Xmlns + "m", Metadata.NamespaceName), + Edm + "Schema", + new XAttribute("Namespace", "NuGetGallery"), + entityType, new XElement( - Edm + "Schema", - new XAttribute("Namespace", "NuGetGallery"), - entityType, + Edm + "EntityContainer", + new XAttribute("Name", "V2FeedContext"), + new XAttribute(Metadata + "IsDefaultEntityContainer", "true"), new XElement( - Edm + "EntityContainer", - new XAttribute("Name", "V2FeedContext"), - new XAttribute(Metadata + "IsDefaultEntityContainer", "true"), - new XElement( - Edm + "EntitySet", - new XAttribute("Name", "Packages"), - new XAttribute("EntityType", "NuGetGallery.V2FeedPackage"))))))); + Edm + "EntitySet", + new XAttribute("Name", "Packages"), + new XAttribute("EntityType", "NuGetGallery.V2FeedPackage"))))))); - return Serialize(document); + return Serialize(document); + } + + public static string WriteFeed( + IReadOnlyList packages, + string feedId, + string feedTitle, + string selfUrl, + string baseUrl, + DateTime updated, + string nextUrl = null) + { + var feed = new XElement( + Atom + "feed", + new XAttribute(XNamespace.Xml + "base", baseUrl), + new XAttribute(XNamespace.Xmlns + "d", DataServices.NamespaceName), + new XAttribute(XNamespace.Xmlns + "m", Metadata.NamespaceName), + new XElement(Atom + "id", feedId), + new XElement(Atom + "title", new XAttribute("type", "text"), feedTitle), + new XElement(Atom + "updated", Timestamp(updated)), + new XElement( + Atom + "link", + new XAttribute("rel", "self"), + new XAttribute("href", selfUrl))); + + foreach (var package in packages) + { + feed.Add(WriteEntryElement(package, baseUrl)); } - public static string WriteFeed( - IReadOnlyList packages, - string feedId, - string feedTitle, - string selfUrl, - string baseUrl, - DateTime updated, - string nextUrl = null) + // A "next" link is how V2 pages: a client follows it until it is absent. + if (!string.IsNullOrEmpty(nextUrl)) { - var feed = new XElement( - Atom + "feed", - new XAttribute(XNamespace.Xml + "base", baseUrl), - new XAttribute(XNamespace.Xmlns + "d", DataServices.NamespaceName), - new XAttribute(XNamespace.Xmlns + "m", Metadata.NamespaceName), - new XElement(Atom + "id", feedId), - new XElement(Atom + "title", new XAttribute("type", "text"), feedTitle), - new XElement(Atom + "updated", Timestamp(updated)), - new XElement( - Atom + "link", - new XAttribute("rel", "self"), - new XAttribute("href", selfUrl))); + feed.Add(new XElement( + Atom + "link", + new XAttribute("rel", "next"), + new XAttribute("href", nextUrl))); + } - foreach (var package in packages) - { - feed.Add(WriteEntryElement(package, baseUrl)); - } + return Serialize(new XDocument(feed)); + } - // A "next" link is how V2 pages: a client follows it until it is absent. - if (!string.IsNullOrEmpty(nextUrl)) - { - feed.Add(new XElement( - Atom + "link", - new XAttribute("rel", "next"), - new XAttribute("href", nextUrl))); - } + public static string WriteEntry(V2FeedPackage package, string baseUrl) + { + var entry = WriteEntryElement(package, baseUrl); - return Serialize(new XDocument(feed)); - } + entry.Add(new XAttribute(XNamespace.Xml + "base", baseUrl)); + entry.Add(new XAttribute(XNamespace.Xmlns + "d", DataServices.NamespaceName)); + entry.Add(new XAttribute(XNamespace.Xmlns + "m", Metadata.NamespaceName)); - public static string WriteEntry(V2FeedPackage package, string baseUrl) - { - var entry = WriteEntryElement(package, baseUrl); + return Serialize(new XDocument(entry)); + } - entry.Add(new XAttribute(XNamespace.Xml + "base", baseUrl)); - entry.Add(new XAttribute(XNamespace.Xmlns + "d", DataServices.NamespaceName)); - entry.Add(new XAttribute(XNamespace.Xmlns + "m", Metadata.NamespaceName)); + private static XElement WriteEntryElement(V2FeedPackage package, string baseUrl) + { + var properties = new XElement(Metadata + "properties"); - return Serialize(new XDocument(entry)); + foreach (var (name, type, _) in Properties) + { + properties.Add(Property(name, type, Value(package, name))); } - private static XElement WriteEntryElement(V2FeedPackage package, string baseUrl) - { - var properties = new XElement(Metadata + "properties"); + return new XElement( + Atom + "entry", + new XElement(Atom + "id", EntityId(baseUrl, package)), + new XElement(Atom + "title", new XAttribute("type", "text"), package.Id), + new XElement(Atom + "summary", new XAttribute("type", "text"), package.Summary ?? string.Empty), + new XElement(Atom + "updated", Timestamp(package.LastUpdated)), + new XElement(Atom + "author", new XElement(Atom + "name", package.Authors ?? string.Empty)), + new XElement( + Atom + "content", + new XAttribute("type", "application/zip"), + new XAttribute("src", package.DownloadUrl)), + new XElement( + Atom + "category", + new XAttribute("term", "NuGetGallery.V2FeedPackage"), + new XAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme")), + properties); + } - foreach (var (name, type, _) in Properties) - { - properties.Add(Property(name, type, Value(package, name))); - } + /// + /// The V2 key is (Id, Version), written as OData key literals. + /// + internal static string EntityId(string baseUrl, V2FeedPackage package) + { + return baseUrl.TrimEnd('/') + + "/Packages(Id='" + package.Id + "',Version='" + package.Version + "')"; + } - return new XElement( - Atom + "entry", - new XElement(Atom + "id", EntityId(baseUrl, package)), - new XElement(Atom + "title", new XAttribute("type", "text"), package.Id), - new XElement(Atom + "summary", new XAttribute("type", "text"), package.Summary ?? string.Empty), - new XElement(Atom + "updated", Timestamp(package.LastUpdated)), - new XElement(Atom + "author", new XElement(Atom + "name", package.Authors ?? string.Empty)), - new XElement( - Atom + "content", - new XAttribute("type", "application/zip"), - new XAttribute("src", package.DownloadUrl)), - new XElement( - Atom + "category", - new XAttribute("term", "NuGetGallery.V2FeedPackage"), - new XAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme")), - properties); - } + private static XElement Property(string name, string type, string value) + { + var element = new XElement(DataServices + name); - /// - /// The V2 key is (Id, Version), written as OData key literals. - /// - internal static string EntityId(string baseUrl, V2FeedPackage package) + if (type != "Edm.String") { - return baseUrl.TrimEnd('/') - + "/Packages(Id='" + package.Id + "',Version='" + package.Version + "')"; + element.Add(new XAttribute(Metadata + "type", type)); } - private static XElement Property(string name, string type, string value) - { - var element = new XElement(DataServices + name); + element.Add(value); - if (type != "Edm.String") - { - element.Add(new XAttribute(Metadata + "type", type)); - } + return element; + } - element.Add(value); + private static string Value(V2FeedPackage p, string name) => name switch + { + "Version" => p.Version, + "NormalizedVersion" => p.NormalizedVersion, + "Authors" => p.Authors, + "Description" => p.Description, + "Summary" => p.Summary, + "Title" => p.Title, + "Tags" => p.Tags, + "Language" => p.Language, + "ReleaseNotes" => p.ReleaseNotes, + "MinClientVersion" => p.MinClientVersion, + "Dependencies" => p.Dependencies, + "IconUrl" => p.IconUrl, + "LicenseUrl" => p.LicenseUrl, + "ProjectUrl" => p.ProjectUrl, + "DownloadCount" => p.DownloadCount.ToString(CultureInfo.InvariantCulture), + "RequireLicenseAcceptance" => Boolean(p.RequireLicenseAcceptance), + "Listed" => Boolean(p.Listed), + "IsPrerelease" => Boolean(p.IsPrerelease), + "IsLatestVersion" => Boolean(p.IsLatestVersion), + "IsAbsoluteLatestVersion" => Boolean(p.IsAbsoluteLatestVersion), + "Published" => Timestamp(p.Published), + "LastUpdated" => Timestamp(p.LastUpdated), + _ => throw new ArgumentOutOfRangeException(nameof(name), name, "Unknown feed property."), + }; - return element; - } + private static string Boolean(bool value) => value ? "true" : "false"; + + private static string Timestamp(DateTime value) + { + // Edm.DateTime carries no offset, so the value has to already be UTC. + return value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture); + } - private static string Value(V2FeedPackage p, string name) => name switch + private static string Serialize(XDocument document) + { + // The declaration is written by hand. Saving to a TextWriter makes XDocument + // declare that writer's encoding - utf-16 for a StringWriter - which then + // contradicts the utf-8 the response is actually sent as, and a real + // XmlReader rejects the document with "There is no Unicode byte order mark". + var builder = new StringBuilder(); + var settings = new XmlWriterSettings { - "Version" => p.Version, - "NormalizedVersion" => p.NormalizedVersion, - "Authors" => p.Authors, - "Description" => p.Description, - "Summary" => p.Summary, - "Title" => p.Title, - "Tags" => p.Tags, - "Language" => p.Language, - "ReleaseNotes" => p.ReleaseNotes, - "MinClientVersion" => p.MinClientVersion, - "Dependencies" => p.Dependencies, - "IconUrl" => p.IconUrl, - "LicenseUrl" => p.LicenseUrl, - "ProjectUrl" => p.ProjectUrl, - "DownloadCount" => p.DownloadCount.ToString(CultureInfo.InvariantCulture), - "RequireLicenseAcceptance" => Boolean(p.RequireLicenseAcceptance), - "Listed" => Boolean(p.Listed), - "IsPrerelease" => Boolean(p.IsPrerelease), - "IsLatestVersion" => Boolean(p.IsLatestVersion), - "IsAbsoluteLatestVersion" => Boolean(p.IsAbsoluteLatestVersion), - "Published" => Timestamp(p.Published), - "LastUpdated" => Timestamp(p.LastUpdated), - _ => throw new ArgumentOutOfRangeException(nameof(name), name, "Unknown feed property."), + OmitXmlDeclaration = true, + Indent = false, }; - private static string Boolean(bool value) => value ? "true" : "false"; - - private static string Timestamp(DateTime value) + using (var writer = XmlWriter.Create(builder, settings)) { - // Edm.DateTime carries no offset, so the value has to already be UTC. - return value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture); + document.Save(writer); } - private static string Serialize(XDocument document) - { - // The declaration is written by hand. Saving to a TextWriter makes XDocument - // declare that writer's encoding - utf-16 for a StringWriter - which then - // contradicts the utf-8 the response is actually sent as, and a real - // XmlReader rejects the document with "There is no Unicode byte order mark". - var builder = new StringBuilder(); - var settings = new XmlWriterSettings - { - OmitXmlDeclaration = true, - Indent = false, - }; - - using (var writer = XmlWriter.Create(builder, settings)) - { - document.Save(writer); - } - - return "" + builder.ToString(); - } + return "" + builder.ToString(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/BaGetEndpointBuilder.cs b/src/BaGet.Web/BaGetEndpointBuilder.cs index 31e76d06a..5cf54fb5e 100644 --- a/src/BaGet.Web/BaGetEndpointBuilder.cs +++ b/src/BaGet.Web/BaGetEndpointBuilder.cs @@ -4,261 +4,260 @@ using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Constraints; -namespace BaGet +namespace BaGet; + +public class BaGetEndpointBuilder { - public class BaGetEndpointBuilder + public void MapEndpoints(IEndpointRouteBuilder endpoints) + { + endpoints.MapRazorPages(); + + MapServiceIndexRoutes(endpoints); + MapPackagePublishRoutes(endpoints); + MapSymbolRoutes(endpoints); + MapSearchRoutes(endpoints); + MapPackageMetadataRoutes(endpoints); + MapPackageContentRoutes(endpoints); + MapV2FeedRoutes(endpoints); + MapPackageMetadataAdminRoutes(endpoints); + MapVulnerabilityRoutes(endpoints); + MapCatalogRoutes(endpoints); + MapValidationRoutes(endpoints); + } + + /// + /// Deprecation and vulnerability metadata for a package version. Writes only, so they + /// share the authorisation of the publish endpoints. + /// + public void MapPackageMetadataAdminRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.SetDeprecationRouteName, + pattern: "v3/package/{id}/{version}/deprecation", + defaults: new { controller = "PackageMetadataAdmin", action = "SetDeprecation" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); + + endpoints.MapControllerRoute( + name: Routes.RemoveDeprecationRouteName, + pattern: "v3/package/{id}/{version}/deprecation", + defaults: new { controller = "PackageMetadataAdmin", action = "RemoveDeprecation" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("DELETE") }); + + endpoints.MapControllerRoute( + name: Routes.SetVulnerabilitiesRouteName, + pattern: "v3/package/{id}/{version}/vulnerabilities", + defaults: new { controller = "PackageMetadataAdmin", action = "SetVulnerabilities" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); + } + + public void MapValidationRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.RepositorySignaturesRouteName, + pattern: "v3/repository-signatures/index.json", + defaults: new { controller = "RepositorySignatures", action = "Index" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.RepositorySigningCertificateRouteName, + pattern: "v3/repository-signatures/{fingerprint}.crt", + defaults: new { controller = "RepositorySignatures", action = "Certificate" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.ValidationStatusRouteName, + pattern: "v3/package/{id}/{version}/validation", + defaults: new { controller = "ValidationStatus", action = "Get" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + } + + public void MapCatalogRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.CatalogIndexRouteName, + pattern: "v3/catalog/index.json", + defaults: new { controller = "Catalog", action = "Index" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.CatalogPageRouteName, + pattern: "v3/catalog/page{pageIndex:int}.json", + defaults: new { controller = "Catalog", action = "Page" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.CatalogLeafRouteName, + pattern: "v3/catalog/data/{commitId}.json", + defaults: new { controller = "Catalog", action = "Leaf" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + } + + public void MapVulnerabilityRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.VulnerabilityIndexRouteName, + pattern: "v3/vulnerabilities/index.json", + defaults: new { controller = "Vulnerability", action = "Index" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.VulnerabilityPageRouteName, + pattern: "v3/vulnerabilities/{pageName}.json", + defaults: new { controller = "Vulnerability", action = "Page" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + } + + /// + /// The V2 (OData) feed. The routes are always mapped; the controller itself + /// answers 404 for every action when "Feeds:EnableV2" is off, so turning the feed + /// off does not change which routes exist. + /// + public void MapV2FeedRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.V2RootRouteName, + pattern: "api/v2", + defaults: new { controller = "V2Feed", action = "Root" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.V2MetadataRouteName, + pattern: "api/v2/$metadata", + defaults: new { controller = "V2Feed", action = "Metadata" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.V2FindPackagesByIdRouteName, + pattern: "api/v2/FindPackagesById()", + defaults: new { controller = "V2Feed", action = "FindPackagesById" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.V2SearchRouteName, + pattern: "api/v2/Search()", + defaults: new { controller = "V2Feed", action = "Search" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + // The keyed form carries its values inside the segment, so it is matched by a + // literal pattern per argument order rather than by route values. + endpoints.MapControllerRoute( + name: Routes.V2PackagesByKeyRouteName, + pattern: "api/v2/Packages(Id={id},Version={version})", + defaults: new { controller = "V2Feed", action = "PackagesByKey" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + + endpoints.MapControllerRoute( + name: Routes.V2PackagesRouteName, + pattern: "api/v2/Packages()", + defaults: new { controller = "V2Feed", action = "Packages" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); + } + + public void MapServiceIndexRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.IndexRouteName, + pattern: "v3/index.json", + defaults: new { controller = "ServiceIndex", action = "Get" }); + } + + public void MapPackagePublishRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.UploadPackageRouteName, + pattern: "api/v2/package", + defaults: new { controller = "PackagePublish", action = "Upload" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); + + endpoints.MapControllerRoute( + name: Routes.DeleteRouteName, + pattern: "api/v2/package/{id}/{version}", + defaults: new { controller = "PackagePublish", action = "Delete" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("DELETE") }); + + endpoints.MapControllerRoute( + name: Routes.RelistRouteName, + pattern: "api/v2/package/{id}/{version}", + defaults: new { controller = "PackagePublish", action = "Relist" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("POST") }); + } + + public void MapSymbolRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.UploadSymbolRouteName, + pattern: "api/v2/symbol", + defaults: new { controller = "Symbol", action = "Upload" }, + constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); + + endpoints.MapControllerRoute( + name: Routes.SymbolDownloadRouteName, + pattern: "api/download/symbols/{file}/{key}/{file2}", + defaults: new { controller = "Symbol", action = "Get" }); + + endpoints.MapControllerRoute( + name: Routes.PrefixedSymbolDownloadRouteName, + pattern: "api/download/symbols/{prefix}/{file}/{key}/{file2}", + defaults: new { controller = "Symbol", action = "Get" }); + } + + public void MapSearchRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.SearchRouteName, + pattern: "v3/search", + defaults: new { controller = "Search", action = "Search" }); + + endpoints.MapControllerRoute( + name: Routes.AutocompleteRouteName, + pattern: "v3/autocomplete", + defaults: new { controller = "Search", action = "Autocomplete" }); + + // This is an unofficial API to find packages that depend on a given package. + endpoints.MapControllerRoute( + name: Routes.DependentsRouteName, + pattern: "v3/dependents", + defaults: new { controller = "Search", action = "Dependents" }); + } + + public void MapPackageMetadataRoutes(IEndpointRouteBuilder endpoints) + { + endpoints.MapControllerRoute( + name: Routes.RegistrationIndexRouteName, + pattern: "v3/registration/{id}/index.json", + defaults: new { controller = "PackageMetadata", action = "RegistrationIndex" }); + + endpoints.MapControllerRoute( + name: Routes.RegistrationLeafRouteName, + pattern: "v3/registration/{id}/{version}.json", + defaults: new { controller = "PackageMetadata", action = "RegistrationLeaf" }); + } + + public void MapPackageContentRoutes(IEndpointRouteBuilder endpoints) { - public void MapEndpoints(IEndpointRouteBuilder endpoints) - { - endpoints.MapRazorPages(); - - MapServiceIndexRoutes(endpoints); - MapPackagePublishRoutes(endpoints); - MapSymbolRoutes(endpoints); - MapSearchRoutes(endpoints); - MapPackageMetadataRoutes(endpoints); - MapPackageContentRoutes(endpoints); - MapV2FeedRoutes(endpoints); - MapPackageMetadataAdminRoutes(endpoints); - MapVulnerabilityRoutes(endpoints); - MapCatalogRoutes(endpoints); - MapValidationRoutes(endpoints); - } - - /// - /// Deprecation and vulnerability metadata for a package version. Writes only, so they - /// share the authorisation of the publish endpoints. - /// - public void MapPackageMetadataAdminRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.SetDeprecationRouteName, - pattern: "v3/package/{id}/{version}/deprecation", - defaults: new { controller = "PackageMetadataAdmin", action = "SetDeprecation" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); - - endpoints.MapControllerRoute( - name: Routes.RemoveDeprecationRouteName, - pattern: "v3/package/{id}/{version}/deprecation", - defaults: new { controller = "PackageMetadataAdmin", action = "RemoveDeprecation" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("DELETE") }); - - endpoints.MapControllerRoute( - name: Routes.SetVulnerabilitiesRouteName, - pattern: "v3/package/{id}/{version}/vulnerabilities", - defaults: new { controller = "PackageMetadataAdmin", action = "SetVulnerabilities" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); - } - - public void MapValidationRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.RepositorySignaturesRouteName, - pattern: "v3/repository-signatures/index.json", - defaults: new { controller = "RepositorySignatures", action = "Index" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.RepositorySigningCertificateRouteName, - pattern: "v3/repository-signatures/{fingerprint}.crt", - defaults: new { controller = "RepositorySignatures", action = "Certificate" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.ValidationStatusRouteName, - pattern: "v3/package/{id}/{version}/validation", - defaults: new { controller = "ValidationStatus", action = "Get" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - } - - public void MapCatalogRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.CatalogIndexRouteName, - pattern: "v3/catalog/index.json", - defaults: new { controller = "Catalog", action = "Index" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.CatalogPageRouteName, - pattern: "v3/catalog/page{pageIndex:int}.json", - defaults: new { controller = "Catalog", action = "Page" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.CatalogLeafRouteName, - pattern: "v3/catalog/data/{commitId}.json", - defaults: new { controller = "Catalog", action = "Leaf" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - } - - public void MapVulnerabilityRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.VulnerabilityIndexRouteName, - pattern: "v3/vulnerabilities/index.json", - defaults: new { controller = "Vulnerability", action = "Index" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.VulnerabilityPageRouteName, - pattern: "v3/vulnerabilities/{pageName}.json", - defaults: new { controller = "Vulnerability", action = "Page" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - } - - /// - /// The V2 (OData) feed. The routes are always mapped; the controller itself - /// answers 404 for every action when "Feeds:EnableV2" is off, so turning the feed - /// off does not change which routes exist. - /// - public void MapV2FeedRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.V2RootRouteName, - pattern: "api/v2", - defaults: new { controller = "V2Feed", action = "Root" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.V2MetadataRouteName, - pattern: "api/v2/$metadata", - defaults: new { controller = "V2Feed", action = "Metadata" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.V2FindPackagesByIdRouteName, - pattern: "api/v2/FindPackagesById()", - defaults: new { controller = "V2Feed", action = "FindPackagesById" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.V2SearchRouteName, - pattern: "api/v2/Search()", - defaults: new { controller = "V2Feed", action = "Search" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - // The keyed form carries its values inside the segment, so it is matched by a - // literal pattern per argument order rather than by route values. - endpoints.MapControllerRoute( - name: Routes.V2PackagesByKeyRouteName, - pattern: "api/v2/Packages(Id={id},Version={version})", - defaults: new { controller = "V2Feed", action = "PackagesByKey" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - - endpoints.MapControllerRoute( - name: Routes.V2PackagesRouteName, - pattern: "api/v2/Packages()", - defaults: new { controller = "V2Feed", action = "Packages" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("GET") }); - } - - public void MapServiceIndexRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.IndexRouteName, - pattern: "v3/index.json", - defaults: new { controller = "ServiceIndex", action = "Get" }); - } - - public void MapPackagePublishRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.UploadPackageRouteName, - pattern: "api/v2/package", - defaults: new { controller = "PackagePublish", action = "Upload" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); - - endpoints.MapControllerRoute( - name: Routes.DeleteRouteName, - pattern: "api/v2/package/{id}/{version}", - defaults: new { controller = "PackagePublish", action = "Delete" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("DELETE") }); - - endpoints.MapControllerRoute( - name: Routes.RelistRouteName, - pattern: "api/v2/package/{id}/{version}", - defaults: new { controller = "PackagePublish", action = "Relist" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("POST") }); - } - - public void MapSymbolRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.UploadSymbolRouteName, - pattern: "api/v2/symbol", - defaults: new { controller = "Symbol", action = "Upload" }, - constraints: new { httpMethod = new HttpMethodRouteConstraint("PUT") }); - - endpoints.MapControllerRoute( - name: Routes.SymbolDownloadRouteName, - pattern: "api/download/symbols/{file}/{key}/{file2}", - defaults: new { controller = "Symbol", action = "Get" }); - - endpoints.MapControllerRoute( - name: Routes.PrefixedSymbolDownloadRouteName, - pattern: "api/download/symbols/{prefix}/{file}/{key}/{file2}", - defaults: new { controller = "Symbol", action = "Get" }); - } - - public void MapSearchRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.SearchRouteName, - pattern: "v3/search", - defaults: new { controller = "Search", action = "Search" }); - - endpoints.MapControllerRoute( - name: Routes.AutocompleteRouteName, - pattern: "v3/autocomplete", - defaults: new { controller = "Search", action = "Autocomplete" }); - - // This is an unofficial API to find packages that depend on a given package. - endpoints.MapControllerRoute( - name: Routes.DependentsRouteName, - pattern: "v3/dependents", - defaults: new { controller = "Search", action = "Dependents" }); - } - - public void MapPackageMetadataRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.RegistrationIndexRouteName, - pattern: "v3/registration/{id}/index.json", - defaults: new { controller = "PackageMetadata", action = "RegistrationIndex" }); - - endpoints.MapControllerRoute( - name: Routes.RegistrationLeafRouteName, - pattern: "v3/registration/{id}/{version}.json", - defaults: new { controller = "PackageMetadata", action = "RegistrationLeaf" }); - } - - public void MapPackageContentRoutes(IEndpointRouteBuilder endpoints) - { - endpoints.MapControllerRoute( - name: Routes.PackageVersionsRouteName, - pattern: "v3/package/{id}/index.json", - defaults: new { controller = "PackageContent", action = "GetPackageVersions" }); - - endpoints.MapControllerRoute( - name: Routes.PackageDownloadRouteName, - pattern: "v3/package/{id}/{version}/{idVersion}.nupkg", - defaults: new { controller = "PackageContent", action = "DownloadPackage" }); - - endpoints.MapControllerRoute( - name: Routes.PackageDownloadManifestRouteName, - pattern: "v3/package/{id}/{version}/{id2}.nuspec", - defaults: new { controller = "PackageContent", action = "DownloadNuspec" }); - - endpoints.MapControllerRoute( - name: Routes.PackageDownloadReadmeRouteName, - pattern: "v3/package/{id}/{version}/readme", - defaults: new { controller = "PackageContent", action = "DownloadReadme" }); - - endpoints.MapControllerRoute( - name: Routes.PackageDownloadIconRouteName, - pattern: "v3/package/{id}/{version}/icon", - defaults: new { controller = "PackageContent", action = "DownloadIcon" }); - } + endpoints.MapControllerRoute( + name: Routes.PackageVersionsRouteName, + pattern: "v3/package/{id}/index.json", + defaults: new { controller = "PackageContent", action = "GetPackageVersions" }); + + endpoints.MapControllerRoute( + name: Routes.PackageDownloadRouteName, + pattern: "v3/package/{id}/{version}/{idVersion}.nupkg", + defaults: new { controller = "PackageContent", action = "DownloadPackage" }); + + endpoints.MapControllerRoute( + name: Routes.PackageDownloadManifestRouteName, + pattern: "v3/package/{id}/{version}/{id2}.nuspec", + defaults: new { controller = "PackageContent", action = "DownloadNuspec" }); + + endpoints.MapControllerRoute( + name: Routes.PackageDownloadReadmeRouteName, + pattern: "v3/package/{id}/{version}/readme", + defaults: new { controller = "PackageContent", action = "DownloadReadme" }); + + endpoints.MapControllerRoute( + name: Routes.PackageDownloadIconRouteName, + pattern: "v3/package/{id}/{version}/icon", + defaults: new { controller = "PackageContent", action = "DownloadIcon" }); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/BaGetUrlGenerator.cs b/src/BaGet.Web/BaGetUrlGenerator.cs index feeee6053..592fb6297 100644 --- a/src/BaGet.Web/BaGetUrlGenerator.cs +++ b/src/BaGet.Web/BaGetUrlGenerator.cs @@ -5,227 +5,226 @@ using Microsoft.AspNetCore.Routing; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +// The URLs below are built from the incoming request's "Host" header, which the client +// controls. The header is validated against the configured allow-list by ASP.NET Core's +// host filtering middleware instead of here: see BaGetOptions.AllowedHosts, which BaGet's +// Startup binds to HostFilteringOptions and enforces with UseHostFiltering. +// +// Validating in this generator would be both too late and too narrow. Too late, because +// by the time a URL is generated the request has already been handled on a host BaGet +// does not serve, and there is no correct URL left to return. Too narrow, because the +// same header is read by routing, by LinkGenerator below and by anything else holding +// the HttpContext; only rejecting the request protects all of them at once. +public class BaGetUrlGenerator : IUrlGenerator { - // The URLs below are built from the incoming request's "Host" header, which the client - // controls. The header is validated against the configured allow-list by ASP.NET Core's - // host filtering middleware instead of here: see BaGetOptions.AllowedHosts, which BaGet's - // Startup binds to HostFilteringOptions and enforces with UseHostFiltering. - // - // Validating in this generator would be both too late and too narrow. Too late, because - // by the time a URL is generated the request has already been handled on a host BaGet - // does not serve, and there is no correct URL left to return. Too narrow, because the - // same header is read by routing, by LinkGenerator below and by anything else holding - // the HttpContext; only rejecting the request protects all of them at once. - public class BaGetUrlGenerator : IUrlGenerator - { - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly LinkGenerator _linkGenerator; - - public BaGetUrlGenerator(IHttpContextAccessor httpContextAccessor, LinkGenerator linkGenerator) - { - _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); - _linkGenerator = linkGenerator ?? throw new ArgumentNullException(nameof(linkGenerator)); - } - - public string GetServiceIndexUrl() - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.IndexRouteName, - values: null); - } - - public string GetPackageContentResourceUrl() - { - return AbsoluteUrl("v3/package"); - } - - public string GetPackageMetadataResourceUrl() - { - return AbsoluteUrl("v3/registration"); - } - - public string GetPackagePublishResourceUrl() - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.UploadPackageRouteName, - values: null); - } - - public string GetSymbolPublishResourceUrl() - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.UploadSymbolRouteName, - values: null); - } - - public string GetSearchResourceUrl() - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.SearchRouteName, - values: null); - } - - public string GetAutocompleteResourceUrl() - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.AutocompleteRouteName, - values: null); - } - - public string GetRegistrationIndexUrl(string id) - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.RegistrationIndexRouteName, - values: new { Id = id.ToLowerInvariant() }); - } - - public string GetRegistrationPageUrl(string id, NuGetVersion lower, NuGetVersion upper) - { - // BaGet does not support paging the registration resource. - throw new NotImplementedException(); - } - - public string GetRegistrationLeafUrl(string id, NuGetVersion version) - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.RegistrationLeafRouteName, - values: new - { - Id = id.ToLowerInvariant(), - Version = version.ToNormalizedString().ToLowerInvariant(), - }); - } - - public string GetPackageVersionsUrl(string id) - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.PackageVersionsRouteName, - values: new { Id = id.ToLowerInvariant() }); - } - - public string GetPackageDownloadUrl(string id, NuGetVersion version) - { - id = id.ToLowerInvariant(); - var versionString = version.ToNormalizedString().ToLowerInvariant(); - - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.PackageDownloadRouteName, - values: new - { - Id = id, - Version = versionString, - IdVersion = $"{id}.{versionString}" - }); - } - - public string GetPackageManifestDownloadUrl(string id, NuGetVersion version) - { - id = id.ToLowerInvariant(); - var versionString = version.ToNormalizedString().ToLowerInvariant(); - - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.PackageDownloadRouteName, - values: new - { - Id = id, - Version = versionString, - Id2 = id, - }); - } - - public string GetPackageIconDownloadUrl(string id, NuGetVersion version) - { - id = id.ToLowerInvariant(); - var versionString = version.ToNormalizedString().ToLowerInvariant(); - - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.PackageDownloadIconRouteName, - values: new - { - Id = id, - Version = versionString - }); - } - - public string GetV2FeedUrl() - { - return _linkGenerator.GetUriByRouteValues( - _httpContextAccessor.HttpContext, - Routes.V2RootRouteName, - values: null); - } - - // These two are templates for the client to expand, not URLs for a specific - // package, so the placeholders are returned verbatim. Routing them through - // LinkGenerator would percent-encode the braces. - public string GetPackageDetailsUriTemplate() - { - return AbsoluteUrl("packages/{id}/{version}"); - } - - public string GetVulnerabilityIndexUrl() - { - return AbsoluteUrl("v3/vulnerabilities/index.json"); - } - - public string GetVulnerabilityPageUrl(string pageName) - { - return AbsoluteUrl($"v3/vulnerabilities/{Uri.EscapeDataString(pageName)}.json"); - } - - public string GetCatalogIndexUrl() - { - return AbsoluteUrl("v3/catalog/index.json"); - } - - public string GetCatalogPageUrl(int pageIndex) - { - return AbsoluteUrl($"v3/catalog/page{pageIndex.ToString(CultureInfo.InvariantCulture)}.json"); - } - - public string GetCatalogLeafUrl(string commitId) - { - return AbsoluteUrl($"v3/catalog/data/{Uri.EscapeDataString(commitId)}.json"); - } - - public string GetRepositorySignaturesUrl() - { - return AbsoluteUrl("v3/repository-signatures/index.json"); - } - - public string GetRepositorySigningCertificateUrl(string fingerprint) - { - return AbsoluteUrl($"v3/repository-signatures/{Uri.EscapeDataString(fingerprint)}.crt"); - } - - public string GetReportAbuseUriTemplate() - { - return AbsoluteUrl("packages/{id}/{version}/report-abuse"); - } - - private string AbsoluteUrl(string relativePath) - { - var request = _httpContextAccessor.HttpContext.Request; - - return string.Concat( - request.Scheme, - "://", - request.Host.ToUriComponent(), - request.PathBase.ToUriComponent(), - "/", - relativePath); - } - } -} + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly LinkGenerator _linkGenerator; + + public BaGetUrlGenerator(IHttpContextAccessor httpContextAccessor, LinkGenerator linkGenerator) + { + _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); + _linkGenerator = linkGenerator ?? throw new ArgumentNullException(nameof(linkGenerator)); + } + + public string GetServiceIndexUrl() + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.IndexRouteName, + values: null); + } + + public string GetPackageContentResourceUrl() + { + return AbsoluteUrl("v3/package"); + } + + public string GetPackageMetadataResourceUrl() + { + return AbsoluteUrl("v3/registration"); + } + + public string GetPackagePublishResourceUrl() + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.UploadPackageRouteName, + values: null); + } + + public string GetSymbolPublishResourceUrl() + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.UploadSymbolRouteName, + values: null); + } + + public string GetSearchResourceUrl() + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.SearchRouteName, + values: null); + } + + public string GetAutocompleteResourceUrl() + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.AutocompleteRouteName, + values: null); + } + + public string GetRegistrationIndexUrl(string id) + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.RegistrationIndexRouteName, + values: new { Id = id.ToLowerInvariant() }); + } + + public string GetRegistrationPageUrl(string id, NuGetVersion lower, NuGetVersion upper) + { + // BaGet does not support paging the registration resource. + throw new NotImplementedException(); + } + + public string GetRegistrationLeafUrl(string id, NuGetVersion version) + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.RegistrationLeafRouteName, + values: new + { + Id = id.ToLowerInvariant(), + Version = version.ToNormalizedString().ToLowerInvariant(), + }); + } + + public string GetPackageVersionsUrl(string id) + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.PackageVersionsRouteName, + values: new { Id = id.ToLowerInvariant() }); + } + + public string GetPackageDownloadUrl(string id, NuGetVersion version) + { + id = id.ToLowerInvariant(); + var versionString = version.ToNormalizedString().ToLowerInvariant(); + + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.PackageDownloadRouteName, + values: new + { + Id = id, + Version = versionString, + IdVersion = $"{id}.{versionString}" + }); + } + + public string GetPackageManifestDownloadUrl(string id, NuGetVersion version) + { + id = id.ToLowerInvariant(); + var versionString = version.ToNormalizedString().ToLowerInvariant(); + + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.PackageDownloadRouteName, + values: new + { + Id = id, + Version = versionString, + Id2 = id, + }); + } + + public string GetPackageIconDownloadUrl(string id, NuGetVersion version) + { + id = id.ToLowerInvariant(); + var versionString = version.ToNormalizedString().ToLowerInvariant(); + + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.PackageDownloadIconRouteName, + values: new + { + Id = id, + Version = versionString + }); + } + + public string GetV2FeedUrl() + { + return _linkGenerator.GetUriByRouteValues( + _httpContextAccessor.HttpContext, + Routes.V2RootRouteName, + values: null); + } + + // These two are templates for the client to expand, not URLs for a specific + // package, so the placeholders are returned verbatim. Routing them through + // LinkGenerator would percent-encode the braces. + public string GetPackageDetailsUriTemplate() + { + return AbsoluteUrl("packages/{id}/{version}"); + } + + public string GetVulnerabilityIndexUrl() + { + return AbsoluteUrl("v3/vulnerabilities/index.json"); + } + + public string GetVulnerabilityPageUrl(string pageName) + { + return AbsoluteUrl($"v3/vulnerabilities/{Uri.EscapeDataString(pageName)}.json"); + } + + public string GetCatalogIndexUrl() + { + return AbsoluteUrl("v3/catalog/index.json"); + } + + public string GetCatalogPageUrl(int pageIndex) + { + return AbsoluteUrl($"v3/catalog/page{pageIndex.ToString(CultureInfo.InvariantCulture)}.json"); + } + + public string GetCatalogLeafUrl(string commitId) + { + return AbsoluteUrl($"v3/catalog/data/{Uri.EscapeDataString(commitId)}.json"); + } + + public string GetRepositorySignaturesUrl() + { + return AbsoluteUrl("v3/repository-signatures/index.json"); + } + + public string GetRepositorySigningCertificateUrl(string fingerprint) + { + return AbsoluteUrl($"v3/repository-signatures/{Uri.EscapeDataString(fingerprint)}.crt"); + } + + public string GetReportAbuseUriTemplate() + { + return AbsoluteUrl("packages/{id}/{version}/report-abuse"); + } + + private string AbsoluteUrl(string relativePath) + { + var request = _httpContextAccessor.HttpContext.Request; + + return string.Concat( + request.Scheme, + "://", + request.Host.ToUriComponent(), + request.PathBase.ToUriComponent(), + "/", + relativePath); + } +} \ No newline at end of file diff --git a/src/BaGet.Web/Controllers/PackageContentController.cs b/src/BaGet.Web/Controllers/PackageContentController.cs index b5bd2b5ab..c7e9b67e5 100644 --- a/src/BaGet.Web/Controllers/PackageContentController.cs +++ b/src/BaGet.Web/Controllers/PackageContentController.cs @@ -6,94 +6,93 @@ using Microsoft.AspNetCore.Mvc; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// The Package Content resource, used to download content from packages. +/// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource +/// +public class PackageContentController : Controller { - /// - /// The Package Content resource, used to download content from packages. - /// See: https://docs.microsoft.com/en-us/nuget/api/package-base-address-resource - /// - public class PackageContentController : Controller + private readonly IPackageContentService _content; + + public PackageContentController(IPackageContentService content) { - private readonly IPackageContentService _content; + _content = content ?? throw new ArgumentNullException(nameof(content)); + } - public PackageContentController(IPackageContentService content) + public async Task> GetPackageVersionsAsync(string id, CancellationToken cancellationToken) + { + var versions = await _content.GetPackageVersionsOrNullAsync(id, cancellationToken); + if (versions == null) { - _content = content ?? throw new ArgumentNullException(nameof(content)); + return NotFound(); } - public async Task> GetPackageVersionsAsync(string id, CancellationToken cancellationToken) + return versions; + } + + public async Task DownloadPackageAsync(string id, string version, CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var nugetVersion)) { - var versions = await _content.GetPackageVersionsOrNullAsync(id, cancellationToken); - if (versions == null) - { - return NotFound(); - } + return NotFound(); + } - return versions; + var packageStream = await _content.GetPackageContentStreamOrNullAsync(id, nugetVersion, cancellationToken); + if (packageStream == null) + { + return NotFound(); } - public async Task DownloadPackageAsync(string id, string version, CancellationToken cancellationToken) + return File(packageStream, "application/octet-stream"); + } + + public async Task DownloadNuspecAsync(string id, string version, CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var nugetVersion)) { - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } - - var packageStream = await _content.GetPackageContentStreamOrNullAsync(id, nugetVersion, cancellationToken); - if (packageStream == null) - { - return NotFound(); - } - - return File(packageStream, "application/octet-stream"); + return NotFound(); } - public async Task DownloadNuspecAsync(string id, string version, CancellationToken cancellationToken) + var nuspecStream = await _content.GetPackageManifestStreamOrNullAsync(id, nugetVersion, cancellationToken); + if (nuspecStream == null) { - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } - - var nuspecStream = await _content.GetPackageManifestStreamOrNullAsync(id, nugetVersion, cancellationToken); - if (nuspecStream == null) - { - return NotFound(); - } - - return File(nuspecStream, "text/xml"); + return NotFound(); } - public async Task DownloadReadmeAsync(string id, string version, CancellationToken cancellationToken) + return File(nuspecStream, "text/xml"); + } + + public async Task DownloadReadmeAsync(string id, string version, CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var nugetVersion)) + { + return NotFound(); + } + + var readmeStream = await _content.GetPackageReadmeStreamOrNullAsync(id, nugetVersion, cancellationToken); + if (readmeStream == null) + { + return NotFound(); + } + + return File(readmeStream, "text/markdown"); + } + + public async Task DownloadIconAsync(string id, string version, CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var nugetVersion)) { - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } - - var readmeStream = await _content.GetPackageReadmeStreamOrNullAsync(id, nugetVersion, cancellationToken); - if (readmeStream == null) - { - return NotFound(); - } - - return File(readmeStream, "text/markdown"); + return NotFound(); } - public async Task DownloadIconAsync(string id, string version, CancellationToken cancellationToken) + var iconStream = await _content.GetPackageIconStreamOrNullAsync(id, nugetVersion, cancellationToken); + if (iconStream == null) { - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } - - var iconStream = await _content.GetPackageIconStreamOrNullAsync(id, nugetVersion, cancellationToken); - if (iconStream == null) - { - return NotFound(); - } - - return File(iconStream, "image/xyz"); + return NotFound(); } + + return File(iconStream, "image/xyz"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Controllers/PackageMetadataAdminController.cs b/src/BaGet.Web/Controllers/PackageMetadataAdminController.cs index c8bc691e0..41be3c70c 100644 --- a/src/BaGet.Web/Controllers/PackageMetadataAdminController.cs +++ b/src/BaGet.Web/Controllers/PackageMetadataAdminController.cs @@ -11,252 +11,251 @@ using Microsoft.Extensions.Options; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// Sets a package version's deprecation and vulnerability metadata. These are writes, so +/// they are authorised exactly like push and delete. +/// +public class PackageMetadataAdminController : Controller { - /// - /// Sets a package version's deprecation and vulnerability metadata. These are writes, so - /// they are authorised exactly like push and delete. - /// - public class PackageMetadataAdminController : Controller + private readonly IAuthenticationService _authentication; + private readonly IPackageAuthorizationService _authorization; + private readonly IPackageDatabase _packages; + private readonly IOptionsSnapshot _options; + private readonly PackageChangeNotifier _notifier; + + public PackageMetadataAdminController( + IAuthenticationService authentication, + IPackageDatabase packages, + IOptionsSnapshot options, + PackageChangeNotifier notifier, + IPackageAuthorizationService authorization) + { + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + + public async Task SetDeprecation( + string id, + string version, + [FromBody] DeprecationRequest request, + CancellationToken cancellationToken) { - private readonly IAuthenticationService _authentication; - private readonly IPackageAuthorizationService _authorization; - private readonly IPackageDatabase _packages; - private readonly IOptionsSnapshot _options; - private readonly PackageChangeNotifier _notifier; - - public PackageMetadataAdminController( - IAuthenticationService authentication, - IPackageDatabase packages, - IOptionsSnapshot options, - PackageChangeNotifier notifier, - IPackageAuthorizationService authorization) + var denied = await AuthorizeAsync(id, cancellationToken); + if (denied != null) return denied; + + if (!NuGetVersion.TryParse(version, out var nugetVersion)) { - _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); - _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); - _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _options = options ?? throw new ArgumentNullException(nameof(options)); + return NotFound(); } - public async Task SetDeprecation( - string id, - string version, - [FromBody] DeprecationRequest request, - CancellationToken cancellationToken) + var error = Validate(request); + if (error != null) { - var denied = await AuthorizeAsync(id, cancellationToken); - if (denied != null) return denied; + return BadRequest(error); + } - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } + var deprecation = new PackageDeprecation + { + Reasons = request.Reasons.Distinct(StringComparer.Ordinal).ToArray(), + Message = request.Message, + AlternatePackageId = request.AlternatePackageId, + AlternateVersionRange = request.AlternatePackageId == null ? null : request.AlternateVersionRange, + }; - var error = Validate(request); - if (error != null) - { - return BadRequest(error); - } + return await RunAsync(id, nugetVersion, () => _packages.SetDeprecationAsync(id, nugetVersion, deprecation, cancellationToken), cancellationToken); + } - var deprecation = new PackageDeprecation - { - Reasons = request.Reasons.Distinct(StringComparer.Ordinal).ToArray(), - Message = request.Message, - AlternatePackageId = request.AlternatePackageId, - AlternateVersionRange = request.AlternatePackageId == null ? null : request.AlternateVersionRange, - }; + public async Task RemoveDeprecation( + string id, + string version, + CancellationToken cancellationToken) + { + var denied = await AuthorizeAsync(id, cancellationToken); + if (denied != null) return denied; - return await RunAsync(id, nugetVersion, () => _packages.SetDeprecationAsync(id, nugetVersion, deprecation, cancellationToken), cancellationToken); + if (!NuGetVersion.TryParse(version, out var nugetVersion)) + { + return NotFound(); } - public async Task RemoveDeprecation( - string id, - string version, - CancellationToken cancellationToken) - { - var denied = await AuthorizeAsync(id, cancellationToken); - if (denied != null) return denied; + return await RunAsync(id, nugetVersion, () => _packages.RemoveDeprecationAsync(id, nugetVersion, cancellationToken), cancellationToken); + } - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } + public async Task SetVulnerabilities( + string id, + string version, + [FromBody] List request, + CancellationToken cancellationToken) + { + var denied = await AuthorizeAsync(id, cancellationToken); + if (denied != null) return denied; - return await RunAsync(id, nugetVersion, () => _packages.RemoveDeprecationAsync(id, nugetVersion, cancellationToken), cancellationToken); + if (!NuGetVersion.TryParse(version, out var nugetVersion)) + { + return NotFound(); } - public async Task SetVulnerabilities( - string id, - string version, - [FromBody] List request, - CancellationToken cancellationToken) + var error = Validate(request); + if (error != null) { - var denied = await AuthorizeAsync(id, cancellationToken); - if (denied != null) return denied; - - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } + return BadRequest(error); + } - var error = Validate(request); - if (error != null) + var vulnerabilities = request + .Select(v => new PackageVulnerability { - return BadRequest(error); - } + AdvisoryUrl = v.AdvisoryUrl, + Severity = v.Severity, + VersionRange = v.VersionRange, + }) + .ToList(); - var vulnerabilities = request - .Select(v => new PackageVulnerability - { - AdvisoryUrl = v.AdvisoryUrl, - Severity = v.Severity, - VersionRange = v.VersionRange, - }) - .ToList(); + return await RunAsync(id, nugetVersion, () => _packages.SetVulnerabilitiesAsync(id, nugetVersion, vulnerabilities, cancellationToken), cancellationToken); + } - return await RunAsync(id, nugetVersion, () => _packages.SetVulnerabilitiesAsync(id, nugetVersion, vulnerabilities, cancellationToken), cancellationToken); + internal static string Validate(DeprecationRequest request) + { + if (request?.Reasons == null || request.Reasons.Count == 0) + { + return "At least one deprecation reason is required."; } - internal static string Validate(DeprecationRequest request) + var unknown = request.Reasons.FirstOrDefault(r => !PackageDeprecation.KnownReasons.Contains(r, StringComparer.Ordinal)); + if (unknown != null) { - if (request?.Reasons == null || request.Reasons.Count == 0) - { - return "At least one deprecation reason is required."; - } + return $"Unknown deprecation reason '{unknown}'. Use one of: {string.Join(", ", PackageDeprecation.KnownReasons)}."; + } - var unknown = request.Reasons.FirstOrDefault(r => !PackageDeprecation.KnownReasons.Contains(r, StringComparer.Ordinal)); - if (unknown != null) - { - return $"Unknown deprecation reason '{unknown}'. Use one of: {string.Join(", ", PackageDeprecation.KnownReasons)}."; - } + if (request.Message?.Length > AbstractContext.DefaultMaxStringLength) + { + return "The deprecation message is too long."; + } - if (request.Message?.Length > AbstractContext.DefaultMaxStringLength) - { - return "The deprecation message is too long."; - } + if (request.AlternatePackageId == null && request.AlternateVersionRange != null) + { + return "An alternate version range needs an alternate package ID."; + } - if (request.AlternatePackageId == null && request.AlternateVersionRange != null) - { - return "An alternate version range needs an alternate package ID."; - } + if (request.AlternateVersionRange != null + && request.AlternateVersionRange != "*" + && !VersionRange.TryParse(request.AlternateVersionRange, out _)) + { + return $"'{request.AlternateVersionRange}' is not a version range."; + } - if (request.AlternateVersionRange != null - && request.AlternateVersionRange != "*" - && !VersionRange.TryParse(request.AlternateVersionRange, out _)) - { - return $"'{request.AlternateVersionRange}' is not a version range."; - } + return null; + } - return null; + internal static string Validate(IReadOnlyList request) + { + if (request == null) + { + return "A list of vulnerabilities is required; send an empty list to clear them."; } - internal static string Validate(IReadOnlyList request) + foreach (var vulnerability in request) { - if (request == null) + if (vulnerability == null) { - return "A list of vulnerabilities is required; send an empty list to clear them."; + return "A vulnerability cannot be null."; } - foreach (var vulnerability in request) + if (!Uri.TryCreate(vulnerability.AdvisoryUrl, UriKind.Absolute, out var url) + || (url.Scheme != Uri.UriSchemeHttps && url.Scheme != Uri.UriSchemeHttp)) { - if (vulnerability == null) - { - return "A vulnerability cannot be null."; - } - - if (!Uri.TryCreate(vulnerability.AdvisoryUrl, UriKind.Absolute, out var url) - || (url.Scheme != Uri.UriSchemeHttps && url.Scheme != Uri.UriSchemeHttp)) - { - return $"'{vulnerability.AdvisoryUrl}' is not an absolute http or https URL."; - } - - // The protocol numbers severity 0 low, 1 moderate, 2 high, 3 critical. - if (vulnerability.Severity < 0 || vulnerability.Severity > 3) - { - return $"Severity {vulnerability.Severity} is outside the range 0 to 3."; - } - - if (vulnerability.VersionRange != null && !VersionRange.TryParse(vulnerability.VersionRange, out _)) - { - return $"'{vulnerability.VersionRange}' is not a version range."; - } + return $"'{vulnerability.AdvisoryUrl}' is not an absolute http or https URL."; } - return null; - } - - private async Task AuthorizeAsync(string id, CancellationToken cancellationToken) - { - // The same rules as deleting or relisting a package. - if (_options.Value.IsReadOnlyMode) + // The protocol numbers severity 0 low, 1 moderate, 2 high, 3 critical. + if (vulnerability.Severity < 0 || vulnerability.Severity > 3) { - return Unauthorized(); + return $"Severity {vulnerability.Severity} is outside the range 0 to 3."; } - var principal = await _authentication.AuthenticatePrincipalAsync(Request.GetApiKey(), cancellationToken); - if (principal == null) + if (vulnerability.VersionRange != null && !VersionRange.TryParse(vulnerability.VersionRange, out _)) { - return Unauthorized(); + return $"'{vulnerability.VersionRange}' is not a version range."; } + } - if (!await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken)) - { - return StatusCode(StatusCodes.Status403Forbidden); - } + return null; + } - return null; + private async Task AuthorizeAsync(string id, CancellationToken cancellationToken) + { + // The same rules as deleting or relisting a package. + if (_options.Value.IsReadOnlyMode) + { + return Unauthorized(); } - private async Task RunAsync( - string id, - NuGetVersion version, - Func> operation, - CancellationToken cancellationToken) + var principal = await _authentication.AuthenticatePrincipalAsync(Request.GetApiKey(), cancellationToken); + if (principal == null) { - try - { - if (!await operation()) - { - return NotFound(); - } + return Unauthorized(); + } - await _notifier.PackageChangedAsync(id, version, cancellationToken); + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken)) + { + return StatusCode(StatusCodes.Status403Forbidden); + } - return NoContent(); - } - catch (NotSupportedException e) + return null; + } + + private async Task RunAsync( + string id, + NuGetVersion version, + Func> operation, + CancellationToken cancellationToken) + { + try + { + if (!await operation()) { - // The configured database cannot store this metadata. - return StatusCode(StatusCodes.Status501NotImplemented, e.Message); + return NotFound(); } + + await _notifier.PackageChangedAsync(id, version, cancellationToken); + + return NoContent(); + } + catch (NotSupportedException e) + { + // The configured database cannot store this metadata. + return StatusCode(StatusCodes.Status501NotImplemented, e.Message); } } +} - public class DeprecationRequest - { - [JsonPropertyName("reasons")] - public IReadOnlyList Reasons { get; set; } +public class DeprecationRequest +{ + [JsonPropertyName("reasons")] + public IReadOnlyList Reasons { get; set; } - [JsonPropertyName("message")] - public string Message { get; set; } + [JsonPropertyName("message")] + public string Message { get; set; } - [JsonPropertyName("alternatePackageId")] - public string AlternatePackageId { get; set; } + [JsonPropertyName("alternatePackageId")] + public string AlternatePackageId { get; set; } - [JsonPropertyName("alternateVersionRange")] - public string AlternateVersionRange { get; set; } - } + [JsonPropertyName("alternateVersionRange")] + public string AlternateVersionRange { get; set; } +} - public class VulnerabilityRequest - { - [JsonPropertyName("advisoryUrl")] - public string AdvisoryUrl { get; set; } +public class VulnerabilityRequest +{ + [JsonPropertyName("advisoryUrl")] + public string AdvisoryUrl { get; set; } - [JsonPropertyName("severity")] - public int Severity { get; set; } + [JsonPropertyName("severity")] + public int Severity { get; set; } - [JsonPropertyName("versionRange")] - public string VersionRange { get; set; } - } -} + [JsonPropertyName("versionRange")] + public string VersionRange { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Web/Controllers/PackageMetadataController.cs b/src/BaGet.Web/Controllers/PackageMetadataController.cs index 18ca1fde5..d3d8a730d 100644 --- a/src/BaGet.Web/Controllers/PackageMetadataController.cs +++ b/src/BaGet.Web/Controllers/PackageMetadataController.cs @@ -6,50 +6,49 @@ using Microsoft.AspNetCore.Mvc; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// The Package Metadata resource, used to fetch packages' information. +/// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource +/// +public class PackageMetadataController : Controller { - /// - /// The Package Metadata resource, used to fetch packages' information. - /// See: https://docs.microsoft.com/en-us/nuget/api/registration-base-url-resource - /// - public class PackageMetadataController : Controller + private readonly IPackageMetadataService _metadata; + + public PackageMetadataController(IPackageMetadataService metadata) { - private readonly IPackageMetadataService _metadata; + _metadata = metadata ?? throw new ArgumentNullException(nameof(metadata)); + } - public PackageMetadataController(IPackageMetadataService metadata) + // GET v3/registration/{id}.json + [HttpGet] + public async Task> RegistrationIndexAsync(string id, CancellationToken cancellationToken) + { + var index = await _metadata.GetRegistrationIndexOrNullAsync(id, cancellationToken); + if (index == null) { - _metadata = metadata ?? throw new ArgumentNullException(nameof(metadata)); + return NotFound(); } - // GET v3/registration/{id}.json - [HttpGet] - public async Task> RegistrationIndexAsync(string id, CancellationToken cancellationToken) - { - var index = await _metadata.GetRegistrationIndexOrNullAsync(id, cancellationToken); - if (index == null) - { - return NotFound(); - } + return index; + } - return index; + // GET v3/registration/{id}/{version}.json + [HttpGet] + public async Task> RegistrationLeafAsync(string id, string version, CancellationToken cancellationToken) + { + if (!NuGetVersion.TryParse(version, out var nugetVersion)) + { + return NotFound(); } - // GET v3/registration/{id}/{version}.json - [HttpGet] - public async Task> RegistrationLeafAsync(string id, string version, CancellationToken cancellationToken) + var leaf = await _metadata.GetRegistrationLeafOrNullAsync(id, nugetVersion, cancellationToken); + if (leaf == null) { - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } - - var leaf = await _metadata.GetRegistrationLeafOrNullAsync(id, nugetVersion, cancellationToken); - if (leaf == null) - { - return NotFound(); - } - - return leaf; + return NotFound(); } + + return leaf; } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Controllers/PackagePublishController.cs b/src/BaGet.Web/Controllers/PackagePublishController.cs index a95aaefa0..bfeb9dfb5 100644 --- a/src/BaGet.Web/Controllers/PackagePublishController.cs +++ b/src/BaGet.Web/Controllers/PackagePublishController.cs @@ -7,182 +7,181 @@ using Microsoft.Extensions.Options; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +public class PackagePublishController : Controller { - public class PackagePublishController : Controller + private readonly IAuthenticationService _authentication; + private readonly IPackageAuthorizationService _authorization; + private readonly IPackageSubmissionService _submissions; + private readonly IPackageDatabase _packages; + private readonly IPackageDeletionService _deleteService; + private readonly IOptionsSnapshot _options; + private readonly ILogger _logger; + private readonly PackageChangeNotifier _notifier; + + public PackagePublishController( + IAuthenticationService authentication, + IPackageSubmissionService submissions, + IPackageDatabase packages, + IPackageDeletionService deletionService, + IOptionsSnapshot options, + ILogger logger, + PackageChangeNotifier notifier, + IPackageAuthorizationService authorization) { - private readonly IAuthenticationService _authentication; - private readonly IPackageAuthorizationService _authorization; - private readonly IPackageSubmissionService _submissions; - private readonly IPackageDatabase _packages; - private readonly IPackageDeletionService _deleteService; - private readonly IOptionsSnapshot _options; - private readonly ILogger _logger; - private readonly PackageChangeNotifier _notifier; - - public PackagePublishController( - IAuthenticationService authentication, - IPackageSubmissionService submissions, - IPackageDatabase packages, - IPackageDeletionService deletionService, - IOptionsSnapshot options, - ILogger logger, - PackageChangeNotifier notifier, - IPackageAuthorizationService authorization) + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _submissions = submissions ?? throw new ArgumentNullException(nameof(submissions)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _deleteService = deletionService ?? throw new ArgumentNullException(nameof(deletionService)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + // See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#push-a-package + public async Task Upload(CancellationToken cancellationToken) + { + var principal = _options.Value.IsReadOnlyMode + ? null + : await _authentication.AuthenticatePrincipalAsync(Request.GetApiKey(), cancellationToken); + if (principal == null) { - _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); - _notifier = notifier ?? throw new ArgumentNullException(nameof(notifier)); - _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); - _submissions = submissions ?? throw new ArgumentNullException(nameof(submissions)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _deleteService = deletionService ?? throw new ArgumentNullException(nameof(deletionService)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + HttpContext.Response.StatusCode = 401; + return; } - // See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#push-a-package - public async Task Upload(CancellationToken cancellationToken) + try { - var principal = _options.Value.IsReadOnlyMode - ? null - : await _authentication.AuthenticatePrincipalAsync(Request.GetApiKey(), cancellationToken); - if (principal == null) + using (var uploadStream = await Request.GetUploadStreamOrNullAsync(cancellationToken)) { - HttpContext.Response.StatusCode = 401; - return; - } + if (uploadStream == null) + { + HttpContext.Response.StatusCode = 400; + return; + } - try - { - using (var uploadStream = await Request.GetUploadStreamOrNullAsync(cancellationToken)) + // Whether the caller may push depends on the package ID, which is inside the + // package. An unreadable package is left for the indexer to reject. + var packageId = uploadStream.ReadPackageIdOrNull(); + if (packageId != null && + !await _authorization.AuthorizeAsync(principal, PackageAction.Push, packageId, cancellationToken)) + { + HttpContext.Response.StatusCode = 403; + return; + } + + var result = await _submissions.SubmitAsync(uploadStream, cancellationToken); + + // An accepted package claims its ID now, as it would on nuget.org: it is + // the pusher's even while it is validated. + if (result == PackageIndexingResult.Success || result == PackageIndexingResult.Accepted) { - if (uploadStream == null) - { + await _authorization.OnPushedAsync(principal, packageId, cancellationToken); + } + + switch (result) + { + case PackageIndexingResult.InvalidPackage: HttpContext.Response.StatusCode = 400; - return; - } - - // Whether the caller may push depends on the package ID, which is inside the - // package. An unreadable package is left for the indexer to reject. - var packageId = uploadStream.ReadPackageIdOrNull(); - if (packageId != null && - !await _authorization.AuthorizeAsync(principal, PackageAction.Push, packageId, cancellationToken)) - { - HttpContext.Response.StatusCode = 403; - return; - } - - var result = await _submissions.SubmitAsync(uploadStream, cancellationToken); - - // An accepted package claims its ID now, as it would on nuget.org: it is - // the pusher's even while it is validated. - if (result == PackageIndexingResult.Success || result == PackageIndexingResult.Accepted) - { - await _authorization.OnPushedAsync(principal, packageId, cancellationToken); - } - - switch (result) - { - case PackageIndexingResult.InvalidPackage: - HttpContext.Response.StatusCode = 400; - break; - - case PackageIndexingResult.PackageAlreadyExists: - HttpContext.Response.StatusCode = 409; - break; - - case PackageIndexingResult.Success: - HttpContext.Response.StatusCode = 201; - break; - - case PackageIndexingResult.Accepted: - HttpContext.Response.StatusCode = 202; - break; - } + break; + + case PackageIndexingResult.PackageAlreadyExists: + HttpContext.Response.StatusCode = 409; + break; + + case PackageIndexingResult.Success: + HttpContext.Response.StatusCode = 201; + break; + + case PackageIndexingResult.Accepted: + HttpContext.Response.StatusCode = 202; + break; } } - catch (Exception e) - { - _logger.LogError(e, "Exception thrown during package upload"); + } + catch (Exception e) + { + _logger.LogError(e, "Exception thrown during package upload"); - HttpContext.Response.StatusCode = 500; - } + HttpContext.Response.StatusCode = 500; } + } - private async Task AuthorizeManageAsync(string id, CancellationToken cancellationToken) + private async Task AuthorizeManageAsync(string id, CancellationToken cancellationToken) + { + var principal = await _authentication.AuthenticatePrincipalAsync(Request.GetApiKey(), cancellationToken); + if (principal == null) { - var principal = await _authentication.AuthenticatePrincipalAsync(Request.GetApiKey(), cancellationToken); - if (principal == null) - { - return Unauthorized(); - } - - if (!await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken)) - { - return StatusCode(403); - } + return Unauthorized(); + } - return null; + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Manage, id, cancellationToken)) + { + return StatusCode(403); } - [HttpDelete] - public async Task Delete(string id, string version, CancellationToken cancellationToken) + return null; + } + + [HttpDelete] + public async Task Delete(string id, string version, CancellationToken cancellationToken) + { + if (_options.Value.IsReadOnlyMode) { - if (_options.Value.IsReadOnlyMode) - { - return Unauthorized(); - } + return Unauthorized(); + } - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } + if (!NuGetVersion.TryParse(version, out var nugetVersion)) + { + return NotFound(); + } - var denied = await AuthorizeManageAsync(id, cancellationToken); - if (denied != null) - { - return denied; - } + var denied = await AuthorizeManageAsync(id, cancellationToken); + if (denied != null) + { + return denied; + } - if (await _deleteService.TryDeletePackageAsync(id, nugetVersion, cancellationToken)) - { - return NoContent(); - } - else - { - return NotFound(); - } + if (await _deleteService.TryDeletePackageAsync(id, nugetVersion, cancellationToken)) + { + return NoContent(); } + else + { + return NotFound(); + } + } - [HttpPost] - public async Task Relist(string id, string version, CancellationToken cancellationToken) + [HttpPost] + public async Task Relist(string id, string version, CancellationToken cancellationToken) + { + if (_options.Value.IsReadOnlyMode) { - if (_options.Value.IsReadOnlyMode) - { - return Unauthorized(); - } + return Unauthorized(); + } - if (!NuGetVersion.TryParse(version, out var nugetVersion)) - { - return NotFound(); - } + if (!NuGetVersion.TryParse(version, out var nugetVersion)) + { + return NotFound(); + } - var denied = await AuthorizeManageAsync(id, cancellationToken); - if (denied != null) - { - return denied; - } + var denied = await AuthorizeManageAsync(id, cancellationToken); + if (denied != null) + { + return denied; + } - if (await _packages.RelistPackageAsync(id, nugetVersion, cancellationToken)) - { - await _notifier.PackageChangedAsync(id, nugetVersion, cancellationToken); + if (await _packages.RelistPackageAsync(id, nugetVersion, cancellationToken)) + { + await _notifier.PackageChangedAsync(id, nugetVersion, cancellationToken); - return Ok(); - } - else - { - return NotFound(); - } + return Ok(); + } + else + { + return NotFound(); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Controllers/SearchController.cs b/src/BaGet.Web/Controllers/SearchController.cs index 19f0fa8d4..ffe23d345 100644 --- a/src/BaGet.Web/Controllers/SearchController.cs +++ b/src/BaGet.Web/Controllers/SearchController.cs @@ -5,93 +5,92 @@ using BaGet.Protocol.Models; using Microsoft.AspNetCore.Mvc; -namespace BaGet.Web +namespace BaGet.Web; + +public class SearchController : Controller { - public class SearchController : Controller + private readonly ISearchService _searchService; + + public SearchController(ISearchService searchService) { - private readonly ISearchService _searchService; + _searchService = searchService ?? throw new ArgumentNullException(nameof(searchService)); + } + + public async Task> SearchAsync( + [FromQuery(Name = "q")] string query = null, + [FromQuery]int skip = 0, + [FromQuery]int take = 20, + [FromQuery]bool prerelease = false, + [FromQuery]string semVerLevel = null, - public SearchController(ISearchService searchService) + // These are unofficial parameters + [FromQuery]string packageType = null, + [FromQuery]string framework = null, + CancellationToken cancellationToken = default) + { + var request = new SearchRequest { - _searchService = searchService ?? throw new ArgumentNullException(nameof(searchService)); - } + Skip = skip, + Take = take, + IncludePrerelease = prerelease, + IncludeSemVer2 = semVerLevel == "2.0.0", + PackageType = packageType, + Framework = framework, + Query = query ?? string.Empty, + }; + + return await _searchService.SearchAsync(request, cancellationToken); + } - public async Task> SearchAsync( - [FromQuery(Name = "q")] string query = null, - [FromQuery]int skip = 0, - [FromQuery]int take = 20, - [FromQuery]bool prerelease = false, - [FromQuery]string semVerLevel = null, + public async Task> AutocompleteAsync( + [FromQuery(Name = "q")] string autocompleteQuery = null, + [FromQuery(Name = "id")] string versionsQuery = null, + [FromQuery]bool prerelease = false, + [FromQuery]string semVerLevel = null, + [FromQuery]int skip = 0, + [FromQuery]int take = 20, - // These are unofficial parameters - [FromQuery]string packageType = null, - [FromQuery]string framework = null, - CancellationToken cancellationToken = default) + // These are unofficial parameters + [FromQuery]string packageType = null, + CancellationToken cancellationToken = default) + { + // If only "id" is provided, find package versions. Otherwise, find package IDs. + if (versionsQuery != null && autocompleteQuery == null) { - var request = new SearchRequest + var request = new VersionsRequest { - Skip = skip, - Take = take, IncludePrerelease = prerelease, IncludeSemVer2 = semVerLevel == "2.0.0", - PackageType = packageType, - Framework = framework, - Query = query ?? string.Empty, + PackageId = versionsQuery, }; - return await _searchService.SearchAsync(request, cancellationToken); + return await _searchService.ListPackageVersionsAsync(request, cancellationToken); } - - public async Task> AutocompleteAsync( - [FromQuery(Name = "q")] string autocompleteQuery = null, - [FromQuery(Name = "id")] string versionsQuery = null, - [FromQuery]bool prerelease = false, - [FromQuery]string semVerLevel = null, - [FromQuery]int skip = 0, - [FromQuery]int take = 20, - - // These are unofficial parameters - [FromQuery]string packageType = null, - CancellationToken cancellationToken = default) + else { - // If only "id" is provided, find package versions. Otherwise, find package IDs. - if (versionsQuery != null && autocompleteQuery == null) + var request = new AutocompleteRequest { - var request = new VersionsRequest - { - IncludePrerelease = prerelease, - IncludeSemVer2 = semVerLevel == "2.0.0", - PackageId = versionsQuery, - }; - - return await _searchService.ListPackageVersionsAsync(request, cancellationToken); - } - else - { - var request = new AutocompleteRequest - { - IncludePrerelease = prerelease, - IncludeSemVer2 = semVerLevel == "2.0.0", - PackageType = packageType, - Skip = skip, - Take = take, - Query = autocompleteQuery, - }; + IncludePrerelease = prerelease, + IncludeSemVer2 = semVerLevel == "2.0.0", + PackageType = packageType, + Skip = skip, + Take = take, + Query = autocompleteQuery, + }; - return await _searchService.AutocompleteAsync(request, cancellationToken); - } + return await _searchService.AutocompleteAsync(request, cancellationToken); } + } - public async Task> DependentsAsync( - [FromQuery] string packageId = null, - CancellationToken cancellationToken = default) + public async Task> DependentsAsync( + [FromQuery] string packageId = null, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(packageId)) { - if (string.IsNullOrWhiteSpace(packageId)) - { - return BadRequest(); - } - - return await _searchService.FindDependentsAsync(packageId, cancellationToken); + return BadRequest(); } + + return await _searchService.FindDependentsAsync(packageId, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Controllers/ServiceIndexController.cs b/src/BaGet.Web/Controllers/ServiceIndexController.cs index af1806ffa..d7c53146e 100644 --- a/src/BaGet.Web/Controllers/ServiceIndexController.cs +++ b/src/BaGet.Web/Controllers/ServiceIndexController.cs @@ -5,25 +5,24 @@ using BaGet.Protocol.Models; using Microsoft.AspNetCore.Mvc; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// The NuGet Service Index. This aids NuGet client to discover this server's services. +/// +public class ServiceIndexController : Controller { - /// - /// The NuGet Service Index. This aids NuGet client to discover this server's services. - /// - public class ServiceIndexController : Controller - { - private readonly IServiceIndexService _serviceIndex; + private readonly IServiceIndexService _serviceIndex; - public ServiceIndexController(IServiceIndexService serviceIndex) - { - _serviceIndex = serviceIndex ?? throw new ArgumentNullException(nameof(serviceIndex)); - } + public ServiceIndexController(IServiceIndexService serviceIndex) + { + _serviceIndex = serviceIndex ?? throw new ArgumentNullException(nameof(serviceIndex)); + } - // GET v3/index - [HttpGet] - public async Task GetAsync(CancellationToken cancellationToken) - { - return await _serviceIndex.GetAsync(cancellationToken); - } + // GET v3/index + [HttpGet] + public async Task GetAsync(CancellationToken cancellationToken) + { + return await _serviceIndex.GetAsync(cancellationToken); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Controllers/SymbolController.cs b/src/BaGet.Web/Controllers/SymbolController.cs index 025796be7..f354077b6 100644 --- a/src/BaGet.Web/Controllers/SymbolController.cs +++ b/src/BaGet.Web/Controllers/SymbolController.cs @@ -6,98 +6,97 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace BaGet.Web +namespace BaGet.Web; + +public class SymbolController : Controller { - public class SymbolController : Controller + private readonly IAuthenticationService _authentication; + private readonly IPackageAuthorizationService _authorization; + private readonly ISymbolIndexingService _indexer; + private readonly ISymbolStorageService _storage; + private readonly IOptionsSnapshot _options; + private readonly ILogger _logger; + + public SymbolController( + IAuthenticationService authentication, + ISymbolIndexingService indexer, + ISymbolStorageService storage, + IOptionsSnapshot options, + ILogger logger, + IPackageAuthorizationService authorization) { - private readonly IAuthenticationService _authentication; - private readonly IPackageAuthorizationService _authorization; - private readonly ISymbolIndexingService _indexer; - private readonly ISymbolStorageService _storage; - private readonly IOptionsSnapshot _options; - private readonly ILogger _logger; + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public SymbolController( - IAuthenticationService authentication, - ISymbolIndexingService indexer, - ISymbolStorageService storage, - IOptionsSnapshot options, - ILogger logger, - IPackageAuthorizationService authorization) + // See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#push-a-package + public async Task Upload(CancellationToken cancellationToken) + { + var principal = _options.Value.IsReadOnlyMode + ? null + : await _authentication.AuthenticatePrincipalAsync(Request.GetApiKey(), cancellationToken); + if (principal == null) { - _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); - _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); - _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer)); - _storage = storage ?? throw new ArgumentNullException(nameof(storage)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + HttpContext.Response.StatusCode = 401; + return; } - // See: https://docs.microsoft.com/en-us/nuget/api/package-publish-resource#push-a-package - public async Task Upload(CancellationToken cancellationToken) + try { - var principal = _options.Value.IsReadOnlyMode - ? null - : await _authentication.AuthenticatePrincipalAsync(Request.GetApiKey(), cancellationToken); - if (principal == null) - { - HttpContext.Response.StatusCode = 401; - return; - } - - try + using (var uploadStream = await Request.GetUploadStreamOrNullAsync(cancellationToken)) { - using (var uploadStream = await Request.GetUploadStreamOrNullAsync(cancellationToken)) + if (uploadStream == null) { - if (uploadStream == null) - { - HttpContext.Response.StatusCode = 400; - return; - } + HttpContext.Response.StatusCode = 400; + return; + } - var packageId = uploadStream.ReadPackageIdOrNull(); - if (packageId != null && - !await _authorization.AuthorizeAsync(principal, PackageAction.Push, packageId, cancellationToken)) - { - HttpContext.Response.StatusCode = 403; - return; - } + var packageId = uploadStream.ReadPackageIdOrNull(); + if (packageId != null && + !await _authorization.AuthorizeAsync(principal, PackageAction.Push, packageId, cancellationToken)) + { + HttpContext.Response.StatusCode = 403; + return; + } - var result = await _indexer.IndexAsync(uploadStream, cancellationToken); + var result = await _indexer.IndexAsync(uploadStream, cancellationToken); - switch (result) - { - case SymbolIndexingResult.InvalidSymbolPackage: - HttpContext.Response.StatusCode = 400; - break; + switch (result) + { + case SymbolIndexingResult.InvalidSymbolPackage: + HttpContext.Response.StatusCode = 400; + break; - case SymbolIndexingResult.PackageNotFound: - HttpContext.Response.StatusCode = 404; - break; + case SymbolIndexingResult.PackageNotFound: + HttpContext.Response.StatusCode = 404; + break; - case SymbolIndexingResult.Success: - HttpContext.Response.StatusCode = 201; - break; - } + case SymbolIndexingResult.Success: + HttpContext.Response.StatusCode = 201; + break; } } - catch (Exception e) - { - _logger.LogError(e, "Exception thrown during symbol upload"); + } + catch (Exception e) + { + _logger.LogError(e, "Exception thrown during symbol upload"); - HttpContext.Response.StatusCode = 500; - } + HttpContext.Response.StatusCode = 500; } + } - public async Task Get(string file, string key) + public async Task Get(string file, string key) + { + var pdbStream = await _storage.GetPortablePdbContentStreamOrNullAsync(file, key); + if (pdbStream == null) { - var pdbStream = await _storage.GetPortablePdbContentStreamOrNullAsync(file, key); - if (pdbStream == null) - { - return NotFound(); - } - - return File(pdbStream, "application/octet-stream"); + return NotFound(); } + + return File(pdbStream, "application/octet-stream"); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Controllers/VulnerabilityController.cs b/src/BaGet.Web/Controllers/VulnerabilityController.cs index 6c3c2d04c..12aa6dd6b 100644 --- a/src/BaGet.Web/Controllers/VulnerabilityController.cs +++ b/src/BaGet.Web/Controllers/VulnerabilityController.cs @@ -7,115 +7,114 @@ using BaGet.Core; using Microsoft.AspNetCore.Mvc; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// The VulnerabilityInfo resource. The client downloads every page and matches the +/// advisories against its restore graph itself. +/// See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info +/// +public class VulnerabilityController : Controller { /// - /// The VulnerabilityInfo resource. The client downloads every page and matches the - /// advisories against its restore graph itself. - /// See: https://learn.microsoft.com/en-us/nuget/api/vulnerability-info + /// All advisories fit in one page: the protocol allows several, but a single page + /// is valid and keeps the client's download to one request. /// - public class VulnerabilityController : Controller - { - /// - /// All advisories fit in one page: the protocol allows several, but a single page - /// is valid and keeps the client's download to one request. - /// - internal const string BasePageName = "base"; + internal const string BasePageName = "base"; - private readonly IPackageDatabase _packages; - private readonly IUrlGenerator _url; + private readonly IPackageDatabase _packages; + private readonly IUrlGenerator _url; - public VulnerabilityController(IPackageDatabase packages, IUrlGenerator url) - { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + public VulnerabilityController(IPackageDatabase packages, IUrlGenerator url) + { + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - [HttpGet] - public IActionResult Index() + [HttpGet] + public IActionResult Index() + { + // The client re-downloads a page when its "@updated" changes. Nothing records + // when an advisory was last set, so the current time is reported: always + // correct, at the cost of the client never reusing its cached copy. + var index = new[] { - // The client re-downloads a page when its "@updated" changes. Nothing records - // when an advisory was last set, so the current time is reported: always - // correct, at the cost of the client never reusing its cached copy. - var index = new[] + new VulnerabilityPageEntry { - new VulnerabilityPageEntry - { - Name = BasePageName, - Url = _url.GetVulnerabilityPageUrl(BasePageName), - Updated = DateTimeOffset.UtcNow, - }, - }; + Name = BasePageName, + Url = _url.GetVulnerabilityPageUrl(BasePageName), + Updated = DateTimeOffset.UtcNow, + }, + }; - return Json(index); - } + return Json(index); + } - [HttpGet] - public async Task Page(string pageName, CancellationToken cancellationToken) + [HttpGet] + public async Task Page(string pageName, CancellationToken cancellationToken) + { + if (!string.Equals(pageName, BasePageName, StringComparison.Ordinal)) { - if (!string.Equals(pageName, BasePageName, StringComparison.Ordinal)) - { - return NotFound(); - } + return NotFound(); + } - var vulnerabilities = await _packages.GetAllVulnerabilitiesAsync(cancellationToken); + var vulnerabilities = await _packages.GetAllVulnerabilitiesAsync(cancellationToken); - return Json(BuildPage(vulnerabilities)); - } + return Json(BuildPage(vulnerabilities)); + } - /// - /// Group the advisories by lowercase package id. An advisory without its own range - /// applies to exactly the version it was recorded against. - /// - internal static IReadOnlyDictionary> BuildPage( - IEnumerable vulnerabilities) - { - return vulnerabilities - .Where(v => v.Package != null) - .Select(v => new + /// + /// Group the advisories by lowercase package id. An advisory without its own range + /// applies to exactly the version it was recorded against. + /// + internal static IReadOnlyDictionary> BuildPage( + IEnumerable vulnerabilities) + { + return vulnerabilities + .Where(v => v.Package != null) + .Select(v => new + { + Id = v.Package.Id.ToLowerInvariant(), + Item = new VulnerabilityPageItem { - Id = v.Package.Id.ToLowerInvariant(), - Item = new VulnerabilityPageItem - { - Url = v.AdvisoryUrl, - Severity = v.Severity, - Versions = v.VersionRange ?? $"[{v.Package.Version.ToNormalizedString()}]", - }, - }) - .GroupBy(x => x.Id, StringComparer.Ordinal) - .OrderBy(g => g.Key, StringComparer.Ordinal) - .ToDictionary( - g => g.Key, - g => (IReadOnlyList)g - .Select(x => x.Item) - .GroupBy(i => (i.Url, i.Severity, i.Versions)) - .Select(d => d.First()) - .ToList(), - StringComparer.Ordinal); - } + Url = v.AdvisoryUrl, + Severity = v.Severity, + Versions = v.VersionRange ?? $"[{v.Package.Version.ToNormalizedString()}]", + }, + }) + .GroupBy(x => x.Id, StringComparer.Ordinal) + .OrderBy(g => g.Key, StringComparer.Ordinal) + .ToDictionary( + g => g.Key, + g => (IReadOnlyList)g + .Select(x => x.Item) + .GroupBy(i => (i.Url, i.Severity, i.Versions)) + .Select(d => d.First()) + .ToList(), + StringComparer.Ordinal); } +} - public class VulnerabilityPageEntry - { - [JsonPropertyName("@name")] - public string Name { get; set; } +public class VulnerabilityPageEntry +{ + [JsonPropertyName("@name")] + public string Name { get; set; } - [JsonPropertyName("@id")] - public string Url { get; set; } + [JsonPropertyName("@id")] + public string Url { get; set; } - [JsonPropertyName("@updated")] - public DateTimeOffset Updated { get; set; } - } + [JsonPropertyName("@updated")] + public DateTimeOffset Updated { get; set; } +} - public class VulnerabilityPageItem - { - [JsonPropertyName("severity")] - public int Severity { get; set; } +public class VulnerabilityPageItem +{ + [JsonPropertyName("severity")] + public int Severity { get; set; } - [JsonPropertyName("url")] - public string Url { get; set; } + [JsonPropertyName("url")] + public string Url { get; set; } - [JsonPropertyName("versions")] - public string Versions { get; set; } - } -} + [JsonPropertyName("versions")] + public string Versions { get; set; } +} \ No newline at end of file diff --git a/src/BaGet.Web/Extensions/HttpRequestExtensions.cs b/src/BaGet.Web/Extensions/HttpRequestExtensions.cs index 1175663c8..edd701794 100644 --- a/src/BaGet.Web/Extensions/HttpRequestExtensions.cs +++ b/src/BaGet.Web/Extensions/HttpRequestExtensions.cs @@ -6,64 +6,63 @@ using Microsoft.AspNetCore.Http; using NuGet.Packaging; -namespace BaGet.Web +namespace BaGet.Web; + +public static class HttpRequestExtensions { - public static class HttpRequestExtensions - { - public const string ApiKeyHeader = "X-NuGet-ApiKey"; + public const string ApiKeyHeader = "X-NuGet-ApiKey"; - public static async Task GetUploadStreamOrNullAsync(this HttpRequest request, CancellationToken cancellationToken) + public static async Task GetUploadStreamOrNullAsync(this HttpRequest request, CancellationToken cancellationToken) + { + // Try to get the nupkg from the multipart/form-data. If that's empty, + // fallback to the request's body. + Stream rawUploadStream = null; + try { - // Try to get the nupkg from the multipart/form-data. If that's empty, - // fallback to the request's body. - Stream rawUploadStream = null; - try + if (request.HasFormContentType && request.Form.Files.Count > 0) { - if (request.HasFormContentType && request.Form.Files.Count > 0) - { - rawUploadStream = request.Form.Files[0].OpenReadStream(); - } - else - { - rawUploadStream = request.Body; - } - - // Convert the upload stream into a temporary file stream to - // minimize memory usage. - return await rawUploadStream?.AsTemporaryFileStreamAsync(cancellationToken); + rawUploadStream = request.Form.Files[0].OpenReadStream(); } - finally + else { - rawUploadStream?.Dispose(); + rawUploadStream = request.Body; } + + // Convert the upload stream into a temporary file stream to + // minimize memory usage. + return await rawUploadStream?.AsTemporaryFileStreamAsync(cancellationToken); } + finally + { + rawUploadStream?.Dispose(); + } + } - /// - /// Read the package ID from an uploaded package, or null if it cannot be read. The - /// stream is left open and rewound. - /// - public static string ReadPackageIdOrNull(this Stream package) + /// + /// Read the package ID from an uploaded package, or null if it cannot be read. The + /// stream is left open and rewound. + /// + public static string ReadPackageIdOrNull(this Stream package) + { + try { - try + using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) { - using (var reader = new PackageArchiveReader(package, leaveStreamOpen: true)) - { - return reader.NuspecReader.GetId(); - } - } - catch (Exception) - { - return null; - } - finally - { - package.Position = 0; + return reader.NuspecReader.GetId(); } } - - public static string GetApiKey(this HttpRequest request) + catch (Exception) { - return request.Headers[ApiKeyHeader]; + return null; } + finally + { + package.Position = 0; + } + } + + public static string GetApiKey(this HttpRequest request) + { + return request.Headers[ApiKeyHeader]; } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Extensions/IApplicationBuilderExtensions.cs b/src/BaGet.Web/Extensions/IApplicationBuilderExtensions.cs index f9bffac27..0c5341078 100644 --- a/src/BaGet.Web/Extensions/IApplicationBuilderExtensions.cs +++ b/src/BaGet.Web/Extensions/IApplicationBuilderExtensions.cs @@ -1,15 +1,14 @@ using System; using Microsoft.AspNetCore.Builder; -namespace BaGet.Web +namespace BaGet.Web; + +public static class IApplicationBuilderExtensions { - public static class IApplicationBuilderExtensions + public static IApplicationBuilder UseOperationCancelledMiddleware(this IApplicationBuilder app) { - public static IApplicationBuilder UseOperationCancelledMiddleware(this IApplicationBuilder app) - { - if (app == null) throw new ArgumentNullException(nameof(app)); + if (app == null) throw new ArgumentNullException(nameof(app)); - return app.UseMiddleware(); - } + return app.UseMiddleware(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Extensions/IHostExtensions.cs b/src/BaGet.Web/Extensions/IHostExtensions.cs index e2757fa48..9ce03cc8f 100644 --- a/src/BaGet.Web/Extensions/IHostExtensions.cs +++ b/src/BaGet.Web/Extensions/IHostExtensions.cs @@ -6,44 +6,43 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; -namespace BaGet.Web +namespace BaGet.Web; + +public static class IHostExtensions { - public static class IHostExtensions + public static IHostBuilder UseBaGet(this IHostBuilder host, Action configure) { - public static IHostBuilder UseBaGet(this IHostBuilder host, Action configure) + return host.ConfigureServices(services => { - return host.ConfigureServices(services => - { - services.AddBaGetWebApplication(configure); - }); - } + services.AddBaGetWebApplication(configure); + }); + } - public static async Task RunMigrationsAsync( - this IHost host, - CancellationToken cancellationToken = default) - { - // Run migrations if necessary. - var options = host.Services.GetRequiredService>(); + public static async Task RunMigrationsAsync( + this IHost host, + CancellationToken cancellationToken = default) + { + // Run migrations if necessary. + var options = host.Services.GetRequiredService>(); - if (options.Value.RunMigrationsAtStartup) + if (options.Value.RunMigrationsAtStartup) + { + using (var scope = host.Services.CreateScope()) { - using (var scope = host.Services.CreateScope()) + var ctx = scope.ServiceProvider.GetService(); + if (ctx != null) { - var ctx = scope.ServiceProvider.GetService(); - if (ctx != null) - { - await ctx.RunMigrationsAsync(cancellationToken); - } + await ctx.RunMigrationsAsync(cancellationToken); } } } + } - public static bool ValidateStartupOptions(this IHost host) - { - return host - .Services - .GetRequiredService() - .Validate(); - } + public static bool ValidateStartupOptions(this IHost host) + { + return host + .Services + .GetRequiredService() + .Validate(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs b/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs index a46dae33a..07e535d93 100644 --- a/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs +++ b/src/BaGet.Web/Extensions/IServiceCollectionExtensions.cs @@ -8,41 +8,40 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.DependencyInjection; -namespace BaGet +namespace BaGet; + +public static class IServiceCollectionExtensions { - public static class IServiceCollectionExtensions + public static IServiceCollection AddBaGetWebApplication( + this IServiceCollection services, + Action configureAction) { - public static IServiceCollection AddBaGetWebApplication( - this IServiceCollection services, - Action configureAction) - { - services - .AddRouting(options => options.LowercaseUrls = true) - .AddControllers() - .AddApplicationPart(typeof(PackageContentController).Assembly) - .AddJsonOptions(options => - { - options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; - }); - - services.AddRazorPages(options => + services + .AddRouting(options => options.LowercaseUrls = true) + .AddControllers() + .AddApplicationPart(typeof(PackageContentController).Assembly) + .AddJsonOptions(options => { - // Add /packages route to the Index page - options.Conventions.AddPageRoute("/Index", "/packages"); + options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; }); - services.AddHttpContextAccessor(); - services.AddTransient(); + services.AddRazorPages(options => + { + // Add /packages route to the Index page + options.Conventions.AddPageRoute("/Index", "/packages"); + }); + + services.AddHttpContextAccessor(); + services.AddTransient(); - services.AddBaGetApplication(configureAction); - services.AddBaGetCatalog(); - services.AddBaGetValidation(); + services.AddBaGetApplication(configureAction); + services.AddBaGetCatalog(); + services.AddBaGetValidation(); - // Browser uploads are staged between their two requests; whatever nobody comes - // back to confirm or cancel is collected here. - services.AddHostedService(); + // Browser uploads are staged between their two requests; whatever nobody comes + // back to confirm or cancel is collected here. + services.AddHostedService(); - return services; - } + return services; } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Extensions/RazorExtensions.cs b/src/BaGet.Web/Extensions/RazorExtensions.cs index 1a48ecde6..87b1e8fd0 100644 --- a/src/BaGet.Web/Extensions/RazorExtensions.cs +++ b/src/BaGet.Web/Extensions/RazorExtensions.cs @@ -1,12 +1,11 @@ using Humanizer; -namespace BaGet.Web +namespace BaGet.Web; + +public static class RazorExtensions { - public static class RazorExtensions + public static string ToMetric(this long value) { - public static string ToMetric(this long value) - { - return ((double) value).ToMetric(); - } + return ((double) value).ToMetric(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/NavLinkTagHelper.cs b/src/BaGet.Web/NavLinkTagHelper.cs index 3bee8c5ce..acb0eb0bd 100644 --- a/src/BaGet.Web/NavLinkTagHelper.cs +++ b/src/BaGet.Web/NavLinkTagHelper.cs @@ -3,84 +3,83 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Razor.TagHelpers; -namespace BaGet.Web +namespace BaGet.Web; + +[HtmlTargetElement(Attributes = "nav-link")] +public class NavLinkTagHelper : TagHelper { - [HtmlTargetElement(Attributes = "nav-link")] - public class NavLinkTagHelper : TagHelper + private const string ActiveClass = "active"; + private const string IndexPage = "/Index"; + private const string PackagesPath = "/packages"; + + private readonly IHttpContextAccessor _accessor; + + public NavLinkTagHelper(IHttpContextAccessor accessor) { - private const string ActiveClass = "active"; - private const string IndexPage = "/Index"; - private const string PackagesPath = "/packages"; + _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor)); + } - private readonly IHttpContextAccessor _accessor; + [HtmlAttributeName("asp-page")] + public string Page { get; set; } - public NavLinkTagHelper(IHttpContextAccessor accessor) + public override void Process(TagHelperContext context, TagHelperOutput output) + { + if (!IsActiveLink()) { - _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor)); + return; } - [HtmlAttributeName("asp-page")] - public string Page { get; set; } + // This helper applies to any element carrying "nav-link", so it adds its class + // instead of replacing the classes the markup already set. + var existing = output.Attributes.ContainsName("class") + ? output.Attributes["class"].Value?.ToString() + : null; - public override void Process(TagHelperContext context, TagHelperOutput output) - { - if (!IsActiveLink()) - { - return; - } - - // This helper applies to any element carrying "nav-link", so it adds its class - // instead of replacing the classes the markup already set. - var existing = output.Attributes.ContainsName("class") - ? output.Attributes["class"].Value?.ToString() - : null; + output.Attributes.SetAttribute("class", WithActiveClass(existing)); + } - output.Attributes.SetAttribute("class", WithActiveClass(existing)); + private static string WithActiveClass(string classes) + { + if (string.IsNullOrWhiteSpace(classes)) + { + return ActiveClass; } - private static string WithActiveClass(string classes) + foreach (var name in classes.Split(' ', StringSplitOptions.RemoveEmptyEntries)) { - if (string.IsNullOrWhiteSpace(classes)) + if (string.Equals(name, ActiveClass, StringComparison.Ordinal)) { - return ActiveClass; + return classes; } - - foreach (var name in classes.Split(' ', StringSplitOptions.RemoveEmptyEntries)) - { - if (string.Equals(name, ActiveClass, StringComparison.Ordinal)) - { - return classes; - } - } - - return $"{classes} {ActiveClass}"; } - private bool IsActiveLink() - { - var httpContext = _accessor.HttpContext; - var pageDescriptor = httpContext?.GetEndpoint()?.Metadata.GetMetadata(); + return $"{classes} {ActiveClass}"; + } + + private bool IsActiveLink() + { + var httpContext = _accessor.HttpContext; + var pageDescriptor = httpContext?.GetEndpoint()?.Metadata.GetMetadata(); - if (pageDescriptor == null) return false; - if (pageDescriptor.AreaName != null) return false; + if (pageDescriptor == null) return false; + if (pageDescriptor.AreaName != null) return false; - // When the link names a page, that name alone decides whether it is active. - // Falling through to the path check below would light up every nav link on the - // pages that check covers. - if (!string.IsNullOrEmpty(Page)) - { - return pageDescriptor.ViewEnginePath == Page; - } + // When the link names a page, that name alone decides whether it is active. + // Falling through to the path check below would light up every nav link on the + // pages that check covers. + if (!string.IsNullOrEmpty(Page)) + { + return pageDescriptor.ViewEnginePath == Page; + } - // The packages link names no page: both "/" and "/packages" render the index. - if (pageDescriptor.ViewEnginePath != IndexPage) return false; + // The packages link names no page: both "/" and "/packages" render the index. + if (pageDescriptor.ViewEnginePath != IndexPage) return false; - // Routing is case-insensitive and tolerates a trailing slash, so the comparison - // must be too. - var path = httpContext.Request.Path.Value?.TrimEnd('/'); + // Routing is case-insensitive and tolerates a trailing slash, so the comparison + // must be too. + var path = httpContext.Request.Path.Value?.TrimEnd('/'); - return string.IsNullOrEmpty(path) - || string.Equals(path, PackagesPath, StringComparison.OrdinalIgnoreCase); - } + return string.IsNullOrEmpty(path) + || string.Equals(path, PackagesPath, StringComparison.OrdinalIgnoreCase); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/OperationCancelledMiddleware.cs b/src/BaGet.Web/OperationCancelledMiddleware.cs index e4f1faf79..aa4426688 100644 --- a/src/BaGet.Web/OperationCancelledMiddleware.cs +++ b/src/BaGet.Web/OperationCancelledMiddleware.cs @@ -4,56 +4,55 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// Captures and converts to HTTP 409 response. +/// Based off: https://github.com/aspnet/AspNetCore/blob/28157e62597bf0e043bc7e937e44c5ec81946b83/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageMiddleware.cs +/// +public class OperationCancelledMiddleware { - /// - /// Captures and converts to HTTP 409 response. - /// Based off: https://github.com/aspnet/AspNetCore/blob/28157e62597bf0e043bc7e937e44c5ec81946b83/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageMiddleware.cs - /// - public class OperationCancelledMiddleware + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + public OperationCancelledMiddleware(RequestDelegate next, ILogger logger) { - private readonly RequestDelegate _next; - private readonly ILogger _logger; + _next = next ?? throw new ArgumentNullException(nameof(next)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - public OperationCancelledMiddleware(RequestDelegate next, ILogger logger) + public async Task Invoke(HttpContext context) + { + try { - _next = next ?? throw new ArgumentNullException(nameof(next)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + await _next(context); } - - public async Task Invoke(HttpContext context) + catch (Exception e) when (ShouldHandleException(context, e)) { try { - await _next(context); + _logger.LogWarning("Request cancelled"); + + context.Response.Clear(); + context.Response.StatusCode = (int)HttpStatusCode.Conflict; + return; } - catch (Exception e) when (ShouldHandleException(context, e)) + catch (Exception) { - try - { - _logger.LogWarning("Request cancelled"); - - context.Response.Clear(); - context.Response.StatusCode = (int)HttpStatusCode.Conflict; - return; - } - catch (Exception) - { - // If there's an exception, rethrow the original exception. - } - - throw; + // If there's an exception, rethrow the original exception. } - bool ShouldHandleException(HttpContext ctx, Exception e) - { - if (ctx.Response.HasStarted) return false; + throw; + } - if (e is OperationCanceledException) return true; - if (e.InnerException is OperationCanceledException) return true; + bool ShouldHandleException(HttpContext ctx, Exception e) + { + if (ctx.Response.HasStarted) return false; - return false; - } + if (e is OperationCanceledException) return true; + if (e.InnerException is OperationCanceledException) return true; + + return false; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/PackageDependencies.cs b/src/BaGet.Web/PackageDependencies.cs index 2ddfdd55b..b61225e08 100644 --- a/src/BaGet.Web/PackageDependencies.cs +++ b/src/BaGet.Web/PackageDependencies.cs @@ -5,94 +5,93 @@ using NuGet.Frameworks; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// A package's dependencies grouped by target framework, for display. Shared by the +/// package page and the upload preview, which must describe the same package the same +/// way: a preview that grouped or named frameworks differently would be a preview of +/// something else. +/// +public static class PackageDependencies { - /// - /// A package's dependencies grouped by target framework, for display. Shared by the - /// package page and the upload preview, which must describe the same package the same - /// way: a preview that grouped or named frameworks differently would be a preview of - /// something else. - /// - public static class PackageDependencies + public static IReadOnlyList GroupByFramework( + IEnumerable dependencies) { - public static IReadOnlyList GroupByFramework( - IEnumerable dependencies) - { - if (dependencies == null) return Array.Empty(); - - return dependencies - .GroupBy(d => d.TargetFramework) - .Select(group => new DependencyGroupModel - { - Name = PrettifyTargetFramework(group.Key), - Dependencies = group - .Where(d => d.Id != null) - .Select(d => new DependencyModel - { - PackageId = d.Id, - VersionSpec = (d.VersionRange != null) - ? VersionRange.Parse(d.VersionRange).PrettyPrint() - : string.Empty - }) - .ToList() - }) - .ToList(); - } - - public static string PrettifyTargetFramework(string targetFramework) - { - if (targetFramework == null) return "All Frameworks"; + if (dependencies == null) return Array.Empty(); - NuGetFramework framework; - try - { - framework = NuGetFramework.Parse(targetFramework); - } - catch (Exception) + return dependencies + .GroupBy(d => d.TargetFramework) + .Select(group => new DependencyGroupModel { - return targetFramework; - } + Name = PrettifyTargetFramework(group.Key), + Dependencies = group + .Where(d => d.Id != null) + .Select(d => new DependencyModel + { + PackageId = d.Id, + VersionSpec = (d.VersionRange != null) + ? VersionRange.Parse(d.VersionRange).PrettyPrint() + : string.Empty + }) + .ToList() + }) + .ToList(); + } - string frameworkName; - if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.NetCoreApp, - StringComparison.OrdinalIgnoreCase)) - { - frameworkName = (framework.Version.Major >= 5) - ? ".NET" - : ".NET Core"; - } - else if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.NetStandard, - StringComparison.OrdinalIgnoreCase)) - { - frameworkName = ".NET Standard"; - } - else if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.Net, - StringComparison.OrdinalIgnoreCase)) - { - frameworkName = ".NET Framework"; - } - else - { - frameworkName = framework.Framework; - } + public static string PrettifyTargetFramework(string targetFramework) + { + if (targetFramework == null) return "All Frameworks"; - var frameworkVersion = (framework.Version.Build == 0) - ? framework.Version.ToString(2) - : framework.Version.ToString(3); + NuGetFramework framework; + try + { + framework = NuGetFramework.Parse(targetFramework); + } + catch (Exception) + { + return targetFramework; + } - return $"{frameworkName} {frameworkVersion}"; + string frameworkName; + if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.NetCoreApp, + StringComparison.OrdinalIgnoreCase)) + { + frameworkName = (framework.Version.Major >= 5) + ? ".NET" + : ".NET Core"; + } + else if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.NetStandard, + StringComparison.OrdinalIgnoreCase)) + { + frameworkName = ".NET Standard"; + } + else if (framework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.Net, + StringComparison.OrdinalIgnoreCase)) + { + frameworkName = ".NET Framework"; + } + else + { + frameworkName = framework.Framework; } - } - public class DependencyGroupModel - { - public string Name { get; set; } - public IReadOnlyList Dependencies { get; set; } - } + var frameworkVersion = (framework.Version.Build == 0) + ? framework.Version.ToString(2) + : framework.Version.ToString(3); - public record DependencyModel - { - public string PackageId { get; init; } - public string VersionSpec { get; init; } + return $"{frameworkName} {frameworkVersion}"; } } + +public class DependencyGroupModel +{ + public string Name { get; set; } + public IReadOnlyList Dependencies { get; set; } +} + +public record DependencyModel +{ + public string PackageId { get; init; } + public string VersionSpec { get; init; } +} \ No newline at end of file diff --git a/src/BaGet.Web/Pages/Index.cshtml.cs b/src/BaGet.Web/Pages/Index.cshtml.cs index f9f5e15e5..9f78594e1 100644 --- a/src/BaGet.Web/Pages/Index.cshtml.cs +++ b/src/BaGet.Web/Pages/Index.cshtml.cs @@ -8,60 +8,59 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace BaGet.Web +namespace BaGet.Web; + +public class IndexModel : PageModel { - public class IndexModel : PageModel - { - private readonly ISearchService _search; + private readonly ISearchService _search; - public IndexModel(ISearchService search) - { - _search = search ?? throw new ArgumentNullException(nameof(search)); - } + public IndexModel(ISearchService search) + { + _search = search ?? throw new ArgumentNullException(nameof(search)); + } - public const int ResultsPerPage = 20; + public const int ResultsPerPage = 20; - [BindProperty(Name = "q", SupportsGet = true)] - public string Query { get; set; } + [BindProperty(Name = "q", SupportsGet = true)] + public string Query { get; set; } - [BindProperty(Name = "p", SupportsGet = true)] - [Range(1, int.MaxValue)] - public int PageIndex { get; set; } = 1; + [BindProperty(Name = "p", SupportsGet = true)] + [Range(1, int.MaxValue)] + public int PageIndex { get; set; } = 1; - [BindProperty(SupportsGet = true)] - public string PackageType { get; set; } = "any"; + [BindProperty(SupportsGet = true)] + public string PackageType { get; set; } = "any"; - [BindProperty(SupportsGet = true)] - public string Framework { get; set; } = "any"; + [BindProperty(SupportsGet = true)] + public string Framework { get; set; } = "any"; - [BindProperty(SupportsGet = true)] - public bool Prerelease { get; set; } = true; + [BindProperty(SupportsGet = true)] + public bool Prerelease { get; set; } = true; - public IReadOnlyList Packages { get; private set; } + public IReadOnlyList Packages { get; private set; } - public async Task OnGetAsync(CancellationToken cancellationToken) - { - if (!ModelState.IsValid) return BadRequest(); + public async Task OnGetAsync(CancellationToken cancellationToken) + { + if (!ModelState.IsValid) return BadRequest(); - var packageType = PackageType == "any" ? null : PackageType; - var framework = Framework == "any" ? null : Framework; + var packageType = PackageType == "any" ? null : PackageType; + var framework = Framework == "any" ? null : Framework; - var search = await _search.SearchAsync( - new SearchRequest - { - Skip = (PageIndex - 1) * ResultsPerPage, - Take = ResultsPerPage, - IncludePrerelease = Prerelease, - IncludeSemVer2 = true, - PackageType = packageType, - Framework = framework, - Query = Query, - }, - cancellationToken); + var search = await _search.SearchAsync( + new SearchRequest + { + Skip = (PageIndex - 1) * ResultsPerPage, + Take = ResultsPerPage, + IncludePrerelease = Prerelease, + IncludeSemVer2 = true, + PackageType = packageType, + Framework = framework, + Query = Query, + }, + cancellationToken); - Packages = search.Data; + Packages = search.Data; - return Page(); - } + return Page(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Pages/Package.cshtml.cs b/src/BaGet.Web/Pages/Package.cshtml.cs index 28a27fbec..22b53354c 100644 --- a/src/BaGet.Web/Pages/Package.cshtml.cs +++ b/src/BaGet.Web/Pages/Package.cshtml.cs @@ -9,135 +9,134 @@ using Microsoft.AspNetCore.Mvc.RazorPages; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +public class PackageModel : PageModel { - public class PackageModel : PageModel + private readonly IPackageService _packages; + private readonly IPackageContentService _content; + private readonly ISearchService _search; + private readonly IUrlGenerator _url; + + public PackageModel( + IPackageService packages, + IPackageContentService content, + ISearchService search, + IUrlGenerator url) { - private readonly IPackageService _packages; - private readonly IPackageContentService _content; - private readonly ISearchService _search; - private readonly IUrlGenerator _url; - - public PackageModel( - IPackageService packages, - IPackageContentService content, - ISearchService search, - IUrlGenerator url) - { - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _content = content ?? throw new ArgumentNullException(nameof(content)); - _search = search ?? throw new ArgumentNullException(nameof(search)); - _url = url ?? throw new ArgumentNullException(nameof(url)); - } + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _content = content ?? throw new ArgumentNullException(nameof(content)); + _search = search ?? throw new ArgumentNullException(nameof(search)); + _url = url ?? throw new ArgumentNullException(nameof(url)); + } - public bool Found { get; private set; } + public bool Found { get; private set; } - public Package Package { get; private set; } + public Package Package { get; private set; } - public bool IsDotnetTemplate { get; private set; } - public bool IsDotnetTool { get; private set; } - public DateTime LastUpdated { get; private set; } - public long TotalDownloads { get; private set; } + public bool IsDotnetTemplate { get; private set; } + public bool IsDotnetTool { get; private set; } + public DateTime LastUpdated { get; private set; } + public long TotalDownloads { get; private set; } - public IReadOnlyList UsedBy { get; set; } - public IReadOnlyList DependencyGroups { get; private set; } - public IReadOnlyList Versions { get; private set; } + public IReadOnlyList UsedBy { get; set; } + public IReadOnlyList DependencyGroups { get; private set; } + public IReadOnlyList Versions { get; private set; } - public HtmlString Readme { get; private set; } + public HtmlString Readme { get; private set; } - public string IconUrl { get; private set; } - public string LicenseUrl { get; private set; } - public string PackageDownloadUrl { get; private set; } + public string IconUrl { get; private set; } + public string LicenseUrl { get; private set; } + public string PackageDownloadUrl { get; private set; } - public async Task OnGetAsync(string id, string version, CancellationToken cancellationToken) + public async Task OnGetAsync(string id, string version, CancellationToken cancellationToken) + { + var packages = await _packages.FindPackagesAsync(id, cancellationToken); + var listedPackages = packages.Where(p => p.Listed).ToList(); + + // Try to find the requested version. + if (NuGetVersion.TryParse(version, out var requestedVersion)) { - var packages = await _packages.FindPackagesAsync(id, cancellationToken); - var listedPackages = packages.Where(p => p.Listed).ToList(); + Package = packages.SingleOrDefault(p => p.Version == requestedVersion); + } - // Try to find the requested version. - if (NuGetVersion.TryParse(version, out var requestedVersion)) - { - Package = packages.SingleOrDefault(p => p.Version == requestedVersion); - } + // Otherwise try to display the latest version. + if (Package == null) + { + Package = listedPackages.OrderByDescending(p => p.Version).FirstOrDefault(); + } - // Otherwise try to display the latest version. - if (Package == null) - { - Package = listedPackages.OrderByDescending(p => p.Version).FirstOrDefault(); - } + if (Package == null) + { + Package = new Package { Id = id }; + Found = false; + return; + } - if (Package == null) - { - Package = new Package { Id = id }; - Found = false; - return; - } + var packageVersion = Package.Version; + + Found = true; + IsDotnetTemplate = Package.PackageTypes.Any(t => t.Name.Equals("Template", StringComparison.OrdinalIgnoreCase)); + IsDotnetTool = Package.PackageTypes.Any(t => t.Name.Equals("DotnetTool", StringComparison.OrdinalIgnoreCase)); + LastUpdated = packages.Max(p => p.Published); + TotalDownloads = packages.Sum(p => p.Downloads); - var packageVersion = Package.Version; + var dependents = await _search.FindDependentsAsync(Package.Id, cancellationToken); - Found = true; - IsDotnetTemplate = Package.PackageTypes.Any(t => t.Name.Equals("Template", StringComparison.OrdinalIgnoreCase)); - IsDotnetTool = Package.PackageTypes.Any(t => t.Name.Equals("DotnetTool", StringComparison.OrdinalIgnoreCase)); - LastUpdated = packages.Max(p => p.Published); - TotalDownloads = packages.Sum(p => p.Downloads); + UsedBy = dependents.Data; + DependencyGroups = PackageDependencies.GroupByFramework(Package.Dependencies); + Versions = ToVersions(listedPackages, packageVersion); - var dependents = await _search.FindDependentsAsync(Package.Id, cancellationToken); + if (Package.HasReadme) + { + Readme = await GetReadmeHtmlStringOrNullAsync(Package.Id, packageVersion, cancellationToken); + } - UsedBy = dependents.Data; - DependencyGroups = PackageDependencies.GroupByFramework(Package.Dependencies); - Versions = ToVersions(listedPackages, packageVersion); + IconUrl = Package.HasEmbeddedIcon + ? _url.GetPackageIconDownloadUrl(Package.Id, packageVersion) + : Package.IconUrlString; + LicenseUrl = Package.LicenseUrlString; + PackageDownloadUrl = _url.GetPackageDownloadUrl(Package.Id, packageVersion); + } - if (Package.HasReadme) + private IReadOnlyList ToVersions(IReadOnlyList packages, NuGetVersion selectedVersion) + { + return packages + .Select(p => new VersionModel { - Readme = await GetReadmeHtmlStringOrNullAsync(Package.Id, packageVersion, cancellationToken); - } - - IconUrl = Package.HasEmbeddedIcon - ? _url.GetPackageIconDownloadUrl(Package.Id, packageVersion) - : Package.IconUrlString; - LicenseUrl = Package.LicenseUrlString; - PackageDownloadUrl = _url.GetPackageDownloadUrl(Package.Id, packageVersion); - } + Version = p.Version, + Downloads = p.Downloads, + Selected = p.Version == selectedVersion, + LastUpdated = p.Published, + }) + .OrderByDescending(m => m.Version) + .ToList(); + } - private IReadOnlyList ToVersions(IReadOnlyList packages, NuGetVersion selectedVersion) + private async Task GetReadmeHtmlStringOrNullAsync( + string packageId, + NuGetVersion packageVersion, + CancellationToken cancellationToken) + { + string readme; + using (var readmeStream = await _content.GetPackageReadmeStreamOrNullAsync(packageId, packageVersion, cancellationToken)) { - return packages - .Select(p => new VersionModel - { - Version = p.Version, - Downloads = p.Downloads, - Selected = p.Version == selectedVersion, - LastUpdated = p.Published, - }) - .OrderByDescending(m => m.Version) - .ToList(); - } + if (readmeStream == null) return null; - private async Task GetReadmeHtmlStringOrNullAsync( - string packageId, - NuGetVersion packageVersion, - CancellationToken cancellationToken) - { - string readme; - using (var readmeStream = await _content.GetPackageReadmeStreamOrNullAsync(packageId, packageVersion, cancellationToken)) + using (var reader = new StreamReader(readmeStream)) { - if (readmeStream == null) return null; - - using (var reader = new StreamReader(readmeStream)) - { - readme = await reader.ReadToEndAsync(); - } + readme = await reader.ReadToEndAsync(); } - - return ReadmeMarkdown.ToHtml(readme); } - public record VersionModel - { - public NuGetVersion Version { get; init; } - public long Downloads { get; init; } - public bool Selected { get; init; } - public DateTime LastUpdated { get; init; } - } + return ReadmeMarkdown.ToHtml(readme); + } + + public record VersionModel + { + public NuGetVersion Version { get; init; } + public long Downloads { get; init; } + public bool Selected { get; init; } + public DateTime LastUpdated { get; init; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Pages/ReportAbuse.cshtml.cs b/src/BaGet.Web/Pages/ReportAbuse.cshtml.cs index c1c32c993..e95a55e95 100644 --- a/src/BaGet.Web/Pages/ReportAbuse.cshtml.cs +++ b/src/BaGet.Web/Pages/ReportAbuse.cshtml.cs @@ -9,87 +9,86 @@ using Microsoft.EntityFrameworkCore; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// Records a report against a package version, for its owners and the administrator. +/// The page works for any ID and version: a client expands the report abuse template +/// from whatever it is looking at. +/// +public class ReportAbuseModel : PageModel { - /// - /// Records a report against a package version, for its owners and the administrator. - /// The page works for any ID and version: a client expands the report abuse template - /// from whatever it is looking at. - /// - public class ReportAbuseModel : PageModel + private readonly IContext _context; + private readonly SystemTime _time; + + public ReportAbuseModel(IContext context, SystemTime time) { - private readonly IContext _context; - private readonly SystemTime _time; + _context = context ?? throw new ArgumentNullException(nameof(context)); + _time = time ?? throw new ArgumentNullException(nameof(time)); + } - public ReportAbuseModel(IContext context, SystemTime time) - { - _context = context ?? throw new ArgumentNullException(nameof(context)); - _time = time ?? throw new ArgumentNullException(nameof(time)); - } + [BindProperty(SupportsGet = true)] + public string Id { get; set; } - [BindProperty(SupportsGet = true)] - public string Id { get; set; } + [BindProperty(SupportsGet = true)] + public string Version { get; set; } - [BindProperty(SupportsGet = true)] - public string Version { get; set; } + [BindProperty] + [Required] + public string Reason { get; set; } - [BindProperty] - [Required] - public string Reason { get; set; } + [BindProperty] + [Required] + [StringLength(AbstractContext.DefaultMaxStringLength)] + public string Details { get; set; } - [BindProperty] - [Required] - [StringLength(AbstractContext.DefaultMaxStringLength)] - public string Details { get; set; } + [BindProperty] + [EmailAddress] + [StringLength(AbstractContext.MaxEmailLength)] + [Display(Name = "Your email (optional)")] + public string ReporterEmail { get; set; } - [BindProperty] - [EmailAddress] - [StringLength(AbstractContext.MaxEmailLength)] - [Display(Name = "Your email (optional)")] - public string ReporterEmail { get; set; } + public bool Submitted { get; private set; } - public bool Submitted { get; private set; } + /// + /// Reports are kept in the database, which Azure Table storage cannot do. + /// + public bool CanReport => !(_context is NullContext); - /// - /// Reports are kept in the database, which Azure Table storage cannot do. - /// - public bool CanReport => !(_context is NullContext); + public void OnGet() + { + } + + public async Task OnPostAsync(CancellationToken cancellationToken) + { + if (!CanReport) return NotFound(); - public void OnGet() + if (!AbuseReport.Reasons.Contains(Reason, StringComparer.Ordinal)) { + ModelState.AddModelError(nameof(Reason), "Choose one of the reasons listed."); } - public async Task OnPostAsync(CancellationToken cancellationToken) + if (Id == null || Id.Length > AbstractContext.MaxPackageIdLength + || !NuGetVersion.TryParse(Version, out var version)) { - if (!CanReport) return NotFound(); - - if (!AbuseReport.Reasons.Contains(Reason, StringComparer.Ordinal)) - { - ModelState.AddModelError(nameof(Reason), "Choose one of the reasons listed."); - } - - if (Id == null || Id.Length > AbstractContext.MaxPackageIdLength - || !NuGetVersion.TryParse(Version, out var version)) - { - return NotFound(); - } - - if (!ModelState.IsValid) return Page(); - - _context.AbuseReports.Add(new AbuseReport - { - PackageId = Id, - PackageVersion = version.ToNormalizedString(), - Reason = Reason, - Details = Details, - ReporterEmail = string.IsNullOrWhiteSpace(ReporterEmail) ? null : ReporterEmail.Trim(), - Created = _time.UtcNow, - }); - await _context.SaveChangesAsync(cancellationToken); - - Submitted = true; - - return Page(); + return NotFound(); } + + if (!ModelState.IsValid) return Page(); + + _context.AbuseReports.Add(new AbuseReport + { + PackageId = Id, + PackageVersion = version.ToNormalizedString(), + Reason = Reason, + Details = Details, + ReporterEmail = string.IsNullOrWhiteSpace(ReporterEmail) ? null : ReporterEmail.Trim(), + Created = _time.UtcNow, + }); + await _context.SaveChangesAsync(cancellationToken); + + Submitted = true; + + return Page(); } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Pages/Statistics.cshtml.cs b/src/BaGet.Web/Pages/Statistics.cshtml.cs index 59b144653..40d81d11d 100644 --- a/src/BaGet.Web/Pages/Statistics.cshtml.cs +++ b/src/BaGet.Web/Pages/Statistics.cshtml.cs @@ -4,25 +4,24 @@ using BaGet.Core; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace BaGet.Web +namespace BaGet.Web; + +public class StatisticsModel : PageModel { - public class StatisticsModel : PageModel - { - private readonly StatisticsService _statistics; + private readonly StatisticsService _statistics; - public StatisticsModel(StatisticsService statistics) - { - _statistics = statistics ?? throw new ArgumentNullException(nameof(statistics)); - } + public StatisticsModel(StatisticsService statistics) + { + _statistics = statistics ?? throw new ArgumentNullException(nameof(statistics)); + } - public FeedStatistics Statistics { get; private set; } + public FeedStatistics Statistics { get; private set; } - public async Task OnGetAsync(CancellationToken cancellationToken) + public async Task OnGetAsync(CancellationToken cancellationToken) + { + if (_statistics.IsSupported) { - if (_statistics.IsSupported) - { - Statistics = await _statistics.GetAsync(cancellationToken); - } + Statistics = await _statistics.GetAsync(cancellationToken); } } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Pages/Upload.cshtml.cs b/src/BaGet.Web/Pages/Upload.cshtml.cs index fe0dd1a4c..24af41844 100644 --- a/src/BaGet.Web/Pages/Upload.cshtml.cs +++ b/src/BaGet.Web/Pages/Upload.cshtml.cs @@ -16,543 +16,592 @@ using NuGet.Packaging; using NuGet.Versioning; -namespace BaGet.Web +namespace BaGet.Web; + +using NuGetPackageType = NuGet.Packaging.Core.PackageType; + +/// +/// Uploading through the browser, in two steps: the first stages the file and shows what +/// it contains, the second publishes it. Both steps go through the same authorization and +/// the same submission pipeline as "dotnet nuget push", so the browser can do what the +/// pusher's own API key could, and no more. +/// +/// +/// Deliberately not an AccountPageModel: that base answers 404 while accounts are +/// disabled, and this page must still work there - with a pasted API key, exactly as the +/// push endpoint requires one. +/// +public class UploadModel : PageModel { - using NuGetPackageType = NuGet.Packaging.Core.PackageType; + internal const string ReadOnlyMessage = + "This server is in read-only mode, so nothing can be uploaded."; + + internal const string SignInMessage = + "Sign in to upload a package."; + + internal const string ApiKeyRejectedMessage = + "That API key was not accepted."; + + internal const string NoApiKeyMessage = + "This server has no API key configured and no accounts, so there is nothing to " + + "tell one visitor from another and nothing to authenticate an upload with. " + + "Set \"ApiKey\", or enable \"Accounts:Enabled\", to upload through the browser."; + + internal const string UnknownTokenMessage = + "This upload is no longer staged. It was cancelled, already published, or staged " + + "by someone else - upload the file again."; + + internal const string UnreadableMessage = + "This file could not be read as a package. Upload the .nupkg or .snupkg a build " + + "produced, not a renamed or repacked copy."; + + internal const string TermsMessage = + "Confirm that you have the right to publish this package before submitting."; + + internal const string InvalidSymbolPackageMessage = + "This symbol package is not valid (its entries, a PDB that is not portable, or " + + "PDBs that do not match the package)."; + + internal const string NotASymbolPackageMessage = + "A .snupkg must declare the SymbolsPackage package type in its own nuspec. This " + + "file does not, so it is not a symbol package - and a symbols archive is not a " + + "package either. Repack it as a symbol package, or upload the .nupkg instead."; + + internal const string CouldNotStageMessage = + "The server could not store this upload. Try again."; + + private readonly IOptionsSnapshot _options; + private readonly IOptions _accounts; + private readonly IAuthenticationService _authentication; + private readonly IPackageAuthorizationService _authorization; + private readonly IPackageSubmissionService _submissions; + private readonly ISymbolIndexingService _symbols; + private readonly IPackageStagingService _staging; + private readonly IPackageDatabase _packages; + private readonly ILogger _logger; + + public UploadModel( + IOptionsSnapshot options, + IOptions accounts, + IAuthenticationService authentication, + IPackageAuthorizationService authorization, + IPackageSubmissionService submissions, + ISymbolIndexingService symbols, + IPackageStagingService staging, + IPackageDatabase packages, + ILogger logger) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); + _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); + _submissions = submissions ?? throw new ArgumentNullException(nameof(submissions)); + _symbols = symbols ?? throw new ArgumentNullException(nameof(symbols)); + _staging = staging ?? throw new ArgumentNullException(nameof(staging)); + _packages = packages ?? throw new ArgumentNullException(nameof(packages)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } /// - /// Uploading through the browser, in two steps: the first stages the file and shows what - /// it contains, the second publishes it. Both steps go through the same authorization and - /// the same submission pipeline as "dotnet nuget push", so the browser can do what the - /// pusher's own API key could, and no more. + /// The package ID a link arrived with, as "upload a new version of this" does. It is + /// a hint for the page only: the ID and version that are published are read from the + /// file, never from the request. /// - /// - /// Deliberately not an AccountPageModel: that base answers 404 while accounts are - /// disabled, and this page must still work there - with a pasted API key, exactly as the - /// push endpoint requires one. - /// - public class UploadModel : PageModel - { - internal const string ReadOnlyMessage = - "This server is in read-only mode, so nothing can be uploaded."; - - internal const string SignInMessage = - "Sign in to upload a package."; - - internal const string ApiKeyRejectedMessage = - "That API key was not accepted."; - - internal const string NoApiKeyMessage = - "This server has no API key configured and no accounts, so there is nothing to " - + "tell one visitor from another and nothing to authenticate an upload with. " - + "Set \"ApiKey\", or enable \"Accounts:Enabled\", to upload through the browser."; - - internal const string UnknownTokenMessage = - "This upload is no longer staged. It was cancelled, already published, or staged " - + "by someone else - upload the file again."; - - internal const string UnreadableMessage = - "This file could not be read as a package. Upload the .nupkg or .snupkg a build " - + "produced, not a renamed or repacked copy."; - - internal const string TermsMessage = - "Confirm that you have the right to publish this package before submitting."; - - internal const string InvalidSymbolPackageMessage = - "This symbol package is not valid (its entries, a PDB that is not portable, or " - + "PDBs that do not match the package)."; - - internal const string NotASymbolPackageMessage = - "A .snupkg must declare the SymbolsPackage package type in its own nuspec. This " - + "file does not, so it is not a symbol package - and a symbols archive is not a " - + "package either. Repack it as a symbol package, or upload the .nupkg instead."; - - internal const string CouldNotStageMessage = - "The server could not store this upload. Try again."; - - private readonly IOptionsSnapshot _options; - private readonly IOptions _accounts; - private readonly IAuthenticationService _authentication; - private readonly IPackageAuthorizationService _authorization; - private readonly IPackageSubmissionService _submissions; - private readonly ISymbolIndexingService _symbols; - private readonly IPackageStagingService _staging; - private readonly IPackageDatabase _packages; - private readonly ILogger _logger; - - public UploadModel( - IOptionsSnapshot options, - IOptions accounts, - IAuthenticationService authentication, - IPackageAuthorizationService authorization, - IPackageSubmissionService submissions, - ISymbolIndexingService symbols, - IPackageStagingService staging, - IPackageDatabase packages, - ILogger logger) - { - _options = options ?? throw new ArgumentNullException(nameof(options)); - _accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); - _authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); - _authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); - _submissions = submissions ?? throw new ArgumentNullException(nameof(submissions)); - _symbols = symbols ?? throw new ArgumentNullException(nameof(symbols)); - _staging = staging ?? throw new ArgumentNullException(nameof(staging)); - _packages = packages ?? throw new ArgumentNullException(nameof(packages)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + [BindProperty(SupportsGet = true)] + public string Id { get; set; } - /// - /// The package ID a link arrived with, as "upload a new version of this" does. It is - /// a hint for the page only: the ID and version that are published are read from the - /// file, never from the request. - /// - [BindProperty(SupportsGet = true)] - public string Id { get; set; } + public bool AccountsEnabled => _accounts.Value.Enabled; - public bool AccountsEnabled => _accounts.Value.Enabled; + public bool IsReadOnlyMode => _options.Value.IsReadOnlyMode; - public bool IsReadOnlyMode => _options.Value.IsReadOnlyMode; + public bool SignedIn => User.Identity?.IsAuthenticated == true; - public bool SignedIn => User.Identity?.IsAuthenticated == true; + /// + /// With accounts off there is no user to own an upload, so the pusher proves itself + /// with an API key - the same key the PUT endpoint requires. + /// + public bool NeedsApiKey => !AccountsEnabled; - /// - /// With accounts off there is no user to own an upload, so the pusher proves itself - /// with an API key - the same key the PUT endpoint requires. - /// - public bool NeedsApiKey => !AccountsEnabled; + /// + /// Nothing on this server can tell one caller from another: accounts are off and no + /// global API key is configured, which is how BaGet ships. The browser upload is + /// closed there rather than offered as a publish button to whoever finds the page, + /// and the API key box - which would accept anything, including nothing - is not + /// rendered to claim otherwise. dotnet nuget push is unaffected: this page is + /// a convenience, not the authorization model. + /// + public bool NothingCanAuthenticate => !AccountsEnabled && string.IsNullOrEmpty(_options.Value.ApiKey); - /// - /// Nothing on this server can tell one caller from another: accounts are off and no - /// global API key is configured, which is how BaGet ships. The browser upload is - /// closed there rather than offered as a publish button to whoever finds the page, - /// and the API key box - which would accept anything, including nothing - is not - /// rendered to claim otherwise. dotnet nuget push is unaffected: this page is - /// a convenience, not the authorization model. - /// - public bool NothingCanAuthenticate => !AccountsEnabled && string.IsNullOrEmpty(_options.Value.ApiKey); + /// + /// What the page says in that state, so the explanation and the refusal are one + /// sentence rather than two that could drift apart. + /// + public string NoApiKeyExplanation => NoApiKeyMessage; - /// - /// What the page says in that state, so the explanation and the refusal are one - /// sentence rather than two that could drift apart. - /// - public string NoApiKeyExplanation => NoApiKeyMessage; + /// + /// Whether to render the form at all. Read-only mode, a server nothing can + /// authenticate against, and an anonymous visitor each get an explanation instead of + /// a file picker that could only fail. + /// + public bool CanUpload => !IsReadOnlyMode && !NothingCanAuthenticate && (!AccountsEnabled || SignedIn); - /// - /// Whether to render the form at all. Read-only mode, a server nothing can - /// authenticate against, and an anonymous visitor each get an explanation instead of - /// a file picker that could only fail. - /// - public bool CanUpload => !IsReadOnlyMode && !NothingCanAuthenticate && (!AccountsEnabled || SignedIn); + /// + /// The staged upload awaiting confirmation, or null while on step one. + /// + public StagedUpload Staged { get; private set; } - /// - /// The staged upload awaiting confirmation, or null while on step one. - /// - public StagedUpload Staged { get; private set; } + public string Message { get; private set; } - public string Message { get; private set; } + public bool Failed { get; private set; } - public bool Failed { get; private set; } + /// + /// Set once something is published, so the page can link to it. + /// + public StagedUpload Published { get; private set; } - /// - /// Set once something is published, so the page can link to it. - /// - public StagedUpload Published { get; private set; } + public void OnGet() + { + } + + public async Task OnPostStageAsync( + IFormFile package, + string apiKey, + CancellationToken cancellationToken) + { + if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); + + var principal = await AuthenticateAsync(apiKey, cancellationToken); + if (principal == null) return Refuse(401, NotAuthenticatedMessage); - public void OnGet() + if (package == null || package.Length == 0) { + return Refuse(400, "Choose a .nupkg or .snupkg file to upload."); } - public async Task OnPostStageAsync( - IFormFile package, - string apiKey, - CancellationToken cancellationToken) + var fileName = Path.GetFileName(package.FileName) ?? string.Empty; + var extension = Path.GetExtension(fileName); + if (!extension.Equals(".nupkg", StringComparison.OrdinalIgnoreCase) && + !extension.Equals(".snupkg", StringComparison.OrdinalIgnoreCase)) { - if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); - if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); + return Refuse(400, "A package is a .nupkg file, and symbols are a .snupkg file."); + } - var principal = await AuthenticateAsync(apiKey, cancellationToken); - if (principal == null) return Refuse(401, NotAuthenticatedMessage); + // The spooled upload is seekable, which is what reading the archive needs; one + // that is not is copied once rather than reported as unreadable. + using var upload = package.OpenReadStream(); + using var copy = upload.CanSeek ? null : await upload.AsTemporaryFileStreamAsync(cancellationToken); + var content = copy ?? upload; + + var staged = await ReadOrNullAsync(content, cancellationToken); + if (staged == null) return Refuse(400, UnreadableMessage); + + // The content decides the pipeline, never the file's name. A .snupkg whose + // nuspec does not declare the symbols package type is therefore not a symbol + // package - and publishing it as a package would store a symbols archive as the + // .nupkg of that ID and version, while the symbol endpoint reads the identical + // bytes as symbols. Refused rather than published as something it is not. + if (extension.Equals(".snupkg", StringComparison.OrdinalIgnoreCase) && !staged.IsSymbolPackage) + { + return Refuse(400, NotASymbolPackageMessage); + } - if (package == null || package.Length == 0) - { - return Refuse(400, "Choose a .nupkg or .snupkg file to upload."); - } + // Authorized before the upload is stored: there is no point keeping a file its + // uploader may not publish. + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, staged.Id, cancellationToken)) + { + return Refuse(403, Denied(staged.Id)); + } - var fileName = Path.GetFileName(package.FileName) ?? string.Empty; - var extension = Path.GetExtension(fileName); - if (!extension.Equals(".nupkg", StringComparison.OrdinalIgnoreCase) && - !extension.Equals(".snupkg", StringComparison.OrdinalIgnoreCase)) - { - return Refuse(400, "A package is a .nupkg file, and symbols are a .snupkg file."); - } + await DescribeSymbolTargetAsync(staged, cancellationToken); - // The spooled upload is seekable, which is what reading the archive needs; one - // that is not is copied once rather than reported as unreadable. - using var upload = package.OpenReadStream(); - using var copy = upload.CanSeek ? null : await upload.AsTemporaryFileStreamAsync(cancellationToken); - var content = copy ?? upload; - - var staged = await ReadOrNullAsync(content, cancellationToken); - if (staged == null) return Refuse(400, UnreadableMessage); - - // The content decides the pipeline, never the file's name. A .snupkg whose - // nuspec does not declare the symbols package type is therefore not a symbol - // package - and publishing it as a package would store a symbols archive as the - // .nupkg of that ID and version, while the symbol endpoint reads the identical - // bytes as symbols. Refused rather than published as something it is not. - if (extension.Equals(".snupkg", StringComparison.OrdinalIgnoreCase) && !staged.IsSymbolPackage) - { - return Refuse(400, NotASymbolPackageMessage); - } + content.Position = 0; - // Authorized before the upload is stored: there is no point keeping a file its - // uploader may not publish. - if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, staged.Id, cancellationToken)) - { - return Refuse(403, Denied(staged.Id)); - } - - await DescribeSymbolTargetAsync(staged, cancellationToken); + try + { + staged.Token = await _staging.StageAsync(content, principal.UserId, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + // A failure the server owns, reported the way the equivalent failure on the + // confirm step is: a sentence with a status code, never a bare 500 or a + // stack trace. + _logger.LogError(e, "Could not stage an upload of {PackageId} {PackageVersion}", staged.Id, staged.Version); - content.Position = 0; + return Refuse(500, CouldNotStageMessage); + } - try - { - staged.Token = await _staging.StageAsync(content, principal.UserId, cancellationToken); - } - catch (Exception e) when (!(e is OperationCanceledException)) - { - // A failure the server owns, reported the way the equivalent failure on the - // confirm step is: a sentence with a status code, never a bare 500 or a - // stack trace. - _logger.LogError(e, "Could not stage an upload of {PackageId} {PackageVersion}", staged.Id, staged.Version); + Staged = staged; - return Refuse(500, CouldNotStageMessage); - } + return Page(); + } - Staged = staged; + public async Task OnPostSubmitAsync( + string token, + string apiKey, + bool acceptTerms, + CancellationToken cancellationToken) + { + if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); - return Page(); - } + var principal = await AuthenticateAsync(apiKey, cancellationToken); + if (principal == null) return RefuseKey(token); - public async Task OnPostSubmitAsync( - string token, - string apiKey, - bool acceptTerms, - CancellationToken cancellationToken) + // Whoever staged the upload is the only one who can open it, so another user's + // token is indistinguishable from one that never existed. + Stream content; + using (var stagedStream = await _staging.OpenAsync(token, principal.UserId, cancellationToken)) { - if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); - if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); - - var principal = await AuthenticateAsync(apiKey, cancellationToken); - if (principal == null) return Refuse(401, NotAuthenticatedMessage); - - // Whoever staged the upload is the only one who can open it, so another user's - // token is indistinguishable from one that never existed. - using var stagedStream = await _staging.OpenAsync(token, principal.UserId, cancellationToken); if (stagedStream == null) return Refuse(404, UnknownTokenMessage); - using var content = await stagedStream.AsTemporaryFileStreamAsync(cancellationToken); - - var staged = await ReadOrNullAsync(content, cancellationToken); - if (staged == null) - { - await _staging.RemoveAsync(token, principal.UserId, cancellationToken); - return Refuse(400, UnreadableMessage); - } - - staged.Token = token; - await DescribeSymbolTargetAsync(staged, cancellationToken); + // Copied and closed before anything is removed: an open handle on the staged + // blob stops it being deleted on file systems that refuse to delete open files. + content = await stagedStream.AsTemporaryFileStreamAsync(cancellationToken); + } - // The checkbox is enforced here too, not only in the browser: the upload stays - // staged so the box can be ticked and the preview submitted again. - if (!acceptTerms) - { - Staged = staged; - return Refuse(400, TermsMessage); - } + using var ownedContent = content; - // Re-checked at submission: ownership may have changed while the preview was on - // screen, and the first check guarded the store, not the publish. - if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, staged.Id, cancellationToken)) - { - await _staging.RemoveAsync(token, principal.UserId, cancellationToken); - return Refuse(403, Denied(staged.Id)); - } + var staged = await ReadOrNullAsync(content, cancellationToken); + if (staged == null) + { + await _staging.RemoveAsync(token, principal.UserId, cancellationToken); + return Refuse(400, UnreadableMessage); + } - content.Position = 0; + staged.Token = token; + await DescribeSymbolTargetAsync(staged, cancellationToken); - return staged.IsSymbolPackage - ? await PublishSymbolsAsync(staged, content, principal, cancellationToken) - : await PublishPackageAsync(staged, content, principal, cancellationToken); + // The checkbox is enforced here too, not only in the browser: the upload stays + // staged so the box can be ticked and the preview submitted again. + if (!acceptTerms) + { + Staged = staged; + return Refuse(400, TermsMessage); } - /// - /// Discard a staged upload. Authenticated, owner-checked and refused in read-only - /// mode, exactly as the other two handlers are: the token is the only handle on an - /// upload, so anyone who learned one - from a log, a screenshot, a shared screen - - /// could otherwise make its owner upload the whole file again, and the deletion is a - /// write to the store that read-only mode is meant to freeze. - /// - public async Task OnPostCancelAsync( - string token, - string apiKey, - CancellationToken cancellationToken) + // Re-checked at submission: ownership may have changed while the preview was on + // screen, and the first check guarded the store, not the publish. + if (!await _authorization.AuthorizeAsync(principal, PackageAction.Push, staged.Id, cancellationToken)) { - if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); - if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); + await _staging.RemoveAsync(token, principal.UserId, cancellationToken); + return Refuse(403, Denied(staged.Id)); + } - var principal = await AuthenticateAsync(apiKey, cancellationToken); - if (principal == null) return Refuse(401, NotAuthenticatedMessage); + content.Position = 0; - // Another user's token is indistinguishable from one that never existed, as it - // is when submitting. - if (!await _staging.RemoveAsync(token, principal.UserId, cancellationToken)) - { - return Refuse(404, UnknownTokenMessage); - } + return staged.IsSymbolPackage + ? await PublishSymbolsAsync(staged, content, principal, cancellationToken) + : await PublishPackageAsync(staged, content, principal, cancellationToken); + } + + /// + /// Discard a staged upload. Authenticated, owner-checked and refused in read-only + /// mode, exactly as the other two handlers are: the token is the only handle on an + /// upload, so anyone who learned one - from a log, a screenshot, a shared screen - + /// could otherwise make its owner upload the whole file again, and the deletion is a + /// write to the store that read-only mode is meant to freeze. + /// + public async Task OnPostCancelAsync( + string token, + string apiKey, + CancellationToken cancellationToken) + { + if (IsReadOnlyMode) return Refuse(401, ReadOnlyMessage); + if (NothingCanAuthenticate) return Refuse(401, NoApiKeyMessage); - Message = "The upload was discarded."; + var principal = await AuthenticateAsync(apiKey, cancellationToken); + if (principal == null) return RefuseKey(token); - return Page(); + // Another user's token is indistinguishable from one that never existed, as it + // is when submitting. + if (!await _staging.RemoveAsync(token, principal.UserId, cancellationToken)) + { + return Refuse(404, UnknownTokenMessage); } - private async Task PublishPackageAsync( - StagedUpload staged, - Stream content, - BaGetPrincipal principal, - CancellationToken cancellationToken) + Message = "The upload was discarded."; + + return Page(); + } + + private async Task PublishPackageAsync( + StagedUpload staged, + Stream content, + BaGetPrincipal principal, + CancellationToken cancellationToken) + { + PackageIndexingResult result; + try { - PackageIndexingResult result; - try - { - result = await _submissions.SubmitAsync(content, cancellationToken); - } - catch (Exception e) when (!(e is OperationCanceledException)) - { - // A failure the server owns: said in a sentence rather than as a stack trace, - // and the upload is kept so it can be submitted again. - _logger.LogError(e, "Could not publish the staged upload {Token}", staged.Token); + result = await _submissions.SubmitAsync(content, cancellationToken); + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + // A failure the server owns: said in a sentence rather than as a stack trace, + // and the upload is kept so it can be submitted again. + _logger.LogError(e, "Could not publish the staged upload {Token}", staged.Token); - Staged = staged; - return Refuse(500, "The server could not publish this package. Try again."); - } + Staged = staged; + return Refuse(500, "The server could not publish this package. Try again."); + } - // An accepted package claims its ID now, as it does on the push endpoint: it is - // the pusher's even while it is being validated. + // An accepted package claims its ID now, as it does on the push endpoint: it is + // the pusher's even while it is being validated. + // The package is already published when this runs, so a failure here must not + // turn the page into a bare 500, and must not keep the staged upload alive. + var ownershipRecorded = true; + try + { if (result == PackageIndexingResult.Success || result == PackageIndexingResult.Accepted) { await _authorization.OnPushedAsync(principal, staged.Id, cancellationToken); } - + } + catch (Exception e) when (!(e is OperationCanceledException)) + { + _logger.LogError(e, "Could not record the ownership of {PackageId}", staged.Id); + ownershipRecorded = false; + } + finally + { await _staging.RemoveAsync(staged.Token, principal.UserId, cancellationToken); - - switch (result) - { - case PackageIndexingResult.Success: - case PackageIndexingResult.Accepted: - Published = staged; - Message = result == PackageIndexingResult.Accepted - ? $"{staged.Id} {staged.Version} was accepted and is being validated." - : $"{staged.Id} {staged.Version} was published."; - return Page(); - - case PackageIndexingResult.PackageAlreadyExists: - // This upload can never be published, so keeping it staged would leave a - // file nobody could use. - return Refuse(409, - $"{staged.Id} {staged.Version} is already on this server, and this server does " - + "not replace a published version. Publish a new version instead."); - - default: - return Refuse(400, UnreadableMessage); - } } - private async Task PublishSymbolsAsync( - StagedUpload staged, - Stream content, - BaGetPrincipal principal, - CancellationToken cancellationToken) + switch (result) { - // Branched on the indexing result, not on a status code: a malformed symbol - // package and one whose package is missing are told apart here, while the push - // endpoint reports the first as 400 and every exception as 400 as well. - var result = await _symbols.IndexAsync(content, cancellationToken); + case PackageIndexingResult.Success: + case PackageIndexingResult.Accepted: + // Only a package that is indexed can be linked to: an accepted one is + // still being validated, so its page does not exist yet and may never. + if (result == PackageIndexingResult.Success) Published = staged; - await _staging.RemoveAsync(staged.Token, principal.UserId, cancellationToken); + Message = result == PackageIndexingResult.Accepted + ? $"{staged.Id} {staged.Version} was accepted and is being validated." + : $"{staged.Id} {staged.Version} was published."; - switch (result) - { - case SymbolIndexingResult.Success: - // No OnPushedAsync: symbols never claim an ID, exactly as on the symbol - // endpoint, so a symbol upload confers no ownership. - Published = staged; - Message = $"The symbols for {staged.Id} {staged.Version} were published."; - return Page(); - - case SymbolIndexingResult.PackageNotFound: - return Refuse(404, MissingSymbolTarget(staged)); - - default: - return Refuse(400, InvalidSymbolPackageMessage); - } - } + if (!ownershipRecorded) + { + Message += $" Recording you as the owner of {staged.Id} failed; ask an administrator to add you."; + } - /// - /// Who is uploading. With accounts on it is the signed-in session; with accounts off - /// there is no session to trust, so a pasted API key authenticates instead. - /// - private async Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken) - { - if (!AccountsEnabled) - { - return await _authentication.AuthenticatePrincipalAsync(apiKey, cancellationToken); - } + return Page(); + + case PackageIndexingResult.PackageAlreadyExists: + // This upload can never be published, so keeping it staged would leave a + // file nobody could use. + return Refuse(409, + $"{staged.Id} {staged.Version} is already on this server, and this server does " + + "not replace a published version. Publish a new version instead."); - // Resolved per request: the factory is only registered while accounts are on. - return HttpContext.RequestServices.GetService()?.Create(User); + default: + return Refuse(400, UnreadableMessage); } + } - private string NotAuthenticatedMessage => AccountsEnabled ? SignInMessage : ApiKeyRejectedMessage; + private async Task PublishSymbolsAsync( + StagedUpload staged, + Stream content, + BaGetPrincipal principal, + CancellationToken cancellationToken) + { + // Branched on the indexing result, not on a status code: a malformed symbol + // package and one whose package is missing are told apart here, while the push + // endpoint reports the first as 400 and every exception as 400 as well. + var result = await _symbols.IndexAsync(content, cancellationToken); - private static string Denied(string packageId) - => $"You may not publish '{packageId}'. Either someone else owns it, or it predates " - + "this server's accounts and only an administrator may publish to it."; + await _staging.RemoveAsync(staged.Token, principal.UserId, cancellationToken); - private static string MissingSymbolTarget(StagedUpload staged) - => "Symbols can only be uploaded for a package version already on this server. " - + $"Push {staged.Id} {staged.Version} first."; + switch (result) + { + case SymbolIndexingResult.Success: + // No OnPushedAsync: symbols never claim an ID, exactly as on the symbol + // endpoint, so a symbol upload confers no ownership. + Published = staged; + Message = $"The symbols for {staged.Id} {staged.Version} were published."; + return Page(); + + case SymbolIndexingResult.PackageNotFound: + return Refuse(404, MissingSymbolTarget(staged)); + + default: + return Refuse(400, InvalidSymbolPackageMessage); + } + } - /// - /// Everything the preview shows, read from the archive itself. Null when the file is - /// not a package at all. - /// - private async Task ReadOrNullAsync(Stream content, CancellationToken cancellationToken) + /// + /// Who is uploading. With accounts on it is the signed-in session; with accounts off + /// there is no session to trust, so a pasted API key authenticates instead. + /// + private async Task AuthenticateAsync(string apiKey, CancellationToken cancellationToken) + { + if (!AccountsEnabled) { - try - { - content.Position = 0; + return await _authentication.AuthenticatePrincipalAsync(apiKey, cancellationToken); + } - using var reader = new PackageArchiveReader(content, leaveStreamOpen: true); - var nuspec = reader.NuspecReader; + // Resolved per request: the factory is only registered while accounts are on. + return HttpContext.RequestServices.GetService()?.Create(User); + } - // The content decides which pipeline runs, not the file's name: a symbol - // package says so in its own nuspec, so renaming a file cannot send it to a - // pipeline its content does not belong to. - var isSymbolPackage = nuspec - .GetPackageTypes() - .Any(t => string.Equals(t.Name, NuGetPackageType.SymbolsPackage.Name, StringComparison.OrdinalIgnoreCase)); + private string NotAuthenticatedMessage => AccountsEnabled ? SignInMessage : ApiKeyRejectedMessage; - var staged = new StagedUpload - { - IsSymbolPackage = isSymbolPackage, - Id = nuspec.GetId(), - Version = nuspec.GetVersion().ToNormalizedString(), - }; + private static string Denied(string packageId) + => $"You may not publish '{packageId}'. Either someone else owns it, or it predates " + + "this server's accounts and only an administrator may publish to it."; - if (isSymbolPackage) - { - staged.SymbolFiles = reader - .GetFiles() - .Where(f => Path.GetExtension(f).Equals(".pdb", StringComparison.OrdinalIgnoreCase)) - .OrderBy(f => f, StringComparer.OrdinalIgnoreCase) - .ToList(); + private static string MissingSymbolTarget(StagedUpload staged) + => "Symbols can only be uploaded for a package version already on this server. " + + $"Push {staged.Id} {staged.Version} first."; - return staged; - } + /// + /// Everything the preview shows, read from the archive itself. Null when the file is + /// not a package at all. + /// + private async Task ReadOrNullAsync(Stream content, CancellationToken cancellationToken) + { + try + { + content.Position = 0; - var metadata = reader.GetPackageMetadata(); + using var reader = new PackageArchiveReader(content, leaveStreamOpen: true); + var nuspec = reader.NuspecReader; - staged.Description = metadata.Description; - staged.Authors = metadata.Authors ?? Array.Empty(); - staged.LicenseUrl = metadata.LicenseUrlString; - staged.License = nuspec.GetLicenseMetadata()?.License; - staged.DependencyGroups = PackageDependencies.GroupByFramework(metadata.Dependencies); + // The content decides which pipeline runs, not the file's name: a symbol + // package says so in its own nuspec, so renaming a file cannot send it to a + // pipeline its content does not belong to. + var isSymbolPackage = nuspec + .GetPackageTypes() + .Any(t => string.Equals(t.Name, NuGetPackageType.SymbolsPackage.Name, StringComparison.OrdinalIgnoreCase)); - if (reader.HasReadme()) - { - using var readme = await reader.GetReadmeAsync(cancellationToken); - using var text = new StreamReader(readme); + var staged = new StagedUpload + { + IsSymbolPackage = isSymbolPackage, + Id = nuspec.GetId(), + Version = nuspec.GetVersion().ToNormalizedString(), + }; - staged.Readme = ReadmeMarkdown.ToHtml(await text.ReadToEndAsync(cancellationToken)); - } + if (isSymbolPackage) + { + staged.SymbolFiles = reader + .GetFiles() + .Where(f => Path.GetExtension(f).Equals(".pdb", StringComparison.OrdinalIgnoreCase)) + .OrderBy(f => f, StringComparer.OrdinalIgnoreCase) + .ToList(); return staged; } - catch (Exception e) when (!(e is OperationCanceledException)) - { - _logger.LogInformation(e, "An upload could not be read as a package"); - return null; - } - finally + + var metadata = reader.GetPackageMetadata(); + + staged.Description = metadata.Description; + staged.Authors = metadata.Authors ?? Array.Empty(); + staged.LicenseUrl = metadata.LicenseUrlString; + staged.License = nuspec.GetLicenseMetadata()?.License; + staged.DependencyGroups = PackageDependencies.GroupByFramework(metadata.Dependencies); + + if (reader.HasReadme()) { - if (content.CanSeek) content.Position = 0; + using var readme = await reader.GetReadmeAsync(cancellationToken); + using var text = new StreamReader(readme); + + staged.Readme = ReadmeMarkdown.ToHtml(await text.ReadToEndAsync(cancellationToken)); } - } - /// - /// Symbols carry no metadata of their own, so the preview reports the version they - /// belong to - and says now, rather than after the upload is confirmed, when there is - /// no such version to attach them to. - /// - private async Task DescribeSymbolTargetAsync(StagedUpload staged, CancellationToken cancellationToken) + return staged; + } + catch (Exception e) when (!(e is OperationCanceledException)) { - if (!staged.IsSymbolPackage) return; - if (!NuGetVersion.TryParse(staged.Version, out var version)) return; + _logger.LogInformation(e, "An upload could not be read as a package"); + return null; + } + finally + { + if (content.CanSeek) content.Position = 0; + } + } + + /// + /// Symbols carry no metadata of their own, so the preview reports the version they + /// belong to - and says now, rather than after the upload is confirmed, when there is + /// no such version to attach them to. + /// + private async Task DescribeSymbolTargetAsync(StagedUpload staged, CancellationToken cancellationToken) + { + if (!staged.IsSymbolPackage) return; + if (!NuGetVersion.TryParse(staged.Version, out var version)) return; - var target = await _packages.FindOrNullAsync(staged.Id, version, includeUnlisted: true, cancellationToken); + var target = await _packages.FindOrNullAsync(staged.Id, version, includeUnlisted: true, cancellationToken); - staged.TargetPackageExists = target != null; - staged.TargetPackageMessage = target == null ? MissingSymbolTarget(staged) : null; - } + staged.TargetPackageExists = target != null; + staged.TargetPackageMessage = target == null ? MissingSymbolTarget(staged) : null; + } - private PageResult Refuse(int statusCode, string message) + /// + /// A rejected API key on the confirm or discard step. The staged upload is untouched, + /// so the page keeps its token and offers the key again instead of dropping back to + /// step one and forcing the whole file to be uploaded again. + /// + private PageResult RefuseKey(string token) + { + if (!AccountsEnabled && !string.IsNullOrEmpty(token) && token.Length == 32 && token.All(Uri.IsHexDigit)) { - Failed = true; - Message = message; + RetryToken = token; + } - var page = Page(); - page.StatusCode = statusCode; + return Refuse(401, NotAuthenticatedMessage); + } - return page; - } + /// + /// The token of a staged upload whose API key was rejected, so the key can be entered + /// again. Nothing about the upload is shown: it was not authenticated. + /// + public string RetryToken { get; private set; } - /// - /// What a staged upload contains, as the preview shows it. - /// - public class StagedUpload - { - public string Token { get; set; } + private PageResult Refuse(int statusCode, string message) + { + Failed = true; + Message = message; + + var page = Page(); + page.StatusCode = statusCode; + + return page; + } + + /// + /// What a staged upload contains, as the preview shows it. + /// + public class StagedUpload + { + public string Token { get; set; } - public bool IsSymbolPackage { get; set; } + public bool IsSymbolPackage { get; set; } - public string Id { get; set; } + public string Id { get; set; } - public string Version { get; set; } + public string Version { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public IReadOnlyList Authors { get; set; } = Array.Empty(); + public IReadOnlyList Authors { get; set; } = Array.Empty(); - /// - /// The license expression or license file the package declares, if any. - /// - public string License { get; set; } + /// + /// The license expression or license file the package declares, if any. + /// + public string License { get; set; } - public string LicenseUrl { get; set; } + public string LicenseUrl { get; set; } - public IReadOnlyList DependencyGroups { get; set; } - = Array.Empty(); + public IReadOnlyList DependencyGroups { get; set; } + = Array.Empty(); - public HtmlString Readme { get; set; } + public HtmlString Readme { get; set; } - public IReadOnlyList SymbolFiles { get; set; } = Array.Empty(); + public IReadOnlyList SymbolFiles { get; set; } = Array.Empty(); - public bool TargetPackageExists { get; set; } + public bool TargetPackageExists { get; set; } - public string TargetPackageMessage { get; set; } - } + public string TargetPackageMessage { get; set; } } -} +} \ No newline at end of file diff --git a/src/BaGet.Web/Pages/_ViewImports.cshtml b/src/BaGet.Web/Pages/_ViewImports.cshtml index 311ed1e12..7ce999104 100644 --- a/src/BaGet.Web/Pages/_ViewImports.cshtml +++ b/src/BaGet.Web/Pages/_ViewImports.cshtml @@ -2,6 +2,6 @@ @using BaGet.Core @using Humanizer @using Microsoft.AspNetCore.Html -@namespace BaGet.Web +@namespace BaGet.Web; @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, BaGet.Web diff --git a/src/BaGet.Web/ReadmeMarkdown.cs b/src/BaGet.Web/ReadmeMarkdown.cs index 7b583977c..49ece559f 100644 --- a/src/BaGet.Web/ReadmeMarkdown.cs +++ b/src/BaGet.Web/ReadmeMarkdown.cs @@ -1,19 +1,18 @@ using Markdig; using Microsoft.AspNetCore.Html; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// Renders a package's readme. The package page and the upload preview use one pipeline +/// so that what an uploader is shown is what readers will be shown. +/// +public static class ReadmeMarkdown { - /// - /// Renders a package's readme. The package page and the upload preview use one pipeline - /// so that what an uploader is shown is what readers will be shown. - /// - public static class ReadmeMarkdown - { - private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder() - .UseAdvancedExtensions() - .Build(); + private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder() + .UseAdvancedExtensions() + .Build(); - public static HtmlString ToHtml(string markdown) - => markdown == null ? null : new HtmlString(Markdown.ToHtml(markdown, Pipeline)); - } -} + public static HtmlString ToHtml(string markdown) + => markdown == null ? null : new HtmlString(Markdown.ToHtml(markdown, Pipeline)); +} \ No newline at end of file diff --git a/src/BaGet.Web/Routes.cs b/src/BaGet.Web/Routes.cs index 5742fac6a..c8c10a582 100644 --- a/src/BaGet.Web/Routes.cs +++ b/src/BaGet.Web/Routes.cs @@ -1,42 +1,41 @@ -namespace BaGet.Web +namespace BaGet.Web; + +public class Routes { - public class Routes - { - public const string IndexRouteName = "index"; - public const string UploadPackageRouteName = "upload-package"; - public const string UploadSymbolRouteName = "upload-symbol"; - public const string DeleteRouteName = "delete"; - public const string RelistRouteName = "relist"; - public const string SearchRouteName = "search"; - public const string AutocompleteRouteName = "autocomplete"; - public const string DependentsRouteName = "dependents"; - public const string RegistrationIndexRouteName = "registration-index"; - public const string RegistrationLeafRouteName = "registration-leaf"; - public const string PackageVersionsRouteName = "package-versions"; - public const string PackageDownloadRouteName = "package-download"; - public const string PackageDownloadManifestRouteName = "package-download-manifest"; - public const string PackageDownloadReadmeRouteName = "package-download-readme"; - public const string PackageDownloadIconRouteName = "package-download-icon"; - public const string SymbolDownloadRouteName = "symbol-download"; - public const string PrefixedSymbolDownloadRouteName = "prefixed-symbol-download"; + public const string IndexRouteName = "index"; + public const string UploadPackageRouteName = "upload-package"; + public const string UploadSymbolRouteName = "upload-symbol"; + public const string DeleteRouteName = "delete"; + public const string RelistRouteName = "relist"; + public const string SearchRouteName = "search"; + public const string AutocompleteRouteName = "autocomplete"; + public const string DependentsRouteName = "dependents"; + public const string RegistrationIndexRouteName = "registration-index"; + public const string RegistrationLeafRouteName = "registration-leaf"; + public const string PackageVersionsRouteName = "package-versions"; + public const string PackageDownloadRouteName = "package-download"; + public const string PackageDownloadManifestRouteName = "package-download-manifest"; + public const string PackageDownloadReadmeRouteName = "package-download-readme"; + public const string PackageDownloadIconRouteName = "package-download-icon"; + public const string SymbolDownloadRouteName = "symbol-download"; + public const string PrefixedSymbolDownloadRouteName = "prefixed-symbol-download"; - public const string V2RootRouteName = "v2-root"; - public const string V2MetadataRouteName = "v2-metadata"; - public const string V2FindPackagesByIdRouteName = "v2-find-packages-by-id"; - public const string V2PackagesRouteName = "v2-packages"; - public const string V2PackagesByKeyRouteName = "v2-packages-by-key"; - public const string V2SearchRouteName = "v2-search"; + public const string V2RootRouteName = "v2-root"; + public const string V2MetadataRouteName = "v2-metadata"; + public const string V2FindPackagesByIdRouteName = "v2-find-packages-by-id"; + public const string V2PackagesRouteName = "v2-packages"; + public const string V2PackagesByKeyRouteName = "v2-packages-by-key"; + public const string V2SearchRouteName = "v2-search"; - public const string SetDeprecationRouteName = "set-deprecation"; - public const string RemoveDeprecationRouteName = "remove-deprecation"; - public const string SetVulnerabilitiesRouteName = "set-vulnerabilities"; - public const string VulnerabilityIndexRouteName = "vulnerability-index"; - public const string VulnerabilityPageRouteName = "vulnerability-page"; - public const string CatalogIndexRouteName = "catalog-index"; - public const string CatalogPageRouteName = "catalog-page"; - public const string CatalogLeafRouteName = "catalog-leaf"; - public const string RepositorySignaturesRouteName = "repository-signatures"; - public const string RepositorySigningCertificateRouteName = "repository-signing-certificate"; - public const string ValidationStatusRouteName = "validation-status"; - } -} + public const string SetDeprecationRouteName = "set-deprecation"; + public const string RemoveDeprecationRouteName = "remove-deprecation"; + public const string SetVulnerabilitiesRouteName = "set-vulnerabilities"; + public const string VulnerabilityIndexRouteName = "vulnerability-index"; + public const string VulnerabilityPageRouteName = "vulnerability-page"; + public const string CatalogIndexRouteName = "catalog-index"; + public const string CatalogPageRouteName = "catalog-page"; + public const string CatalogLeafRouteName = "catalog-leaf"; + public const string RepositorySignaturesRouteName = "repository-signatures"; + public const string RepositorySigningCertificateRouteName = "repository-signing-certificate"; + public const string ValidationStatusRouteName = "validation-status"; +} \ No newline at end of file diff --git a/src/BaGet.Web/StagingSweepWorker.cs b/src/BaGet.Web/StagingSweepWorker.cs index 95d0b9a04..27a532c04 100644 --- a/src/BaGet.Web/StagingSweepWorker.cs +++ b/src/BaGet.Web/StagingSweepWorker.cs @@ -6,68 +6,67 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -namespace BaGet.Web +namespace BaGet.Web; + +/// +/// Removes uploads that were staged and then neither confirmed nor cancelled - a closed +/// browser tab, a lost session. Confirming and cancelling remove their own upload, so +/// this only collects what nobody came back for; without it staging would grow without +/// bound. +/// +public class StagingSweepWorker : BackgroundService { /// - /// Removes uploads that were staged and then neither confirmed nor cancelled - a closed - /// browser tab, a lost session. Confirming and cancelling remove their own upload, so - /// this only collects what nobody came back for; without it staging would grow without - /// bound. + /// How long an unconfirmed upload is kept. Long enough to read a preview, decide, and + /// come back to the tab; short enough that a store does not fill with abandoned files. /// - public class StagingSweepWorker : BackgroundService - { - /// - /// How long an unconfirmed upload is kept. Long enough to read a preview, decide, and - /// come back to the tab; short enough that a store does not fill with abandoned files. - /// - internal static readonly TimeSpan MaxStagingAge = TimeSpan.FromHours(24); + internal static readonly TimeSpan MaxStagingAge = TimeSpan.FromHours(24); - internal static readonly TimeSpan SweepInterval = TimeSpan.FromHours(1); + internal static readonly TimeSpan SweepInterval = TimeSpan.FromHours(1); - private readonly IServiceScopeFactory _scopes; - private readonly ILogger _logger; + private readonly IServiceScopeFactory _scopes; + private readonly ILogger _logger; - public StagingSweepWorker(IServiceScopeFactory scopes, ILogger logger) - { - _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } + public StagingSweepWorker(IServiceScopeFactory scopes, ILogger logger) + { + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) { - while (!stoppingToken.IsCancellationRequested) + // The wait comes first on purpose: an upload is confirmed within minutes of + // arriving, so nothing is urgent at startup, and a start must not wait on + // storage. + try { - // The wait comes first on purpose: an upload is confirmed within minutes of - // arriving, so nothing is urgent at startup, and a start must not wait on - // storage. - try - { - await Task.Delay(SweepInterval, stoppingToken); - } - catch (OperationCanceledException) - { - return; - } + await Task.Delay(SweepInterval, stoppingToken); + } + catch (OperationCanceledException) + { + return; + } - try - { - using var scope = _scopes.CreateScope(); - var staging = scope.ServiceProvider.GetRequiredService(); - var time = scope.ServiceProvider.GetRequiredService(); + try + { + using var scope = _scopes.CreateScope(); + var staging = scope.ServiceProvider.GetRequiredService(); + var time = scope.ServiceProvider.GetRequiredService(); - await staging.SweepAsync(time.UtcNow - MaxStagingAge, stoppingToken); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - return; - } - catch (Exception e) - { - // Retried on the next pass: a store that is briefly unreachable must not - // stop the sweep for the life of the process. - _logger.LogError(e, "Could not sweep abandoned staged uploads"); - } + await staging.SweepAsync(time.UtcNow - MaxStagingAge, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception e) + { + // Retried on the next pass: a store that is briefly unreachable must not + // stop the sweep for the life of the process. + _logger.LogError(e, "Could not sweep abandoned staged uploads"); } } } -} +} \ No newline at end of file diff --git a/src/BaGet/ConfigureBaGetOptions.cs b/src/BaGet/ConfigureBaGetOptions.cs index 1d465c272..fe00d191c 100644 --- a/src/BaGet/ConfigureBaGetOptions.cs +++ b/src/BaGet/ConfigureBaGetOptions.cs @@ -10,162 +10,161 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -namespace BaGet -{ - /// - /// BaGet's options configuration, specific to the default BaGet application. - /// Don't use this if you are embedding BaGet into your own custom ASP.NET Core application. - /// - public class ConfigureBaGetOptions - : IConfigureOptions +namespace BaGet; + +/// +/// BaGet's options configuration, specific to the default BaGet application. +/// Don't use this if you are embedding BaGet into your own custom ASP.NET Core application. +/// +public class ConfigureBaGetOptions + : IConfigureOptions , IConfigureOptions , IConfigureOptions , IConfigureOptions , IConfigureOptions , IValidateOptions - { - public const string CorsPolicy = "AllowAll"; +{ + public const string CorsPolicy = "AllowAll"; - /// - /// The entry that disables host filtering. - /// - public const string AllowAnyHost = "*"; + /// + /// The entry that disables host filtering. + /// + public const string AllowAnyHost = "*"; - private readonly IConfiguration _configuration; + private readonly IConfiguration _configuration; - public ConfigureBaGetOptions(IConfiguration configuration) - { - _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); - } + public ConfigureBaGetOptions(IConfiguration configuration) + { + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + } - private static readonly HashSet ValidDatabaseTypes - = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "AzureTable", - "MySql", - "PostgreSql", - "Sqlite", - "SqlServer", - }; - - private static readonly HashSet ValidStorageTypes - = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "AliyunOss", - "AwsS3", - "AzureBlobStorage", - "Filesystem", - "GoogleCloud", - "Null", - }; - - private static readonly HashSet ValidSearchTypes - = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "AzureSearch", - "Database", - "Null", - }; - - public void Configure(CorsOptions options) + private static readonly HashSet ValidDatabaseTypes + = new HashSet(StringComparer.OrdinalIgnoreCase) { - // TODO: Consider disabling this on production builds. - options.AddPolicy( - CorsPolicy, - builder => builder.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader()); - } - - public void Configure(FormOptions options) + "AzureTable", + "MySql", + "PostgreSql", + "Sqlite", + "SqlServer", + }; + + private static readonly HashSet ValidStorageTypes + = new HashSet(StringComparer.OrdinalIgnoreCase) { - options.MultipartBodyLengthLimit = int.MaxValue; - } - - public void Configure(ForwardedHeadersOptions options) + "AliyunOss", + "AwsS3", + "AzureBlobStorage", + "Filesystem", + "GoogleCloud", + "Null", + }; + + private static readonly HashSet ValidSearchTypes + = new HashSet(StringComparer.OrdinalIgnoreCase) { - options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + "AzureSearch", + "Database", + "Null", + }; - // Do not restrict to local network/proxy - options.KnownNetworks.Clear(); - options.KnownProxies.Clear(); - } + public void Configure(CorsOptions options) + { + // TODO: Consider disabling this on production builds. + options.AddPolicy( + CorsPolicy, + builder => builder.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader()); + } - public void Configure(HostFilteringOptions options) - { - var allowedHosts = ParseAllowedHosts(_configuration[nameof(BaGetOptions.AllowedHosts)]); + public void Configure(FormOptions options) + { + options.MultipartBodyLengthLimit = int.MaxValue; + } - options.AllowedHosts = allowedHosts; + public void Configure(ForwardedHeadersOptions options) + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; - // An absent or empty "Host" header cannot be on an allow-list, and the URLs - // BaGet advertises are built from that header. Only tolerate it while host - // filtering is disabled, which is how the middleware behaves out of the box. - options.AllowEmptyHosts = allowedHosts.Contains(AllowAnyHost); + // Do not restrict to local network/proxy + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + } + + public void Configure(HostFilteringOptions options) + { + var allowedHosts = ParseAllowedHosts(_configuration[nameof(BaGetOptions.AllowedHosts)]); + + options.AllowedHosts = allowedHosts; + + // An absent or empty "Host" header cannot be on an allow-list, and the URLs + // BaGet advertises are built from that header. Only tolerate it while host + // filtering is disabled, which is how the middleware behaves out of the box. + options.AllowEmptyHosts = allowedHosts.Contains(AllowAnyHost); + } + + /// + /// Turn a configured value into the list the + /// host filtering middleware expects. An absent or blank value means "allow any + /// host", so that a deployment which never configured this keeps working. + /// + internal static List ParseAllowedHosts(string value) + { + var hosts = (value ?? string.Empty) + .Split(';', StringSplitOptions.RemoveEmptyEntries) + // ASP.NET Core's own parsing of this key does not trim, which turns the + // usual "a.example.com; b.example.com" spacing into patterns that match + // nothing and locks out hosts the operator meant to allow. + .Select(host => host.Trim()) + .Where(host => host.Length > 0) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + if (hosts.Count == 0) + { + return new List { AllowAnyHost }; } - /// - /// Turn a configured value into the list the - /// host filtering middleware expects. An absent or blank value means "allow any - /// host", so that a deployment which never configured this keeps working. - /// - internal static List ParseAllowedHosts(string value) + return hosts; + } + + public void Configure(IISServerOptions options) + { + options.MaxRequestBodySize = 262144000; + } + + public ValidateOptionsResult Validate(string name, BaGetOptions options) + { + var failures = new List(); + + if (options.Database == null) failures.Add($"The '{nameof(BaGetOptions.Database)}' config is required"); + if (options.Mirror == null) failures.Add($"The '{nameof(BaGetOptions.Mirror)}' config is required"); + if (options.Search == null) failures.Add($"The '{nameof(BaGetOptions.Search)}' config is required"); + if (options.Storage == null) failures.Add($"The '{nameof(BaGetOptions.Storage)}' config is required"); + + if (!ValidDatabaseTypes.Contains(options.Database?.Type)) { - var hosts = (value ?? string.Empty) - .Split(';', StringSplitOptions.RemoveEmptyEntries) - // ASP.NET Core's own parsing of this key does not trim, which turns the - // usual "a.example.com; b.example.com" spacing into patterns that match - // nothing and locks out hosts the operator meant to allow. - .Select(host => host.Trim()) - .Where(host => host.Length > 0) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); - - if (hosts.Count == 0) - { - return new List { AllowAnyHost }; - } - - return hosts; + failures.Add( + $"The '{nameof(BaGetOptions.Database)}:{nameof(DatabaseOptions.Type)}' config is invalid. " + + $"Allowed values: {string.Join(", ", ValidDatabaseTypes)}"); } - public void Configure(IISServerOptions options) + if (!ValidStorageTypes.Contains(options.Storage?.Type)) { - options.MaxRequestBodySize = 262144000; + failures.Add( + $"The '{nameof(BaGetOptions.Storage)}:{nameof(StorageOptions.Type)}' config is invalid. " + + $"Allowed values: {string.Join(", ", ValidStorageTypes)}"); } - public ValidateOptionsResult Validate(string name, BaGetOptions options) + if (!ValidSearchTypes.Contains(options.Search?.Type)) { - var failures = new List(); - - if (options.Database == null) failures.Add($"The '{nameof(BaGetOptions.Database)}' config is required"); - if (options.Mirror == null) failures.Add($"The '{nameof(BaGetOptions.Mirror)}' config is required"); - if (options.Search == null) failures.Add($"The '{nameof(BaGetOptions.Search)}' config is required"); - if (options.Storage == null) failures.Add($"The '{nameof(BaGetOptions.Storage)}' config is required"); - - if (!ValidDatabaseTypes.Contains(options.Database?.Type)) - { - failures.Add( - $"The '{nameof(BaGetOptions.Database)}:{nameof(DatabaseOptions.Type)}' config is invalid. " + - $"Allowed values: {string.Join(", ", ValidDatabaseTypes)}"); - } - - if (!ValidStorageTypes.Contains(options.Storage?.Type)) - { - failures.Add( - $"The '{nameof(BaGetOptions.Storage)}:{nameof(StorageOptions.Type)}' config is invalid. " + - $"Allowed values: {string.Join(", ", ValidStorageTypes)}"); - } - - if (!ValidSearchTypes.Contains(options.Search?.Type)) - { - failures.Add( - $"The '{nameof(BaGetOptions.Search)}:{nameof(SearchOptions.Type)}' config is invalid. " + - $"Allowed values: {string.Join(", ", ValidSearchTypes)}"); - } - - if (failures.Any()) return ValidateOptionsResult.Fail(failures); - - return ValidateOptionsResult.Success; + failures.Add( + $"The '{nameof(BaGetOptions.Search)}:{nameof(SearchOptions.Type)}' config is invalid. " + + $"Allowed values: {string.Join(", ", ValidSearchTypes)}"); } + + if (failures.Any()) return ValidateOptionsResult.Fail(failures); + + return ValidateOptionsResult.Success; } -} +} \ No newline at end of file diff --git a/src/BaGet/ConfigureRazorRuntimeCompilation.cs b/src/BaGet/ConfigureRazorRuntimeCompilation.cs index 80490934e..7e43ca4f3 100644 --- a/src/BaGet/ConfigureRazorRuntimeCompilation.cs +++ b/src/BaGet/ConfigureRazorRuntimeCompilation.cs @@ -5,28 +5,27 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +public class ConfigureRazorRuntimeCompilation : IConfigureOptions { - public class ConfigureRazorRuntimeCompilation : IConfigureOptions - { - private readonly IHostEnvironment _env; + private readonly IHostEnvironment _env; - public ConfigureRazorRuntimeCompilation(IHostEnvironment env) - { - _env = env ?? throw new ArgumentNullException(nameof(env)); - } + public ConfigureRazorRuntimeCompilation(IHostEnvironment env) + { + _env = env ?? throw new ArgumentNullException(nameof(env)); + } - public void Configure(MvcRazorRuntimeCompilationOptions options) - { - var path = Path.Combine(_env.ContentRootPath, "..", "BaGet.Web"); + public void Configure(MvcRazorRuntimeCompilationOptions options) + { + var path = Path.Combine(_env.ContentRootPath, "..", "BaGet.Web"); - // Try to enable Razor "hot reload". - if (!_env.IsDevelopment()) return; - if (!Directory.Exists(path)) return; + // Try to enable Razor "hot reload". + if (!_env.IsDevelopment()) return; + if (!Directory.Exists(path)) return; - var provider = new PhysicalFileProvider(Path.GetFullPath(path)); + var provider = new PhysicalFileProvider(Path.GetFullPath(path)); - options.FileProviders.Add(provider); - } + options.FileProviders.Add(provider); } -} +} \ No newline at end of file diff --git a/src/BaGet/Program.cs b/src/BaGet/Program.cs index d7cd3a0f8..e1c675192 100644 --- a/src/BaGet/Program.cs +++ b/src/BaGet/Program.cs @@ -18,279 +18,278 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -namespace BaGet +namespace BaGet; + +/// +/// Declared partial and public so that WebApplicationFactory can name it as the entry +/// point of the integration tests. +/// +public partial class Program { - /// - /// Declared partial and public so that WebApplicationFactory can name it as the entry - /// point of the integration tests. - /// - public partial class Program + public static async Task Main(string[] args) { - public static async Task Main(string[] args) - { - var app = BuildApplication(args); + var app = BuildApplication(args); - if (!app.ValidateStartupOptions()) - { - return; - } + if (!app.ValidateStartupOptions()) + { + return; + } - var commands = new CommandLineApplication - { - Name = "baget", - Description = "A light-weight NuGet service", + var commands = new CommandLineApplication + { + Name = "baget", + Description = "A light-weight NuGet service", - // The host consumes arguments of its own - "--environment", - // "--contentRoot", "--applicationName" and the rest - and they reach this - // parser too. Rejecting them would make a legitimate invocation such as - // "baget --environment Staging" fail before the service starts. - UnrecognizedArgumentHandling = UnrecognizedArgumentHandling.CollectAndContinue, - }; + // The host consumes arguments of its own - "--environment", + // "--contentRoot", "--applicationName" and the rest - and they reach this + // parser too. Rejecting them would make a legitimate invocation such as + // "baget --environment Staging" fail before the service starts. + UnrecognizedArgumentHandling = UnrecognizedArgumentHandling.CollectAndContinue, + }; - commands.HelpOption(inherited: true); + commands.HelpOption(inherited: true); - commands.Command("import", import => + commands.Command("import", import => + { + import.Command("downloads", downloads => { - import.Command("downloads", downloads => + downloads.OnExecuteAsync(async cancellationToken => { - downloads.OnExecuteAsync(async cancellationToken => + using (var scope = app.Services.CreateScope()) { - using (var scope = app.Services.CreateScope()) - { - var importer = scope.ServiceProvider.GetRequiredService(); + var importer = scope.ServiceProvider.GetRequiredService(); - await importer.ImportAsync(cancellationToken); - } - }); + await importer.ImportAsync(cancellationToken); + } }); }); + }); - commands.Command("catalog", catalog => + commands.Command("catalog", catalog => + { + catalog.Command("rebuild", rebuild => { - catalog.Command("rebuild", rebuild => + rebuild.Description = "Append the catalog entries missing for the packages in the database."; + rebuild.OnExecuteAsync(async cancellationToken => { - rebuild.Description = "Append the catalog entries missing for the packages in the database."; - rebuild.OnExecuteAsync(async cancellationToken => + using (var scope = app.Services.CreateScope()) { - using (var scope = app.Services.CreateScope()) - { - var rebuilder = scope.ServiceProvider.GetRequiredService(); + var rebuilder = scope.ServiceProvider.GetRequiredService(); - await rebuilder.RebuildAsync(cancellationToken); - } - }); + await rebuilder.RebuildAsync(cancellationToken); + } }); }); + }); - commands.Option("--urls", "The URLs that BaGet should bind to.", CommandOptionType.SingleValue); - - commands.OnExecuteAsync(async cancellationToken => - { - await app.RunMigrationsAsync(cancellationToken); - await app.RunAsync(cancellationToken); - }); - - await commands.ExecuteAsync(args); - } + commands.Option("--urls", "The URLs that BaGet should bind to.", CommandOptionType.SingleValue); - /// - /// Build the application: configuration, services and the request pipeline. - /// - /// - /// The integration tests reach the host through this, by way of - /// WebApplicationFactory, which runs and takes the application as - /// it is built. The command line wiring in therefore runs only - /// when BaGet is started for real. - /// - public static WebApplication BuildApplication(string[] args) + commands.OnExecuteAsync(async cancellationToken => { - var builder = WebApplication.CreateBuilder(args); + await app.RunMigrationsAsync(cancellationToken); + await app.RunAsync(cancellationToken); + }); - ConfigureConfiguration(builder.Configuration); - ConfigureWebHost(builder.WebHost); - ConfigureServices(builder.Services, builder.Configuration); + await commands.ExecuteAsync(args); + } - var app = builder.Build(); + /// + /// Build the application: configuration, services and the request pipeline. + /// + /// + /// The integration tests reach the host through this, by way of + /// WebApplicationFactory, which runs and takes the application as + /// it is built. The command line wiring in therefore runs only + /// when BaGet is started for real. + /// + public static WebApplication BuildApplication(string[] args) + { + var builder = WebApplication.CreateBuilder(args); - ConfigurePipeline(app); + ConfigureConfiguration(builder.Configuration); + ConfigureWebHost(builder.WebHost); + ConfigureServices(builder.Services, builder.Configuration); - return app; - } + var app = builder.Build(); - private static void ConfigureConfiguration(IConfigurationBuilder configuration) - { - var root = Environment.GetEnvironmentVariable("BAGET_CONFIG_ROOT"); + ConfigurePipeline(app); - if (!string.IsNullOrEmpty(root)) - { - configuration.SetBasePath(root); - } - } + return app; + } - private static void ConfigureWebHost(IWebHostBuilder web) - { - web.ConfigureKestrel(options => - { - // Remove the upload limit from Kestrel. If needed, an upload limit can - // be enforced by a reverse proxy server, like IIS. - options.Limits.MaxRequestBodySize = null; - }); - } + private static void ConfigureConfiguration(IConfigurationBuilder configuration) + { + var root = Environment.GetEnvironmentVariable("BAGET_CONFIG_ROOT"); - private static void ConfigureServices(IServiceCollection services, IConfiguration configuration) + if (!string.IsNullOrEmpty(root)) { - // Ideally we'd use: - // - // services.ConfigureOptions(); - // - // However, "ConfigureOptions" doesn't register validations as expected. - // We'll instead register all these configurations manually. - // See: https://github.com/dotnet/runtime/issues/38491 - services.AddTransient, ConfigureBaGetOptions>(); - services.AddTransient, ConfigureBaGetOptions>(); - services.AddTransient, ConfigureBaGetOptions>(); - services.AddTransient, ConfigureBaGetOptions>(); - services.AddTransient, ConfigureBaGetOptions>(); - services.AddTransient, ConfigureBaGetOptions>(); - - services.AddBaGetOptions(nameof(IISServerOptions)); - services.AddBaGetWebApplication(ConfigureBaGetApplication); - services.AddBaGetAccounts(configuration); - - // You can swap between implementations of subsystems like storage and search using BaGet's configuration. - // Each subsystem's implementation has a provider that reads the configuration to determine if it should be - // activated. BaGet will run through all its providers until it finds one that is active. - services.AddScoped(DependencyInjectionExtensions.GetServiceFromProviders); - services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders); - services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders); - services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders); - services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders); - - services.AddSingleton, ConfigureRazorRuntimeCompilation>(); - - services.AddCors(); + configuration.SetBasePath(root); } + } - private static void ConfigureBaGetApplication(BaGetApplication app) + private static void ConfigureWebHost(IWebHostBuilder web) + { + web.ConfigureKestrel(options => { - // Add database providers. - app.AddAzureTableDatabase(); - app.AddMySqlDatabase(); - app.AddPostgreSqlDatabase(); - app.AddSqliteDatabase(); - app.AddSqlServerDatabase(); - - // Add storage providers. - app.AddFileStorage(); - app.AddAliyunOssStorage(); - app.AddAwsS3Storage(); - app.AddAzureBlobStorage(); - app.AddGoogleCloudStorage(); - - // Add search providers. - app.AddAzureSearch(); - } + // Remove the upload limit from Kestrel. If needed, an upload limit can + // be enforced by a reverse proxy server, like IIS. + options.Limits.MaxRequestBodySize = null; + }); + } - private static void ConfigurePipeline(WebApplication app) + private static void ConfigureServices(IServiceCollection services, IConfiguration configuration) + { + // Ideally we'd use: + // + // services.ConfigureOptions(); + // + // However, "ConfigureOptions" doesn't register validations as expected. + // We'll instead register all these configurations manually. + // See: https://github.com/dotnet/runtime/issues/38491 + services.AddTransient, ConfigureBaGetOptions>(); + services.AddTransient, ConfigureBaGetOptions>(); + services.AddTransient, ConfigureBaGetOptions>(); + services.AddTransient, ConfigureBaGetOptions>(); + services.AddTransient, ConfigureBaGetOptions>(); + services.AddTransient, ConfigureBaGetOptions>(); + + services.AddBaGetOptions(nameof(IISServerOptions)); + services.AddBaGetWebApplication(ConfigureBaGetApplication); + services.AddBaGetAccounts(configuration); + + // You can swap between implementations of subsystems like storage and search using BaGet's configuration. + // Each subsystem's implementation has a provider that reads the configuration to determine if it should be + // activated. BaGet will run through all its providers until it finds one that is active. + services.AddScoped(DependencyInjectionExtensions.GetServiceFromProviders); + services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders); + services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders); + services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders); + services.AddTransient(DependencyInjectionExtensions.GetServiceFromProviders); + + services.AddSingleton, ConfigureRazorRuntimeCompilation>(); + + services.AddCors(); + } + + private static void ConfigureBaGetApplication(BaGetApplication app) + { + // Add database providers. + app.AddAzureTableDatabase(); + app.AddMySqlDatabase(); + app.AddPostgreSqlDatabase(); + app.AddSqliteDatabase(); + app.AddSqlServerDatabase(); + + // Add storage providers. + app.AddFileStorage(); + app.AddAliyunOssStorage(); + app.AddAwsS3Storage(); + app.AddAzureBlobStorage(); + app.AddGoogleCloudStorage(); + + // Add search providers. + app.AddAzureSearch(); + } + + private static void ConfigurePipeline(WebApplication app) + { + var options = app.Configuration.Get(); + + // Reject a request whose "Host" header is not one BaGet serves, before anything + // reads it. Every absolute URL BaGet advertises is built from that header, so a + // forged host would otherwise decide where clients are sent. + // + // The default builder happens to add this middleware as well, but BaGet cannot + // rely on that: a host built with a slim or empty builder does not, and the check + // is BaGet's to own. Running it twice is a repeated string comparison, which is + // cheaper than depending on the builder's choices. + app.UseHostFiltering(); + + WarnIfNothingAuthenticates(app, options); + + if (app.Environment.IsDevelopment()) { - var options = app.Configuration.Get(); + app.UseDeveloperExceptionPage(); + app.UseStatusCodePages(); + } - // Reject a request whose "Host" header is not one BaGet serves, before anything - // reads it. Every absolute URL BaGet advertises is built from that header, so a - // forged host would otherwise decide where clients are sent. - // - // The default builder happens to add this middleware as well, but BaGet cannot - // rely on that: a host built with a slim or empty builder does not, and the check - // is BaGet's to own. Running it twice is a repeated string comparison, which is - // cheaper than depending on the builder's choices. - app.UseHostFiltering(); + // The configured path base may be absent, "." meaning the root, or a path that + // is missing its leading slash. Normalise it once so that startup cannot fail on + // an unusable value and so both uses below agree on it. + var pathBase = NormalizePathBase(options.PathBase); - WarnIfNothingAuthenticates(app, options); + app.UseForwardedHeaders(); + app.UsePathBase(pathBase); - if (app.Environment.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - app.UseStatusCodePages(); - } - - // The configured path base may be absent, "." meaning the root, or a path that - // is missing its leading slash. Normalise it once so that startup cannot fail on - // an unusable value and so both uses below agree on it. - var pathBase = NormalizePathBase(options.PathBase); - - app.UseForwardedHeaders(); - app.UsePathBase(pathBase); - - // UsePathBase only sets the request's path base if the incoming path starts - // with it. A reverse proxy may instead strip the path base before forwarding, - // leaving nothing for UsePathBase to match, and BaGet would then advertise - // URLs that bypass the proxy. Apply the configured path base in that case. - if (pathBase.HasValue) + // UsePathBase only sets the request's path base if the incoming path starts + // with it. A reverse proxy may instead strip the path base before forwarding, + // leaving nothing for UsePathBase to match, and BaGet would then advertise + // URLs that bypass the proxy. Apply the configured path base in that case. + if (pathBase.HasValue) + { + app.Use((context, next) => { - app.Use((context, next) => + if (!context.Request.PathBase.HasValue) { - if (!context.Request.PathBase.HasValue) - { - context.Request.PathBase = pathBase; - } + context.Request.PathBase = pathBase; + } - return next(); - }); - } + return next(); + }); + } - app.UseStaticFiles(); - app.UseRouting(); + app.UseStaticFiles(); + app.UseRouting(); - app.UseCors(ConfigureBaGetOptions.CorsPolicy); - app.UseAuthentication(); - app.UseAuthorization(); - app.UseOperationCancelledMiddleware(); + app.UseCors(ConfigureBaGetOptions.CorsPolicy); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseOperationCancelledMiddleware(); - // WebApplication is itself an endpoint route builder, so the endpoints are mapped - // onto it directly rather than inside a UseEndpoints callback. - new BaGetEndpointBuilder().MapEndpoints(app); - } + // WebApplication is itself an endpoint route builder, so the endpoints are mapped + // onto it directly rather than inside a UseEndpoints callback. + new BaGetEndpointBuilder().MapEndpoints(app); + } - /// - /// Say once, at startup, that this server accepts packages from anyone. With no - /// global API key and no accounts there is nothing to tell one caller from another, - /// so every push, overwrite and delete is open to whoever can reach the server. That - /// is a legitimate configuration on a private network and the shipped default, which - /// is exactly why it must not be silent. - /// - private static void WarnIfNothingAuthenticates(WebApplication app, BaGetOptions options) - { - if (options.IsReadOnlyMode) return; - if (!string.IsNullOrEmpty(options.ApiKey)) return; + /// + /// Say once, at startup, that this server accepts packages from anyone. With no + /// global API key and no accounts there is nothing to tell one caller from another, + /// so every push, overwrite and delete is open to whoever can reach the server. That + /// is a legitimate configuration on a private network and the shipped default, which + /// is exactly why it must not be silent. + /// + private static void WarnIfNothingAuthenticates(WebApplication app, BaGetOptions options) + { + if (options.IsReadOnlyMode) return; + if (!string.IsNullOrEmpty(options.ApiKey)) return; - var accounts = app.Configuration.GetSection(nameof(BaGetOptions.Accounts)).Get(); - if (accounts?.Enabled == true) return; + var accounts = app.Configuration.GetSection(nameof(BaGetOptions.Accounts)).Get(); + if (accounts?.Enabled == true) return; - app.Logger.LogWarning( - "No API key is configured and accounts are disabled, so anyone who can reach this " - + "server may publish packages, claim package IDs and delete versions. Set \"ApiKey\", " - + "or turn on \"Accounts:Enabled\", to require authentication."); - } + app.Logger.LogWarning( + "No API key is configured and accounts are disabled, so anyone who can reach this " + + "server may publish packages, claim package IDs and delete versions. Set \"ApiKey\", " + + "or turn on \"Accounts:Enabled\", to require authentication."); + } - /// - /// Turn a configured path base into one the request pipeline can use. An absent - /// value, "." and "/" all mean "no path base"; anything else is given the leading - /// slash that requires. - /// - internal static PathString NormalizePathBase(string value) + /// + /// Turn a configured path base into one the request pipeline can use. An absent + /// value, "." and "/" all mean "no path base"; anything else is given the leading + /// slash that requires. + /// + internal static PathString NormalizePathBase(string value) + { + if (string.IsNullOrWhiteSpace(value)) { - if (string.IsNullOrWhiteSpace(value)) - { - return PathString.Empty; - } - - var trimmed = value.Trim().TrimEnd('/'); - if (trimmed.Length == 0 || trimmed == ".") - { - return PathString.Empty; - } + return PathString.Empty; + } - return new PathString(trimmed.StartsWith("/") ? trimmed : "/" + trimmed); + var trimmed = value.Trim().TrimEnd('/'); + if (trimmed.Length == 0 || trimmed == ".") + { + return PathString.Empty; } + + return new PathString(trimmed.StartsWith("/") ? trimmed : "/" + trimmed); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Azure.Tests/Search/AzureAutocompleteQueryTests.cs b/tests/BaGet.Azure.Tests/Search/AzureAutocompleteQueryTests.cs index 06e866aa6..18cfdb95d 100644 --- a/tests/BaGet.Azure.Tests/Search/AzureAutocompleteQueryTests.cs +++ b/tests/BaGet.Azure.Tests/Search/AzureAutocompleteQueryTests.cs @@ -3,108 +3,107 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Azure.Tests.Search +namespace BaGet.Azure.Tests.Search; + +public class AzureAutocompleteQueryTests { - public class AzureAutocompleteQueryTests + [Fact] + public void PrefixMatchesTheWholeIdAndKeepsTheAnalyzedMatch() { - [Fact] - public void PrefixMatchesTheWholeIdAndKeepsTheAnalyzedMatch() - { - // The analyzed match keeps documents indexed before "normalizedId" existed findable. - Assert.Equal( - @"+(normalizedId:newtonsoft.js* OR newtonsoft.js)", - AzureSearchService.BuildAutocompleteQuery("Newtonsoft.Js", packageType: null)); - } + // The analyzed match keeps documents indexed before "normalizedId" existed findable. + Assert.Equal( + @"+(normalizedId:newtonsoft.js* OR newtonsoft.js)", + AzureSearchService.BuildAutocompleteQuery("Newtonsoft.Js", packageType: null)); + } - [Fact] - public void EscapesTheQuery() - { - Assert.Equal( - @"+(normalizedId:a\:b\)* OR a\:b\))", - AzureSearchService.BuildAutocompleteQuery("a:b)", packageType: null)); - } + [Fact] + public void EscapesTheQuery() + { + Assert.Equal( + @"+(normalizedId:a\:b\)* OR a\:b\))", + AzureSearchService.BuildAutocompleteQuery("a:b)", packageType: null)); + } - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - [InlineData("*")] - public void AnEmptyQueryMatchesEverything(string query) - { - Assert.Equal("*", AzureSearchService.BuildAutocompleteQuery(query, packageType: null)); - } + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("*")] + public void AnEmptyQueryMatchesEverything(string query) + { + Assert.Equal("*", AzureSearchService.BuildAutocompleteQuery(query, packageType: null)); + } - [Fact] - public void AddsThePackageTypeAsARequiredClause() - { - Assert.Equal( - @"+(normalizedId:foo* OR foo) +packageTypes:""DotnetTool""", - AzureSearchService.BuildAutocompleteQuery("foo", "DotnetTool")); - } + [Fact] + public void AddsThePackageTypeAsARequiredClause() + { + Assert.Equal( + @"+(normalizedId:foo* OR foo) +packageTypes:""DotnetTool""", + AzureSearchService.BuildAutocompleteQuery("foo", "DotnetTool")); + } - [Fact] - public void APackageTypeAloneIsAValidQuery() - { - Assert.Equal(@"+packageTypes:""DotnetTool""", AzureSearchService.BuildAutocompleteQuery(null, "DotnetTool")); - } + [Fact] + public void APackageTypeAloneIsAValidQuery() + { + Assert.Equal(@"+packageTypes:""DotnetTool""", AzureSearchService.BuildAutocompleteQuery(null, "DotnetTool")); + } - [Fact] - public void TheVersionsFilterIsAnExactLowercaseMatch() - { - Assert.Equal( - "normalizedId eq 'newtonsoft.json' and searchFilters eq 'Default'", - AzureSearchService.BuildVersionsFilter("Newtonsoft.Json", "searchFilters eq 'Default'")); - } + [Fact] + public void TheVersionsFilterIsAnExactLowercaseMatch() + { + Assert.Equal( + "normalizedId eq 'newtonsoft.json' and searchFilters eq 'Default'", + AzureSearchService.BuildVersionsFilter("Newtonsoft.Json", "searchFilters eq 'Default'")); + } - [Fact] - public void TheVersionsFilterEscapesAQuote() - { - Assert.Equal( - "normalizedId eq 'a''b' and x", - AzureSearchService.BuildVersionsFilter("a'b", "x")); - } + [Fact] + public void TheVersionsFilterEscapesAQuote() + { + Assert.Equal( + "normalizedId eq 'a''b' and x", + AzureSearchService.BuildVersionsFilter("a'b", "x")); + } - [Fact] - public void IndexedDocumentsCarryTheNormalizedId() + [Fact] + public void IndexedDocumentsCarryTheNormalizedId() + { + var package = new Package { - var package = new Package - { - Id = "Newtonsoft.Json", - Version = NuGetVersion.Parse("1.0.0"), - Authors = new string[0], - Tags = new string[0], - Listed = true, - Dependencies = new List(), - PackageTypes = new List(), - TargetFrameworks = new List(), - }; + Id = "Newtonsoft.Json", + Version = NuGetVersion.Parse("1.0.0"), + Authors = new string[0], + Tags = new string[0], + Listed = true, + Dependencies = new List(), + PackageTypes = new List(), + TargetFrameworks = new List(), + }; - var actions = new IndexActionBuilder().AddPackage(new PackageRegistration("Newtonsoft.Json", new[] { package })); + var actions = new IndexActionBuilder().AddPackage(new PackageRegistration("Newtonsoft.Json", new[] { package })); - Assert.All(actions, a => Assert.Equal("newtonsoft.json", ((PackageDocument)a.Document).NormalizedId)); - } + Assert.All(actions, a => Assert.Equal("newtonsoft.json", ((PackageDocument)a.Document).NormalizedId)); } +} - public class TableSearchFilterTests +public class TableSearchFilterTests +{ + [Fact] + public void TheSearchPrefixIsLowercasedToMatchThePartitionKeys() { - [Fact] - public void TheSearchPrefixIsLowercasedToMatchThePartitionKeys() - { - var filter = TableSearchService.GenerateSearchFilter("Newtonsoft", includePrerelease: true, includeSemVer2: true); + var filter = TableSearchService.GenerateSearchFilter("Newtonsoft", includePrerelease: true, includeSemVer2: true); - Assert.Contains("PartitionKey ge 'newtonsoft'", filter); - Assert.DoesNotContain("Newtonsoft", filter); - } + Assert.Contains("PartitionKey ge 'newtonsoft'", filter); + Assert.DoesNotContain("Newtonsoft", filter); + } - [Fact] - public void TheVersionsFilterSelectsOnePartition() - { - var filter = TableSearchService.GenerateVersionsFilter("Newtonsoft.Json", includePrerelease: false, includeSemVer2: false); + [Fact] + public void TheVersionsFilterSelectsOnePartition() + { + var filter = TableSearchService.GenerateVersionsFilter("Newtonsoft.Json", includePrerelease: false, includeSemVer2: false); - Assert.Contains("PartitionKey eq 'newtonsoft.json'", filter); - Assert.Contains("Listed eq true", filter); - Assert.Contains("IsPrerelease eq false", filter); - Assert.Contains("SemVerLevel eq 0", filter); - } + Assert.Contains("PartitionKey eq 'newtonsoft.json'", filter); + Assert.Contains("Listed eq true", filter); + Assert.Contains("IsPrerelease eq false", filter); + Assert.Contains("SemVerLevel eq 0", filter); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Azure.Tests/Search/AzureSearchFilterTests.cs b/tests/BaGet.Azure.Tests/Search/AzureSearchFilterTests.cs index 8776250ae..c4cd3accb 100644 --- a/tests/BaGet.Azure.Tests/Search/AzureSearchFilterTests.cs +++ b/tests/BaGet.Azure.Tests/Search/AzureSearchFilterTests.cs @@ -4,74 +4,73 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Azure.Tests.Search +namespace BaGet.Azure.Tests.Search; + +/// +/// Covers the OData filter that uses to pick the document for +/// a set of search filters. writes one document per +/// value, so the filter's value has to be exactly what the indexer +/// writes, or a query silently matches nothing - or every copy of the same package. +/// +public class AzureSearchFilterTests { - /// - /// Covers the OData filter that uses to pick the document for - /// a set of search filters. writes one document per - /// value, so the filter's value has to be exactly what the indexer - /// writes, or a query silently matches nothing - or every copy of the same package. - /// - public class AzureSearchFilterTests + [Theory] + [InlineData(false, false, "searchFilters eq 'Default'")] + [InlineData(true, false, "searchFilters eq 'IncludePrerelease'")] + [InlineData(false, true, "searchFilters eq 'IncludeSemVer2'")] + [InlineData(true, true, "searchFilters eq 'IncludePrereleaseAndSemVer2'")] + public void BuildsTheFilterForEachCombination(bool prerelease, bool semVer2, string expected) { - [Theory] - [InlineData(false, false, "searchFilters eq 'Default'")] - [InlineData(true, false, "searchFilters eq 'IncludePrerelease'")] - [InlineData(false, true, "searchFilters eq 'IncludeSemVer2'")] - [InlineData(true, true, "searchFilters eq 'IncludePrereleaseAndSemVer2'")] - public void BuildsTheFilterForEachCombination(bool prerelease, bool semVer2, string expected) - { - Assert.Equal(expected, AzureSearchService.BuildSearchFilter(prerelease, semVer2)); - } - - [Theory] - [InlineData(false, false)] - [InlineData(true, false)] - [InlineData(false, true)] - [InlineData(true, true)] - public void MatchesExactlyOneIndexedDocument(bool prerelease, bool semVer2) - { - var documents = IndexedDocuments(); - var filter = AzureSearchService.BuildSearchFilter(prerelease, semVer2); - - // Four documents are indexed for this registration, one per search filter. - Assert.Equal(4, documents.Count); - Assert.Single(documents.Where(d => $"searchFilters eq '{d.SearchFilters}'" == filter)); - } + Assert.Equal(expected, AzureSearchService.BuildSearchFilter(prerelease, semVer2)); + } - private static List IndexedDocuments() - { - // A stable, a prerelease and a SemVer 2.0.0 version, so that none of the four search - // filter combinations is empty. - var registration = new PackageRegistration( - "Test", - new[] - { - Package("1.0.0", prerelease: false, semVerLevel: SemVerLevel.Unknown), - Package("2.0.0-beta", prerelease: true, semVerLevel: SemVerLevel.Unknown), - Package("3.0.0+build", prerelease: false, semVerLevel: SemVerLevel.SemVer2), - }); + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void MatchesExactlyOneIndexedDocument(bool prerelease, bool semVer2) + { + var documents = IndexedDocuments(); + var filter = AzureSearchService.BuildSearchFilter(prerelease, semVer2); - return new IndexActionBuilder() - .AddPackage(registration) - .Select(a => a.Document) - .OfType() - .ToList(); - } + // Four documents are indexed for this registration, one per search filter. + Assert.Equal(4, documents.Count); + Assert.Single(documents.Where(d => $"searchFilters eq '{d.SearchFilters}'" == filter)); + } - private static Package Package(string version, bool prerelease, SemVerLevel semVerLevel) - => new Package + private static List IndexedDocuments() + { + // A stable, a prerelease and a SemVer 2.0.0 version, so that none of the four search + // filter combinations is empty. + var registration = new PackageRegistration( + "Test", + new[] { - Id = "Test", - Version = NuGetVersion.Parse(version), - Listed = true, - IsPrerelease = prerelease, - SemVerLevel = semVerLevel, - Authors = new[] { "author" }, - Tags = new[] { "tag" }, - Dependencies = new List(), - PackageTypes = new List(), - TargetFrameworks = new List(), - }; + Package("1.0.0", prerelease: false, semVerLevel: SemVerLevel.Unknown), + Package("2.0.0-beta", prerelease: true, semVerLevel: SemVerLevel.Unknown), + Package("3.0.0+build", prerelease: false, semVerLevel: SemVerLevel.SemVer2), + }); + + return new IndexActionBuilder() + .AddPackage(registration) + .Select(a => a.Document) + .OfType() + .ToList(); } -} + + private static Package Package(string version, bool prerelease, SemVerLevel semVerLevel) + => new Package + { + Id = "Test", + Version = NuGetVersion.Parse(version), + Listed = true, + IsPrerelease = prerelease, + SemVerLevel = semVerLevel, + Authors = new[] { "author" }, + Tags = new[] { "tag" }, + Dependencies = new List(), + PackageTypes = new List(), + TargetFrameworks = new List(), + }; +} \ No newline at end of file diff --git a/tests/BaGet.Azure.Tests/Search/AzureSearchQueryBuilderTests.cs b/tests/BaGet.Azure.Tests/Search/AzureSearchQueryBuilderTests.cs index f895f2f1b..7b849848e 100644 --- a/tests/BaGet.Azure.Tests/Search/AzureSearchQueryBuilderTests.cs +++ b/tests/BaGet.Azure.Tests/Search/AzureSearchQueryBuilderTests.cs @@ -1,178 +1,177 @@ using System; using Xunit; -namespace BaGet.Azure.Tests.Search +namespace BaGet.Azure.Tests.Search; + +/// +/// The search runs with the full Lucene syntax, so every caller supplied value that +/// reaches the query has to be escaped or it changes what the query means. +/// +public class AzureSearchQueryBuilderTests { - /// - /// The search runs with the full Lucene syntax, so every caller supplied value that - /// reaches the query has to be escaped or it changes what the query means. - /// - public class AzureSearchQueryBuilderTests + public class EscapeQueryTerm { - public class EscapeQueryTerm - { - [Theory] - [InlineData("newtonsoft", "newtonsoft")] - [InlineData("Newtonsoft.Json", "Newtonsoft.Json")] - [InlineData("my_package", "my_package")] - [InlineData("", "")] - public void LeavesAnOrdinaryTermAlone(string input, string expected) - { - Assert.Equal(expected, AzureSearchService.EscapeQueryTerm(input)); - } - - [Theory] - [InlineData("+", @"\+")] - [InlineData("-", @"\-")] - [InlineData("&", @"\&")] - [InlineData("|", @"\|")] - [InlineData("!", @"\!")] - [InlineData("(", @"\(")] - [InlineData(")", @"\)")] - [InlineData("{", @"\{")] - [InlineData("}", @"\}")] - [InlineData("[", @"\[")] - [InlineData("]", @"\]")] - [InlineData("^", @"\^")] - [InlineData("~", @"\~")] - [InlineData("*", @"\*")] - [InlineData("?", @"\?")] - [InlineData(":", @"\:")] - [InlineData("/", @"\/")] - public void EscapesEachSyntaxCharacter(string input, string expected) - { - Assert.Equal(expected, AzureSearchService.EscapeQueryTerm(input)); - } + [Theory] + [InlineData("newtonsoft", "newtonsoft")] + [InlineData("Newtonsoft.Json", "Newtonsoft.Json")] + [InlineData("my_package", "my_package")] + [InlineData("", "")] + public void LeavesAnOrdinaryTermAlone(string input, string expected) + { + Assert.Equal(expected, AzureSearchService.EscapeQueryTerm(input)); + } - [Fact] - public void EscapesAQuote() - { - Assert.Equal(@"\""", AzureSearchService.EscapeQueryTerm(@"""")); - } + [Theory] + [InlineData("+", @"\+")] + [InlineData("-", @"\-")] + [InlineData("&", @"\&")] + [InlineData("|", @"\|")] + [InlineData("!", @"\!")] + [InlineData("(", @"\(")] + [InlineData(")", @"\)")] + [InlineData("{", @"\{")] + [InlineData("}", @"\}")] + [InlineData("[", @"\[")] + [InlineData("]", @"\]")] + [InlineData("^", @"\^")] + [InlineData("~", @"\~")] + [InlineData("*", @"\*")] + [InlineData("?", @"\?")] + [InlineData(":", @"\:")] + [InlineData("/", @"\/")] + public void EscapesEachSyntaxCharacter(string input, string expected) + { + Assert.Equal(expected, AzureSearchService.EscapeQueryTerm(input)); + } - [Fact] - public void EscapesABackslash() - { - Assert.Equal(@"\\", AzureSearchService.EscapeQueryTerm(@"\")); - } + [Fact] + public void EscapesAQuote() + { + Assert.Equal(@"\""", AzureSearchService.EscapeQueryTerm(@"""")); + } - [Fact] - public void DoesNotQuote() - { - // A phrase cannot carry a trailing "*", so a term must not be quoted. - Assert.DoesNotContain(@"""", AzureSearchService.EscapeQueryTerm("prefix")); - } + [Fact] + public void EscapesABackslash() + { + Assert.Equal(@"\\", AzureSearchService.EscapeQueryTerm(@"\")); + } - [Fact] - public void ThrowsForNull() - { - Assert.Throws(() => AzureSearchService.EscapeQueryTerm(null)); - } + [Fact] + public void DoesNotQuote() + { + // A phrase cannot carry a trailing "*", so a term must not be quoted. + Assert.DoesNotContain(@"""", AzureSearchService.EscapeQueryTerm("prefix")); } - public class BuildSearchQuery + [Fact] + public void ThrowsForNull() { - /// - /// The number of quotes that actually delimit a phrase, ignoring any that are - /// escaped and are therefore literal text inside one. - /// - private static int UnescapedQuotes(string value) - { - var count = 0; + Assert.Throws(() => AzureSearchService.EscapeQueryTerm(null)); + } + } - for (var i = 0; i < value.Length; i++) - { - if (value[i] != '"') continue; - if (i > 0 && value[i - 1] == '\\') continue; + public class BuildSearchQuery + { + /// + /// The number of quotes that actually delimit a phrase, ignoring any that are + /// escaped and are therefore literal text inside one. + /// + private static int UnescapedQuotes(string value) + { + var count = 0; - count++; - } + for (var i = 0; i < value.Length; i++) + { + if (value[i] != '"') continue; + if (i > 0 && value[i - 1] == '\\') continue; - return count; + count++; } - [Fact] - public void IsEmptyWithNoCriteria() - { - Assert.Equal(string.Empty, AzureSearchService.BuildSearchQuery(null, null, null)); - } + return count; + } - [Fact] - public void MakesTheQueryAPrefixSearch() - { - Assert.Equal("json*", AzureSearchService.BuildSearchQuery("json", null, null)); - } + [Fact] + public void IsEmptyWithNoCriteria() + { + Assert.Equal(string.Empty, AzureSearchService.BuildSearchQuery(null, null, null)); + } - [Fact] - public void DoesNotDoubleTheWildcard() - { - Assert.Equal("json*", AzureSearchService.BuildSearchQuery("json*", null, null)); - } + [Fact] + public void MakesTheQueryAPrefixSearch() + { + Assert.Equal("json*", AzureSearchService.BuildSearchQuery("json", null, null)); + } - [Fact] - public void EscapesTheQueryWhileKeepingItAPrefixSearch() - { - // Unescaped, the ")" closes a clause the caller never opened and the "+id:" - // that follows becomes query syntax rather than text to match. - var built = AzureSearchService.BuildSearchQuery(") +id:evil", null, null); + [Fact] + public void DoesNotDoubleTheWildcard() + { + Assert.Equal("json*", AzureSearchService.BuildSearchQuery("json*", null, null)); + } - Assert.Equal(@"\) \+id\:evil*", built); - } + [Fact] + public void EscapesTheQueryWhileKeepingItAPrefixSearch() + { + // Unescaped, the ")" closes a clause the caller never opened and the "+id:" + // that follows becomes query syntax rather than text to match. + var built = AzureSearchService.BuildSearchQuery(") +id:evil", null, null); - [Fact] - public void QuotesThePackageType() - { - Assert.Equal( - @" +packageTypes:""DotnetTool""", - AzureSearchService.BuildSearchQuery(null, "DotnetTool", null)); - } + Assert.Equal(@"\) \+id\:evil*", built); + } - [Fact] - public void EscapesAPackageTypeThatWouldInjectAClause() - { - var built = AzureSearchService.BuildSearchQuery( - null, @"a"" OR id:evil OR ""b", null); + [Fact] + public void QuotesThePackageType() + { + Assert.Equal( + @" +packageTypes:""DotnetTool""", + AzureSearchService.BuildSearchQuery(null, "DotnetTool", null)); + } - // The injected quotes are escaped, so they are literal text inside the phrase - // and only the two delimiters are unescaped - the clause cannot be closed. - Assert.Equal(@" +packageTypes:""a\"" OR id:evil OR \""b""", built); - Assert.Equal(2, UnescapedQuotes(built)); - } + [Fact] + public void EscapesAPackageTypeThatWouldInjectAClause() + { + var built = AzureSearchService.BuildSearchQuery( + null, @"a"" OR id:evil OR ""b", null); - [Fact] - public void QuotesEveryFramework() - { - Assert.Equal( - @" +frameworks:(""net6.0"" ""any"")", - AzureSearchService.BuildSearchQuery(null, null, new[] { "net6.0", "any" })); - } + // The injected quotes are escaped, so they are literal text inside the phrase + // and only the two delimiters are unescaped - the clause cannot be closed. + Assert.Equal(@" +packageTypes:""a\"" OR id:evil OR \""b""", built); + Assert.Equal(2, UnescapedQuotes(built)); + } - [Fact] - public void EscapesAFrameworkThatWouldInjectAClause() - { - // An unrecognised moniker is passed through verbatim by - // FindAllCompatibleFrameworks, so it reaches the query as the caller typed it. - var built = AzureSearchService.BuildSearchQuery( - null, null, new[] { @"a"") OR id:evil OR (""b", "any" }); - - // Four unescaped quotes: two phrases, each with its own pair. - Assert.Equal(4, UnescapedQuotes(built)); - Assert.Contains(@"\""", built); - } + [Fact] + public void QuotesEveryFramework() + { + Assert.Equal( + @" +frameworks:(""net6.0"" ""any"")", + AzureSearchService.BuildSearchQuery(null, null, new[] { "net6.0", "any" })); + } - [Fact] - public void IgnoresAnEmptyFrameworkList() - { - Assert.Equal(string.Empty, AzureSearchService.BuildSearchQuery(null, null, new string[0])); - } + [Fact] + public void EscapesAFrameworkThatWouldInjectAClause() + { + // An unrecognised moniker is passed through verbatim by + // FindAllCompatibleFrameworks, so it reaches the query as the caller typed it. + var built = AzureSearchService.BuildSearchQuery( + null, null, new[] { @"a"") OR id:evil OR (""b", "any" }); + + // Four unescaped quotes: two phrases, each with its own pair. + Assert.Equal(4, UnescapedQuotes(built)); + Assert.Contains(@"\""", built); + } - [Fact] - public void CombinesEveryCriterion() - { - var built = AzureSearchService.BuildSearchQuery("json", "DotnetTool", new[] { "net6.0" }); + [Fact] + public void IgnoresAnEmptyFrameworkList() + { + Assert.Equal(string.Empty, AzureSearchService.BuildSearchQuery(null, null, new string[0])); + } - Assert.Equal(@"json* +packageTypes:""DotnetTool"" +frameworks:(""net6.0"")", built); - } + [Fact] + public void CombinesEveryCriterion() + { + var built = AzureSearchService.BuildSearchQuery("json", "DotnetTool", new[] { "net6.0" }); + + Assert.Equal(@"json* +packageTypes:""DotnetTool"" +frameworks:(""net6.0"")", built); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Azure.Tests/Search/AzureSearchQueryTests.cs b/tests/BaGet.Azure.Tests/Search/AzureSearchQueryTests.cs index 8ca5ed84c..745c4a613 100644 --- a/tests/BaGet.Azure.Tests/Search/AzureSearchQueryTests.cs +++ b/tests/BaGet.Azure.Tests/Search/AzureSearchQueryTests.cs @@ -1,193 +1,192 @@ using System; using Xunit; -namespace BaGet.Azure.Tests.Search +namespace BaGet.Azure.Tests.Search; + +/// +/// Covers the query construction of . The queries run with +/// the full Lucene query syntax, so a value interpolated into one must not be able to change +/// the query's meaning. +/// See https://learn.microsoft.com/azure/search/query-lucene-syntax. +/// +public class AzureSearchQueryTests { - /// - /// Covers the query construction of . The queries run with - /// the full Lucene query syntax, so a value interpolated into one must not be able to change - /// the query's meaning. - /// See https://learn.microsoft.com/azure/search/query-lucene-syntax. - /// - public class AzureSearchQueryTests + public class EscapeQueryPhrase { - public class EscapeQueryPhrase - { - [Theory] - [InlineData("Newtonsoft.Json", "\"Newtonsoft.Json\"")] - [InlineData("newtonsoft.json", "\"newtonsoft.json\"")] - [InlineData("my-package", "\"my-package\"")] - [InlineData("my_package", "\"my_package\"")] - [InlineData("Package1", "\"Package1\"")] - public void QuotesOrdinaryIds(string input, string expected) - { - Assert.Equal(expected, AzureSearchService.EscapeQueryPhrase(input)); - } + [Theory] + [InlineData("Newtonsoft.Json", "\"Newtonsoft.Json\"")] + [InlineData("newtonsoft.json", "\"newtonsoft.json\"")] + [InlineData("my-package", "\"my-package\"")] + [InlineData("my_package", "\"my_package\"")] + [InlineData("Package1", "\"Package1\"")] + public void QuotesOrdinaryIds(string input, string expected) + { + Assert.Equal(expected, AzureSearchService.EscapeQueryPhrase(input)); + } - /// - /// The characters the docs list as operators in the full Lucene syntax: - /// + - & | ! ( ) { } [ ] ^ " ~ * ? : \ /. Inside a quoted phrase they are - /// content rather than operators, so only the phrase delimiter and the escape - /// character itself need a backslash. Each case asserts the phrase still has exactly - /// one opening and one closing delimiter. - /// - [Theory] - [InlineData("+", "\"a+b\"")] - [InlineData("-", "\"a-b\"")] - [InlineData("&", "\"a&b\"")] - [InlineData("|", "\"a|b\"")] - [InlineData("!", "\"a!b\"")] - [InlineData("(", "\"a(b\"")] - [InlineData(")", "\"a)b\"")] - [InlineData("{", "\"a{b\"")] - [InlineData("}", "\"a}b\"")] - [InlineData("[", "\"a[b\"")] - [InlineData("]", "\"a]b\"")] - [InlineData("^", "\"a^b\"")] - [InlineData("~", "\"a~b\"")] - [InlineData("*", "\"a*b\"")] - [InlineData("?", "\"a?b\"")] - [InlineData(":", "\"a:b\"")] - [InlineData("/", "\"a/b\"")] - [InlineData("\"", "\"a\\\"b\"")] - [InlineData("\\", "\"a\\\\b\"")] - public void HandlesEverySignificantCharacter(string character, string expected) - { - Assert.Equal(expected, AzureSearchService.EscapeQueryPhrase("a" + character + "b")); - } + /// + /// The characters the docs list as operators in the full Lucene syntax: + /// + - & | ! ( ) { } [ ] ^ " ~ * ? : \ /. Inside a quoted phrase they are + /// content rather than operators, so only the phrase delimiter and the escape + /// character itself need a backslash. Each case asserts the phrase still has exactly + /// one opening and one closing delimiter. + /// + [Theory] + [InlineData("+", "\"a+b\"")] + [InlineData("-", "\"a-b\"")] + [InlineData("&", "\"a&b\"")] + [InlineData("|", "\"a|b\"")] + [InlineData("!", "\"a!b\"")] + [InlineData("(", "\"a(b\"")] + [InlineData(")", "\"a)b\"")] + [InlineData("{", "\"a{b\"")] + [InlineData("}", "\"a}b\"")] + [InlineData("[", "\"a[b\"")] + [InlineData("]", "\"a]b\"")] + [InlineData("^", "\"a^b\"")] + [InlineData("~", "\"a~b\"")] + [InlineData("*", "\"a*b\"")] + [InlineData("?", "\"a?b\"")] + [InlineData(":", "\"a:b\"")] + [InlineData("/", "\"a/b\"")] + [InlineData("\"", "\"a\\\"b\"")] + [InlineData("\\", "\"a\\\\b\"")] + public void HandlesEverySignificantCharacter(string character, string expected) + { + Assert.Equal(expected, AzureSearchService.EscapeQueryPhrase("a" + character + "b")); + } - [Fact] - public void EscapesTheQuotationMarkSoThePhraseCannotBeClosedEarly() - { - Assert.Equal("\"foo\\\" OR bar:baz\"", AzureSearchService.EscapeQueryPhrase("foo\" OR bar:baz")); - } + [Fact] + public void EscapesTheQuotationMarkSoThePhraseCannotBeClosedEarly() + { + Assert.Equal("\"foo\\\" OR bar:baz\"", AzureSearchService.EscapeQueryPhrase("foo\" OR bar:baz")); + } - [Fact] - public void EscapesABackslashThatWouldOtherwiseEscapeTheClosingQuotationMark() - { - // Without escaping the backslash the result would be `"foo\"`, whose closing - // delimiter is escaped away, leaving an unterminated phrase. - Assert.Equal("\"foo\\\\\"", AzureSearchService.EscapeQueryPhrase("foo\\")); - } + [Fact] + public void EscapesABackslashThatWouldOtherwiseEscapeTheClosingQuotationMark() + { + // Without escaping the backslash the result would be `"foo\"`, whose closing + // delimiter is escaped away, leaving an unterminated phrase. + Assert.Equal("\"foo\\\\\"", AzureSearchService.EscapeQueryPhrase("foo\\")); + } - [Fact] - public void EscapesAnEscapeThatIsAlreadyInTheValue() - { - // An id that already contains an escape sequence must be matched literally: the - // backslash is doubled so the parser hands `a\-b` to the analyzer. - Assert.Equal("\"a\\\\-b\"", AzureSearchService.EscapeQueryPhrase("a\\-b")); - Assert.Equal("\"a\\\\\\\\b\"", AzureSearchService.EscapeQueryPhrase("a\\\\b")); - } + [Fact] + public void EscapesAnEscapeThatIsAlreadyInTheValue() + { + // An id that already contains an escape sequence must be matched literally: the + // backslash is doubled so the parser hands `a\-b` to the analyzer. + Assert.Equal("\"a\\\\-b\"", AzureSearchService.EscapeQueryPhrase("a\\-b")); + Assert.Equal("\"a\\\\\\\\b\"", AzureSearchService.EscapeQueryPhrase("a\\\\b")); + } - [Fact] - public void KeepsWhitespaceInsideTheSinglePhrase() - { - // Whitespace cannot be escaped in the Lucene syntax; quoting is what keeps the - // value from being split into several terms (and `OR` from becoming an operator). - Assert.Equal("\"foo OR bar\"", AzureSearchService.EscapeQueryPhrase("foo OR bar")); - } + [Fact] + public void KeepsWhitespaceInsideTheSinglePhrase() + { + // Whitespace cannot be escaped in the Lucene syntax; quoting is what keeps the + // value from being split into several terms (and `OR` from becoming an operator). + Assert.Equal("\"foo OR bar\"", AzureSearchService.EscapeQueryPhrase("foo OR bar")); + } - [Fact] - public void QuotesAnEmptyValue() - { - Assert.Equal("\"\"", AzureSearchService.EscapeQueryPhrase(string.Empty)); - } + [Fact] + public void QuotesAnEmptyValue() + { + Assert.Equal("\"\"", AzureSearchService.EscapeQueryPhrase(string.Empty)); + } - [Fact] - public void ThrowsOnNull() - { - Assert.Throws(() => AzureSearchService.EscapeQueryPhrase(null)); - } + [Fact] + public void ThrowsOnNull() + { + Assert.Throws(() => AzureSearchService.EscapeQueryPhrase(null)); } + } - public class BuildDependentsQuery + public class BuildDependentsQuery + { + [Fact] + public void BuildsAFieldedPhraseQuery() { - [Fact] - public void BuildsAFieldedPhraseQuery() - { - Assert.Equal( - "dependencies:\"newtonsoft.json\"", - AzureSearchService.BuildDependentsQuery("newtonsoft.json")); - } + Assert.Equal( + "dependencies:\"newtonsoft.json\"", + AzureSearchService.BuildDependentsQuery("newtonsoft.json")); + } - [Fact] - public void LowercasesThePackageId() - { - // The field is indexed with a keyword tokenizer and a lowercase filter. - Assert.Equal( - "dependencies:\"newtonsoft.json\"", - AzureSearchService.BuildDependentsQuery("Newtonsoft.Json")); - } + [Fact] + public void LowercasesThePackageId() + { + // The field is indexed with a keyword tokenizer and a lowercase filter. + Assert.Equal( + "dependencies:\"newtonsoft.json\"", + AzureSearchService.BuildDependentsQuery("Newtonsoft.Json")); + } - [Fact] - public void DoesNotLetAnIdAddAClause() - { - var query = AzureSearchService.BuildDependentsQuery("foo OR dependencies:bar"); + [Fact] + public void DoesNotLetAnIdAddAClause() + { + var query = AzureSearchService.BuildDependentsQuery("foo OR dependencies:bar"); - Assert.Equal("dependencies:\"foo or dependencies:bar\"", query); - Assert.Equal(2, CountPhraseDelimiters(query)); - } + Assert.Equal("dependencies:\"foo or dependencies:bar\"", query); + Assert.Equal(2, CountPhraseDelimiters(query)); + } - [Fact] - public void DoesNotLetAnIdEscapeThePhrase() - { - var query = AzureSearchService.BuildDependentsQuery("foo\" OR id:/.*/ OR x:\"y"); + [Fact] + public void DoesNotLetAnIdEscapeThePhrase() + { + var query = AzureSearchService.BuildDependentsQuery("foo\" OR id:/.*/ OR x:\"y"); - Assert.Equal("dependencies:\"foo\\\" or id:/.*/ or x:\\\"y\"", query); - Assert.Equal(2, CountPhraseDelimiters(query)); - } + Assert.Equal("dependencies:\"foo\\\" or id:/.*/ or x:\\\"y\"", query); + Assert.Equal(2, CountPhraseDelimiters(query)); + } - [Fact] - public void DoesNotLetATrailingBackslashEscapeThePhrase() - { - var query = AzureSearchService.BuildDependentsQuery("foo\\"); + [Fact] + public void DoesNotLetATrailingBackslashEscapeThePhrase() + { + var query = AzureSearchService.BuildDependentsQuery("foo\\"); - Assert.Equal("dependencies:\"foo\\\\\"", query); - Assert.Equal(2, CountPhraseDelimiters(query)); - } + Assert.Equal("dependencies:\"foo\\\\\"", query); + Assert.Equal(2, CountPhraseDelimiters(query)); + } - [Fact] - public void BuildsAnEmptyPhraseForAnEmptyId() - { - Assert.Equal("dependencies:\"\"", AzureSearchService.BuildDependentsQuery(string.Empty)); - } + [Fact] + public void BuildsAnEmptyPhraseForAnEmptyId() + { + Assert.Equal("dependencies:\"\"", AzureSearchService.BuildDependentsQuery(string.Empty)); + } - [Fact] - public void ThrowsOnNull() - { - Assert.Throws(() => AzureSearchService.BuildDependentsQuery(null)); - } + [Fact] + public void ThrowsOnNull() + { + Assert.Throws(() => AzureSearchService.BuildDependentsQuery(null)); + } - /// - /// Counts the quotation marks that are not preceded by an escape, which is how the - /// query parser finds the start and the end of the phrase. Anything other than 2 means - /// the value escaped the phrase. - /// - private static int CountPhraseDelimiters(string query) - { - var delimiters = 0; - var escaped = false; + /// + /// Counts the quotation marks that are not preceded by an escape, which is how the + /// query parser finds the start and the end of the phrase. Anything other than 2 means + /// the value escaped the phrase. + /// + private static int CountPhraseDelimiters(string query) + { + var delimiters = 0; + var escaped = false; - foreach (var character in query) + foreach (var character in query) + { + if (escaped) { - if (escaped) - { - escaped = false; - continue; - } - - if (character == '\\') - { - escaped = true; - } - else if (character == '"') - { - delimiters++; - } + escaped = false; + continue; } - return delimiters; + if (character == '\\') + { + escaped = true; + } + else if (character == '"') + { + delimiters++; + } } + + return delimiters; } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Azure.Tests/Table/TableJsonTests.cs b/tests/BaGet.Azure.Tests/Table/TableJsonTests.cs index 2e7dcab09..25fd3d62a 100644 --- a/tests/BaGet.Azure.Tests/Table/TableJsonTests.cs +++ b/tests/BaGet.Azure.Tests/Table/TableJsonTests.cs @@ -3,90 +3,89 @@ using Newtonsoft.Json; using Xunit; -namespace BaGet.Azure.Tests.Table +namespace BaGet.Azure.Tests.Table; + +/// +/// The table's JSON columns moved from Newtonsoft.Json to System.Text.Json. Existing rows +/// were written by Newtonsoft, so they must still read, and new rows must look the same. +/// +public class TableJsonTests { - /// - /// The table's JSON columns moved from Newtonsoft.Json to System.Text.Json. Existing rows - /// were written by Newtonsoft, so they must still read, and new rows must look the same. - /// - public class TableJsonTests + private static readonly List Dependencies = new List { - private static readonly List Dependencies = new List - { - new DependencyModel { Id = "Newtonsoft.Json", VersionRange = "[13.0.1, )", TargetFramework = "net6.0" }, - new DependencyModel { Id = null, VersionRange = null, TargetFramework = "netstandard2.0" }, - }; + new DependencyModel { Id = "Newtonsoft.Json", VersionRange = "[13.0.1, )", TargetFramework = "net6.0" }, + new DependencyModel { Id = null, VersionRange = null, TargetFramework = "netstandard2.0" }, + }; - [Fact] - public void ReadsDependenciesNewtonsoftWrote() - { - var read = TableJson.Deserialize>(JsonConvert.SerializeObject(Dependencies)); + [Fact] + public void ReadsDependenciesNewtonsoftWrote() + { + var read = TableJson.Deserialize>(JsonConvert.SerializeObject(Dependencies)); - Assert.Equal( - Dependencies.Select(d => (d.Id, d.VersionRange, d.TargetFramework)), - read.Select(d => (d.Id, d.VersionRange, d.TargetFramework))); - } + Assert.Equal( + Dependencies.Select(d => (d.Id, d.VersionRange, d.TargetFramework)), + read.Select(d => (d.Id, d.VersionRange, d.TargetFramework))); + } - [Fact] - public void WritesWhatNewtonsoftWrote() - { - Assert.Equal(JsonConvert.SerializeObject(Dependencies), TableJson.Serialize(Dependencies)); + [Fact] + public void WritesWhatNewtonsoftWrote() + { + Assert.Equal(JsonConvert.SerializeObject(Dependencies), TableJson.Serialize(Dependencies)); - var types = new List { new PackageTypeModel { Name = "Dependency", Version = "" } }; - Assert.Equal(JsonConvert.SerializeObject(types), TableJson.Serialize(types)); - } + var types = new List { new PackageTypeModel { Name = "Dependency", Version = "" } }; + Assert.Equal(JsonConvert.SerializeObject(types), TableJson.Serialize(types)); + } - public static IEnumerable StringArrays => new[] - { - new object[] { new string[0] }, - new object[] { new[] { "Ação", "日本語", "a\"b\\c" } }, - }; + public static IEnumerable StringArrays => new[] + { + new object[] { new string[0] }, + new object[] { new[] { "Ação", "日本語", "a\"b\\c" } }, + }; - [Theory] - [MemberData(nameof(StringArrays))] - public void StringArraysMatchNewtonsoft(string[] values) - { - var newtonsoft = JsonConvert.SerializeObject(values); + [Theory] + [MemberData(nameof(StringArrays))] + public void StringArraysMatchNewtonsoft(string[] values) + { + var newtonsoft = JsonConvert.SerializeObject(values); - Assert.Equal(newtonsoft, TableJson.Serialize(values)); - Assert.Equal(values, TableJson.Deserialize(newtonsoft)); - } + Assert.Equal(newtonsoft, TableJson.Serialize(values)); + Assert.Equal(values, TableJson.Deserialize(newtonsoft)); + } - [Fact] - public void ReadsPropertyNamesInAnyCase() - { - var read = TableJson.Deserialize>("[{\"name\":\"DotnetTool\",\"VERSION\":\"1.0\"}]"); + [Fact] + public void ReadsPropertyNamesInAnyCase() + { + var read = TableJson.Deserialize>("[{\"name\":\"DotnetTool\",\"VERSION\":\"1.0\"}]"); - Assert.Equal("DotnetTool", read.Single().Name); - Assert.Equal("1.0", read.Single().Version); - } + Assert.Equal("DotnetTool", read.Single().Name); + Assert.Equal("1.0", read.Single().Version); + } - [Fact] - public void ANullDocumentReadsAsNull() - { - Assert.Null(TableJson.Deserialize("null")); - } + [Fact] + public void ANullDocumentReadsAsNull() + { + Assert.Null(TableJson.Deserialize("null")); } +} - public class TablePartitionCountTests +public class TablePartitionCountTests +{ + [Fact] + public void CountsEachRunOfAPartitionOnce() { - [Fact] - public void CountsEachRunOfAPartitionOnce() - { - Assert.Equal(3, TableSearchService.CountPartitions(new[] { "a", "a", "b", "c", "c", "c" })); - } + Assert.Equal(3, TableSearchService.CountPartitions(new[] { "a", "a", "b", "c", "c", "c" })); + } - [Fact] - public void NoRowsIsNoPartitions() - { - Assert.Equal(0, TableSearchService.CountPartitions(new string[0])); - } + [Fact] + public void NoRowsIsNoPartitions() + { + Assert.Equal(0, TableSearchService.CountPartitions(new string[0])); + } - [Fact] - public void PartitionKeysAreComparedOrdinally() - { - // Partition keys are lowercased IDs; a differently cased key is a different partition. - Assert.Equal(2, TableSearchService.CountPartitions(new[] { "a", "A" })); - } + [Fact] + public void PartitionKeysAreComparedOrdinally() + { + // Partition keys are lowercased IDs; a differently cased key is a different partition. + Assert.Equal(2, TableSearchService.CountPartitions(new[] { "a", "A" })); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Authentication/ApiKeyAuthenticationServiceTests.cs b/tests/BaGet.Core.Tests/Authentication/ApiKeyAuthenticationServiceTests.cs index 27c1f28aa..cd22fb21d 100644 --- a/tests/BaGet.Core.Tests/Authentication/ApiKeyAuthenticationServiceTests.cs +++ b/tests/BaGet.Core.Tests/Authentication/ApiKeyAuthenticationServiceTests.cs @@ -4,82 +4,81 @@ using Moq; using Xunit; -namespace BaGet.Core.Tests.Authentication +namespace BaGet.Core.Tests.Authentication; + +public class ApiKeyAuthenticationServiceTests { - public class ApiKeyAuthenticationServiceTests + private static ApiKeyAuthenticationService Target(string configuredApiKey) { - private static ApiKeyAuthenticationService Target(string configuredApiKey) - { - var options = new Mock>(); - options.Setup(o => o.Value).Returns(new BaGetOptions { ApiKey = configuredApiKey }); + var options = new Mock>(); + options.Setup(o => o.Value).Returns(new BaGetOptions { ApiKey = configuredApiKey }); - return new ApiKeyAuthenticationService(options.Object); - } + return new ApiKeyAuthenticationService(options.Object); + } - private static Task Authenticate(string configuredApiKey, string providedApiKey) - => Target(configuredApiKey).AuthenticateAsync(providedApiKey, CancellationToken.None); + private static Task Authenticate(string configuredApiKey, string providedApiKey) + => Target(configuredApiKey).AuthenticateAsync(providedApiKey, CancellationToken.None); - [Fact] - public async Task AcceptsTheConfiguredApiKey() - { - Assert.True(await Authenticate("secret", "secret")); - } + [Fact] + public async Task AcceptsTheConfiguredApiKey() + { + Assert.True(await Authenticate("secret", "secret")); + } - [Fact] - public async Task RejectsAWrongApiKey() - { - Assert.False(await Authenticate("secret", "wrong")); - } + [Fact] + public async Task RejectsAWrongApiKey() + { + Assert.False(await Authenticate("secret", "wrong")); + } - [Fact] - public async Task RejectsAMissingApiKeyWhenOneIsConfigured() - { - Assert.False(await Authenticate("secret", null)); - Assert.False(await Authenticate("secret", "")); - } + [Fact] + public async Task RejectsAMissingApiKeyWhenOneIsConfigured() + { + Assert.False(await Authenticate("secret", null)); + Assert.False(await Authenticate("secret", "")); + } - [Fact] - public async Task ComparisonIsCaseSensitive() - { - Assert.False(await Authenticate("secret", "SECRET")); - } + [Fact] + public async Task ComparisonIsCaseSensitive() + { + Assert.False(await Authenticate("secret", "SECRET")); + } - [Fact] - public async Task RejectsAnApiKeyWithSurroundingWhitespace() - { - Assert.False(await Authenticate("secret", " secret ")); - } + [Fact] + public async Task RejectsAnApiKeyWithSurroundingWhitespace() + { + Assert.False(await Authenticate("secret", " secret ")); + } - [Theory] - // Same length, differing at the first character and at the last: the comparison is - // fixed time, so neither can be told from the other by how long the answer took. - [InlineData("Xecret")] - [InlineData("secreX")] - [InlineData("XXXXXX")] - public async Task RejectsAKeyOfTheRightLengthThatIsWrong(string providedApiKey) - { - Assert.False(await Authenticate("secret", providedApiKey)); - } + [Theory] + // Same length, differing at the first character and at the last: the comparison is + // fixed time, so neither can be told from the other by how long the answer took. + [InlineData("Xecret")] + [InlineData("secreX")] + [InlineData("XXXXXX")] + public async Task RejectsAKeyOfTheRightLengthThatIsWrong(string providedApiKey) + { + Assert.False(await Authenticate("secret", providedApiKey)); + } - [Fact] - public async Task AcceptsAKeyWhoseCharactersAreNotAscii() - { - // The comparison is over the UTF-8 bytes, so a multi-byte key still matches - // itself and nothing else. - Assert.True(await Authenticate("sécret-🔑", "sécret-🔑")); - Assert.False(await Authenticate("sécret-🔑", "sécret-🔒")); - } + [Fact] + public async Task AcceptsAKeyWhoseCharactersAreNotAscii() + { + // The comparison is over the UTF-8 bytes, so a multi-byte key still matches + // itself and nothing else. + Assert.True(await Authenticate("sécret-🔑", "sécret-🔑")); + Assert.False(await Authenticate("sécret-🔑", "sécret-🔒")); + } - [Theory] - [InlineData(null)] - [InlineData("")] - public async Task AcceptsAnythingWhenNoApiKeyIsConfigured(string configuredApiKey) - { - // Documented behaviour: an unset API key leaves the server open. This is what - // makes package deletion succeed without a key on a default install. - Assert.True(await Authenticate(configuredApiKey, "anything")); - Assert.True(await Authenticate(configuredApiKey, null)); - Assert.True(await Authenticate(configuredApiKey, "")); - } + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task AcceptsAnythingWhenNoApiKeyIsConfigured(string configuredApiKey) + { + // Documented behaviour: an unset API key leaves the server open. This is what + // makes package deletion succeed without a key on a default install. + Assert.True(await Authenticate(configuredApiKey, "anything")); + Assert.True(await Authenticate(configuredApiKey, null)); + Assert.True(await Authenticate(configuredApiKey, "")); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Entities/PackageTests.cs b/tests/BaGet.Core.Tests/Entities/PackageTests.cs index 7b45b8bb0..dcd998c55 100644 --- a/tests/BaGet.Core.Tests/Entities/PackageTests.cs +++ b/tests/BaGet.Core.Tests/Entities/PackageTests.cs @@ -1,60 +1,59 @@ using System; using Xunit; -namespace BaGet.Core.Tests.Entities +namespace BaGet.Core.Tests.Entities; + +public class PackageTests { - public class PackageTests + [Fact] + public void PublishedIsUtcWhenReadBackFromTheDatabase() { - [Fact] - public void PublishedIsUtcWhenReadBackFromTheDatabase() + // The database returns a DateTime whose Kind is Unspecified. + var package = new Package { - // The database returns a DateTime whose Kind is Unspecified. - var package = new Package - { - Published = new DateTime(2020, 5, 6, 7, 8, 9, DateTimeKind.Unspecified) - }; + Published = new DateTime(2020, 5, 6, 7, 8, 9, DateTimeKind.Unspecified) + }; - Assert.Equal(DateTimeKind.Utc, package.Published.Kind); - } + Assert.Equal(DateTimeKind.Utc, package.Published.Kind); + } - [Fact] - public void PublishedKeepsItsValueWhenAlreadyUtc() - { - var published = new DateTime(2020, 5, 6, 7, 8, 9, DateTimeKind.Utc); - var package = new Package { Published = published }; + [Fact] + public void PublishedKeepsItsValueWhenAlreadyUtc() + { + var published = new DateTime(2020, 5, 6, 7, 8, 9, DateTimeKind.Utc); + var package = new Package { Published = published }; - Assert.Equal(published, package.Published); - Assert.Equal(DateTimeKind.Utc, package.Published.Kind); - } + Assert.Equal(published, package.Published); + Assert.Equal(DateTimeKind.Utc, package.Published.Kind); + } - [Fact] - public void PublishedConvertsToAnUnshiftedDateTimeOffset() + [Fact] + public void PublishedConvertsToAnUnshiftedDateTimeOffset() + { + var package = new Package { - var package = new Package - { - Published = new DateTime(2020, 5, 6, 7, 8, 9, DateTimeKind.Unspecified) - }; + Published = new DateTime(2020, 5, 6, 7, 8, 9, DateTimeKind.Unspecified) + }; - DateTimeOffset published = package.Published; + DateTimeOffset published = package.Published; - // Without an explicit UTC kind the conversion applies the server's local - // offset, moving the published timestamp reported by the NuGet protocol. - Assert.Equal(TimeSpan.Zero, published.Offset); - Assert.Equal(new DateTimeOffset(2020, 5, 6, 7, 8, 9, TimeSpan.Zero), published); - } + // Without an explicit UTC kind the conversion applies the server's local + // offset, moving the published timestamp reported by the NuGet protocol. + Assert.Equal(TimeSpan.Zero, published.Offset); + Assert.Equal(new DateTimeOffset(2020, 5, 6, 7, 8, 9, TimeSpan.Zero), published); + } - [Fact] - public void DefaultPublishedConvertsToDateTimeOffset() - { - var package = new Package(); + [Fact] + public void DefaultPublishedConvertsToDateTimeOffset() + { + var package = new Package(); - // A package with no published date - V2UpstreamClient falls back to - // DateTime.MinValue - threw on servers east of UTC, because applying a - // positive local offset to DateTime.MinValue underflows year 0. - DateTimeOffset published = package.Published; + // A package with no published date - V2UpstreamClient falls back to + // DateTime.MinValue - threw on servers east of UTC, because applying a + // positive local offset to DateTime.MinValue underflows year 0. + DateTimeOffset published = package.Published; - Assert.Equal(TimeSpan.Zero, published.Offset); - Assert.Equal(DateTimeOffset.MinValue, published); - } + Assert.Equal(TimeSpan.Zero, published.Offset); + Assert.Equal(DateTimeOffset.MinValue, published); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Entities/StringArrayComparerTests.cs b/tests/BaGet.Core.Tests/Entities/StringArrayComparerTests.cs index 098a8ed16..30358907c 100644 --- a/tests/BaGet.Core.Tests/Entities/StringArrayComparerTests.cs +++ b/tests/BaGet.Core.Tests/Entities/StringArrayComparerTests.cs @@ -1,93 +1,92 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; using Xunit; -namespace BaGet.Core.Tests.Entities +namespace BaGet.Core.Tests.Entities; + +public class StringArrayComparerTests { - public class StringArrayComparerTests + private readonly StringArrayComparer _target = StringArrayComparer.Instance; + + [Fact] + public void EqualsIsTrueForTheSameContent() + { + Assert.True(_target.Equals(new[] { "a", "b" }, new[] { "a", "b" })); + } + + [Fact] + public void EqualsIsTrueForTwoEmptyArrays() + { + Assert.True(_target.Equals(new string[0], new string[0])); + } + + [Fact] + public void EqualsIsFalseForDifferentOrder() + { + // The property is an array, so order is part of its value. + Assert.False(_target.Equals(new[] { "a", "b" }, new[] { "b", "a" })); + } + + [Fact] + public void EqualsIsFalseForDifferentLengths() + { + Assert.False(_target.Equals(new[] { "a" }, new[] { "a", "b" })); + } + + [Fact] + public void EqualsIsCaseSensitive() + { + Assert.False(_target.Equals(new[] { "a" }, new[] { "A" })); + } + + [Fact] + public void EqualsHandlesNullThroughTheUntypedComparer() { - private readonly StringArrayComparer _target = StringArrayComparer.Instance; - - [Fact] - public void EqualsIsTrueForTheSameContent() - { - Assert.True(_target.Equals(new[] { "a", "b" }, new[] { "a", "b" })); - } - - [Fact] - public void EqualsIsTrueForTwoEmptyArrays() - { - Assert.True(_target.Equals(new string[0], new string[0])); - } - - [Fact] - public void EqualsIsFalseForDifferentOrder() - { - // The property is an array, so order is part of its value. - Assert.False(_target.Equals(new[] { "a", "b" }, new[] { "b", "a" })); - } - - [Fact] - public void EqualsIsFalseForDifferentLengths() - { - Assert.False(_target.Equals(new[] { "a" }, new[] { "a", "b" })); - } - - [Fact] - public void EqualsIsCaseSensitive() - { - Assert.False(_target.Equals(new[] { "a" }, new[] { "A" })); - } - - [Fact] - public void EqualsHandlesNullThroughTheUntypedComparer() - { - // Snapshotting compares through the untyped member, which is where a null - // property value arrives. - var comparer = (ValueComparer)_target; - - Assert.True(comparer.Equals(null, null)); - Assert.False(comparer.Equals(null, new[] { "a" })); - Assert.False(comparer.Equals(new[] { "a" }, null)); - } - - [Fact] - public void EqualArraysHaveEqualHashCodes() - { - Assert.Equal( - _target.GetHashCode(new[] { "a", "b" }), - _target.GetHashCode(new[] { "a", "b" })); - } - - [Fact] - public void EmptyArraysHaveEqualHashCodes() - { - Assert.Equal( - _target.GetHashCode(new string[0]), - _target.GetHashCode(new string[0])); - } - - [Fact] - public void GetHashCodeHandlesNullThroughTheUntypedComparer() - { - var comparer = (ValueComparer)_target; - - Assert.Equal(0, comparer.GetHashCode(null)); - } - - [Fact] - public void SnapshotCopiesTheArray() - { - // A snapshot must not alias the original, otherwise mutating the property in - // place would mutate the snapshot too and the change would go undetected. - var original = new[] { "a", "b" }; - - var snapshot = _target.Snapshot(original); - - Assert.NotSame(original, snapshot); - Assert.Equal(original, snapshot); - - original[0] = "changed"; - Assert.Equal("a", snapshot[0]); - } + // Snapshotting compares through the untyped member, which is where a null + // property value arrives. + var comparer = (ValueComparer)_target; + + Assert.True(comparer.Equals(null, null)); + Assert.False(comparer.Equals(null, new[] { "a" })); + Assert.False(comparer.Equals(new[] { "a" }, null)); + } + + [Fact] + public void EqualArraysHaveEqualHashCodes() + { + Assert.Equal( + _target.GetHashCode(new[] { "a", "b" }), + _target.GetHashCode(new[] { "a", "b" })); + } + + [Fact] + public void EmptyArraysHaveEqualHashCodes() + { + Assert.Equal( + _target.GetHashCode(new string[0]), + _target.GetHashCode(new string[0])); + } + + [Fact] + public void GetHashCodeHandlesNullThroughTheUntypedComparer() + { + var comparer = (ValueComparer)_target; + + Assert.Equal(0, comparer.GetHashCode(null)); + } + + [Fact] + public void SnapshotCopiesTheArray() + { + // A snapshot must not alias the original, otherwise mutating the property in + // place would mutate the snapshot too and the change would go undetected. + var original = new[] { "a", "b" }; + + var snapshot = _target.Snapshot(original); + + Assert.NotSame(original, snapshot); + Assert.Equal(original, snapshot); + + original[0] = "changed"; + Assert.Equal("a", snapshot[0]); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Entities/ValueConverterTests.cs b/tests/BaGet.Core.Tests/Entities/ValueConverterTests.cs index 6faccb72a..cec79d486 100644 --- a/tests/BaGet.Core.Tests/Entities/ValueConverterTests.cs +++ b/tests/BaGet.Core.Tests/Entities/ValueConverterTests.cs @@ -2,91 +2,90 @@ using System; using Xunit; -namespace BaGet.Core.Tests.Entities +namespace BaGet.Core.Tests.Entities; + +public class StringArrayToJsonConverterTests { - public class StringArrayToJsonConverterTests + private readonly StringArrayToJsonConverter _target = StringArrayToJsonConverter.Instance; + + private string ToStore(string[] value) => (string)_target.ConvertToProvider(value); + + private string[] FromStore(string value) => (string[])_target.ConvertFromProvider(value); + + public static IEnumerable Arrays => new[] + { + new object[] { new string[0] }, + new object[] { new[] { "one" } }, + new object[] { new[] { "one", "two", "three" } }, + new object[] { new[] { "" } }, + new object[] { new[] { "with \"quotes\"", "with,comma", "with\\backslash" } }, + new object[] { new[] { "ünïcödé", "中文" } }, + }; + + [Theory] + [MemberData(nameof(Arrays))] + public void RoundTripsAnArray(string[] value) + { + Assert.Equal(value, FromStore(ToStore(value))); + } + + [Fact] + public void ReadsAnEmptyColumnAsAnEmptyArray() { - private readonly StringArrayToJsonConverter _target = StringArrayToJsonConverter.Instance; - - private string ToStore(string[] value) => (string)_target.ConvertToProvider(value); - - private string[] FromStore(string value) => (string[])_target.ConvertFromProvider(value); - - public static IEnumerable Arrays => new[] - { - new object[] { new string[0] }, - new object[] { new[] { "one" } }, - new object[] { new[] { "one", "two", "three" } }, - new object[] { new[] { "" } }, - new object[] { new[] { "with \"quotes\"", "with,comma", "with\\backslash" } }, - new object[] { new[] { "ünïcödé", "中文" } }, - }; - - [Theory] - [MemberData(nameof(Arrays))] - public void RoundTripsAnArray(string[] value) - { - Assert.Equal(value, FromStore(ToStore(value))); - } - - [Fact] - public void ReadsAnEmptyColumnAsAnEmptyArray() - { - // Rows written before the column existed hold an empty string. - Assert.Equal(new string[0], FromStore("")); - } - - [Fact] - public void PreservesOrder() - { - var value = new[] { "z", "a", "m" }; - - Assert.Equal(value, FromStore(ToStore(value))); - } - - [Fact] - public void PreservesDuplicates() - { - var value = new[] { "a", "a", "b" }; - - Assert.Equal(value, FromStore(ToStore(value))); - } + // Rows written before the column existed hold an empty string. + Assert.Equal(new string[0], FromStore("")); } - public class UriToStringConverterTests + [Fact] + public void PreservesOrder() { - private readonly UriToStringConverter _target = UriToStringConverter.Instance; - - private string ToStore(Uri value) => (string)_target.ConvertToProvider(value); - - private Uri FromStore(string value) => (Uri)_target.ConvertFromProvider(value); - - [Theory] - [InlineData("https://example.test/package")] - [InlineData("http://example.test/")] - [InlineData("https://example.test/path/to/thing?query=1&other=2")] - [InlineData("https://example.test/path#fragment")] - public void RoundTripsAnAbsoluteUri(string value) - { - var uri = new Uri(value); - - Assert.Equal(uri, FromStore(ToStore(uri))); - } - - [Fact] - public void RoundTripsAUriWithAnEscapedSpace() - { - var uri = new Uri("https://example.test/a%20b"); - - Assert.Equal(uri, FromStore(ToStore(uri))); - } - - [Fact] - public void StoresTheAbsoluteUri() - { - Assert.Equal( - "https://example.test/package", - ToStore(new Uri("https://example.test/package"))); - } + var value = new[] { "z", "a", "m" }; + + Assert.Equal(value, FromStore(ToStore(value))); + } + + [Fact] + public void PreservesDuplicates() + { + var value = new[] { "a", "a", "b" }; + + Assert.Equal(value, FromStore(ToStore(value))); } } + +public class UriToStringConverterTests +{ + private readonly UriToStringConverter _target = UriToStringConverter.Instance; + + private string ToStore(Uri value) => (string)_target.ConvertToProvider(value); + + private Uri FromStore(string value) => (Uri)_target.ConvertFromProvider(value); + + [Theory] + [InlineData("https://example.test/package")] + [InlineData("http://example.test/")] + [InlineData("https://example.test/path/to/thing?query=1&other=2")] + [InlineData("https://example.test/path#fragment")] + public void RoundTripsAnAbsoluteUri(string value) + { + var uri = new Uri(value); + + Assert.Equal(uri, FromStore(ToStore(uri))); + } + + [Fact] + public void RoundTripsAUriWithAnEscapedSpace() + { + var uri = new Uri("https://example.test/a%20b"); + + Assert.Equal(uri, FromStore(ToStore(uri))); + } + + [Fact] + public void StoresTheAbsoluteUri() + { + Assert.Equal( + "https://example.test/package", + ToStore(new Uri("https://example.test/package"))); + } +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Extensions/PackageArchiveReaderExtensionsTests.cs b/tests/BaGet.Core.Tests/Extensions/PackageArchiveReaderExtensionsTests.cs index 053d2c860..0b8eda652 100644 --- a/tests/BaGet.Core.Tests/Extensions/PackageArchiveReaderExtensionsTests.cs +++ b/tests/BaGet.Core.Tests/Extensions/PackageArchiveReaderExtensionsTests.cs @@ -4,307 +4,307 @@ using NuGet.Packaging; using Xunit; -namespace BaGet.Core.Tests.Extensions +namespace BaGet.Core.Tests.Extensions; + +public class PackageArchiveReaderExtensionsTests { - public class PackageArchiveReaderExtensionsTests + private static Package Read(string extraMetadata = "", IDictionary files = null) { - private static Package Read(string extraMetadata = "", IDictionary files = null) - { - using var stream = TestPackage.CreateMinimal(extraMetadata, files: files); - using var reader = new PackageArchiveReader(stream); + using var stream = TestPackage.CreateMinimal(extraMetadata, files: files); + using var reader = new PackageArchiveReader(stream); - return reader.GetPackageMetadata(); - } + return reader.GetPackageMetadata(); + } - public class Identity + public class Identity + { + [Fact] + public void ReadsTheIdAndVersion() { - [Fact] - public void ReadsTheIdAndVersion() - { - using var stream = TestPackage.CreateMinimal(id: "My.Package", version: "2.3.4"); - using var reader = new PackageArchiveReader(stream); + using var stream = TestPackage.CreateMinimal(id: "My.Package", version: "2.3.4"); + using var reader = new PackageArchiveReader(stream); - var package = reader.GetPackageMetadata(); + var package = reader.GetPackageMetadata(); - Assert.Equal("My.Package", package.Id); - Assert.Equal("2.3.4", package.Version.ToNormalizedString()); - } + Assert.Equal("My.Package", package.Id); + Assert.Equal("2.3.4", package.Version.ToNormalizedString()); + } - [Fact] - public void MarksAPrereleaseVersion() - { - using var stream = TestPackage.CreateMinimal(version: "1.0.0-beta1"); - using var reader = new PackageArchiveReader(stream); + [Fact] + public void MarksAPrereleaseVersion() + { + using var stream = TestPackage.CreateMinimal(version: "1.0.0-beta1"); + using var reader = new PackageArchiveReader(stream); - Assert.True(reader.GetPackageMetadata().IsPrerelease); - } + Assert.True(reader.GetPackageMetadata().IsPrerelease); + } - [Fact] - public void AReleaseVersionIsNotPrerelease() - { - Assert.False(Read().IsPrerelease); - } + [Fact] + public void AReleaseVersionIsNotPrerelease() + { + Assert.False(Read().IsPrerelease); + } - [Fact] - public void ListsThePackageByDefault() - { - Assert.True(Read().Listed); - } + [Fact] + public void ListsThePackageByDefault() + { + Assert.True(Read().Listed); } + } - public class Authors + public class Authors + { + [Fact] + public void SplitsOnCommas() { - [Fact] - public void SplitsOnCommas() - { - using var stream = TestPackage.CreateMinimal(authors: "First,Second"); - using var reader = new PackageArchiveReader(stream); + using var stream = TestPackage.CreateMinimal(authors: "First,Second"); + using var reader = new PackageArchiveReader(stream); - Assert.Equal(new[] { "First", "Second" }, reader.GetPackageMetadata().Authors); - } + Assert.Equal(new[] { "First", "Second" }, reader.GetPackageMetadata().Authors); + } - [Fact] - public void SplitsOnSemicolons() - { - using var stream = TestPackage.CreateMinimal(authors: "First;Second"); - using var reader = new PackageArchiveReader(stream); + [Fact] + public void SplitsOnSemicolons() + { + using var stream = TestPackage.CreateMinimal(authors: "First;Second"); + using var reader = new PackageArchiveReader(stream); - Assert.Equal(new[] { "First", "Second" }, reader.GetPackageMetadata().Authors); - } + Assert.Equal(new[] { "First", "Second" }, reader.GetPackageMetadata().Authors); + } - [Fact] - public void KeepsSpacesInsideAName() - { - // An author's name is not space delimited, unlike tags. - using var stream = TestPackage.CreateMinimal(authors: "Ada Lovelace,Alan Turing"); - using var reader = new PackageArchiveReader(stream); + [Fact] + public void KeepsSpacesInsideAName() + { + // An author's name is not space delimited, unlike tags. + using var stream = TestPackage.CreateMinimal(authors: "Ada Lovelace,Alan Turing"); + using var reader = new PackageArchiveReader(stream); - Assert.Equal( - new[] { "Ada Lovelace", "Alan Turing" }, - reader.GetPackageMetadata().Authors); - } + Assert.Equal( + new[] { "Ada Lovelace", "Alan Turing" }, + reader.GetPackageMetadata().Authors); + } - [Fact] - public void DropsEmptyEntries() - { - using var stream = TestPackage.CreateMinimal(authors: "First,,Second,"); - using var reader = new PackageArchiveReader(stream); + [Fact] + public void DropsEmptyEntries() + { + using var stream = TestPackage.CreateMinimal(authors: "First,,Second,"); + using var reader = new PackageArchiveReader(stream); - Assert.Equal(new[] { "First", "Second" }, reader.GetPackageMetadata().Authors); - } + Assert.Equal(new[] { "First", "Second" }, reader.GetPackageMetadata().Authors); } + } - public class Tags + public class Tags + { + [Fact] + public void AreEmptyWhenAbsent() { - [Fact] - public void AreEmptyWhenAbsent() - { - Assert.Empty(Read().Tags); - } + Assert.Empty(Read().Tags); + } - [Fact] - public void SplitOnSpaces() - { - Assert.Equal( - new[] { "one", "two", "three" }, - Read(" one two three").Tags); - } + [Fact] + public void SplitOnSpaces() + { + Assert.Equal( + new[] { "one", "two", "three" }, + Read(" one two three").Tags); + } - [Fact] - public void SplitOnCommasAndSemicolons() - { - Assert.Equal( - new[] { "one", "two", "three" }, - Read(" one,two;three").Tags); - } + [Fact] + public void SplitOnCommasAndSemicolons() + { + Assert.Equal( + new[] { "one", "two", "three" }, + Read(" one,two;three").Tags); + } - [Fact] - public void DropEmptyEntries() - { - Assert.Equal( - new[] { "one", "two" }, - Read(" one two ").Tags); - } + [Fact] + public void DropEmptyEntries() + { + Assert.Equal( + new[] { "one", "two" }, + Read(" one two ").Tags); } + } - public class OptionalStrings + public class OptionalStrings + { + [Fact] + public void AreEmptyRatherThanNullWhenAbsent() { - [Fact] - public void AreEmptyRatherThanNullWhenAbsent() - { - var package = Read(); + var package = Read(); - Assert.Equal(string.Empty, package.Language); - Assert.Equal(string.Empty, package.ReleaseNotes); - Assert.Equal(string.Empty, package.MinClientVersion); - } + Assert.Equal(string.Empty, package.Language); + Assert.Equal(string.Empty, package.ReleaseNotes); + Assert.Equal(string.Empty, package.MinClientVersion); + } - [Fact] - public void AreReadWhenPresent() - { - var package = Read( -@" en-GB + [Fact] + public void AreReadWhenPresent() + { + var package = Read( + @" en-GB Notes here A summary A title"); - Assert.Equal("en-GB", package.Language); - Assert.Equal("Notes here", package.ReleaseNotes); - Assert.Equal("A summary", package.Summary); - Assert.Equal("A title", package.Title); - } + Assert.Equal("en-GB", package.Language); + Assert.Equal("Notes here", package.ReleaseNotes); + Assert.Equal("A summary", package.Summary); + Assert.Equal("A title", package.Title); + } - [Fact] - public void RequireLicenseAcceptanceDefaultsToFalse() - { - Assert.False(Read().RequireLicenseAcceptance); - } + [Fact] + public void RequireLicenseAcceptanceDefaultsToFalse() + { + Assert.False(Read().RequireLicenseAcceptance); + } - [Fact] - public void RequireLicenseAcceptanceIsRead() - { - Assert.True(Read(" true") - .RequireLicenseAcceptance); - } + [Fact] + public void RequireLicenseAcceptanceIsRead() + { + Assert.True(Read(" true") + .RequireLicenseAcceptance); } + } - public class Urls + public class Urls + { + [Fact] + public void AreNullWhenAbsent() { - [Fact] - public void AreNullWhenAbsent() - { - var package = Read(); + var package = Read(); - Assert.Null(package.IconUrl); - Assert.Null(package.LicenseUrl); - Assert.Null(package.ProjectUrl); - } + Assert.Null(package.IconUrl); + Assert.Null(package.LicenseUrl); + Assert.Null(package.ProjectUrl); + } - [Fact] - public void AreReadWhenAbsolute() - { - var package = Read( -@" https://example.test/icon.png + [Fact] + public void AreReadWhenAbsolute() + { + var package = Read( + @" https://example.test/icon.png https://example.test/licence https://example.test/"); - Assert.Equal("https://example.test/icon.png", package.IconUrl.AbsoluteUri); - Assert.Equal("https://example.test/licence", package.LicenseUrl.AbsoluteUri); - Assert.Equal("https://example.test/", package.ProjectUrl.AbsoluteUri); - } + Assert.Equal("https://example.test/icon.png", package.IconUrl.AbsoluteUri); + Assert.Equal("https://example.test/licence", package.LicenseUrl.AbsoluteUri); + Assert.Equal("https://example.test/", package.ProjectUrl.AbsoluteUri); + } - [Fact] - public void ARelativeIconUrlIsIgnoredRatherThanFatal() - { - // Older packages carry a relative iconUrl. It cannot be served, but it must - // not stop the package being read: the alternative is that pushing such a - // package fails with an unhandled UriFormatException. - var package = Read(" images/icon.png"); + [Fact] + public void ARelativeIconUrlIsIgnoredRatherThanFatal() + { + // Older packages carry a relative iconUrl. It cannot be served, but it must + // not stop the package being read: the alternative is that pushing such a + // package fails with an unhandled UriFormatException. + var package = Read(" images/icon.png"); - Assert.Null(package.IconUrl); - } + Assert.Null(package.IconUrl); + } - [Fact] - public void AMalformedProjectUrlIsIgnoredRatherThanFatal() - { - var package = Read(" not a url at all"); + [Fact] + public void AMalformedProjectUrlIsIgnoredRatherThanFatal() + { + var package = Read(" not a url at all"); - Assert.Null(package.ProjectUrl); - } + Assert.Null(package.ProjectUrl); } + } - public class Repository + public class Repository + { + [Fact] + public void IsNullWhenAbsent() { - [Fact] - public void IsNullWhenAbsent() - { - var package = Read(); + var package = Read(); - Assert.Null(package.RepositoryUrl); - Assert.Null(package.RepositoryType); - } + Assert.Null(package.RepositoryUrl); + Assert.Null(package.RepositoryType); + } - [Fact] - public void IsReadForAnHttpsUrl() - { - var package = Read( - @" "); + [Fact] + public void IsReadForAnHttpsUrl() + { + var package = Read( + @" "); - Assert.Equal("https://example.test/repo", package.RepositoryUrl.AbsoluteUri); - Assert.Equal("git", package.RepositoryType); - } + Assert.Equal("https://example.test/repo", package.RepositoryUrl.AbsoluteUri); + Assert.Equal("git", package.RepositoryType); + } - [Fact] - public void IsRejectedForAPlainHttpUrl() - { - var package = Read( - @" "); + [Fact] + public void IsRejectedForAPlainHttpUrl() + { + var package = Read( + @" "); - Assert.Null(package.RepositoryUrl); - Assert.Null(package.RepositoryType); - } + Assert.Null(package.RepositoryUrl); + Assert.Null(package.RepositoryType); + } - [Fact] - public void IsRejectedForANonAbsoluteUrl() - { - var package = Read(@" "); + [Fact] + public void IsRejectedForANonAbsoluteUrl() + { + var package = Read(@" "); - Assert.Null(package.RepositoryUrl); - } + Assert.Null(package.RepositoryUrl); + } - [Fact] - public void AMissingTypeIsNotFatal() - { - // The type attribute is optional; only the URL is required. - var package = Read(@" "); + [Fact] + public void AMissingTypeIsNotFatal() + { + // The type attribute is optional; only the URL is required. + var package = Read(@" "); - Assert.Equal("https://example.test/repo", package.RepositoryUrl.AbsoluteUri); - } + Assert.Equal("https://example.test/repo", package.RepositoryUrl.AbsoluteUri); } + } - public class Dependencies + public class Dependencies + { + [Fact] + public void AreEmptyWhenAbsent() { - [Fact] - public void AreEmptyWhenAbsent() - { - Assert.Empty(Read().Dependencies); - } + Assert.Empty(Read().Dependencies); + } - [Fact] - public void AreReadWithTheirRangeAndFramework() - { - var package = Read( -@" + [Fact] + public void AreReadWithTheirRangeAndFramework() + { + var package = Read( + @" "); - var dependency = Assert.Single(package.Dependencies); - Assert.Equal("Other.Package", dependency.Id); - Assert.Equal("netstandard2.0", dependency.TargetFramework); - Assert.Contains("1.2.3", dependency.VersionRange); - } + var dependency = Assert.Single(package.Dependencies); + Assert.Equal("Other.Package", dependency.Id); + Assert.Equal("netstandard2.0", dependency.TargetFramework); + Assert.Contains("1.2.3", dependency.VersionRange); + } - [Fact] - public void AnEmptyGroupIsRecordedAsAFrameworkWithNoPackage() - { - var package = Read( -@" + [Fact] + public void AnEmptyGroupIsRecordedAsAFrameworkWithNoPackage() + { + var package = Read( + @" "); - var dependency = Assert.Single(package.Dependencies); - Assert.Null(dependency.Id); - Assert.Null(dependency.VersionRange); - Assert.Equal("netstandard2.0", dependency.TargetFramework); - } + var dependency = Assert.Single(package.Dependencies); + Assert.Null(dependency.Id); + Assert.Null(dependency.VersionRange); + Assert.Equal("netstandard2.0", dependency.TargetFramework); + } - [Fact] - public void EveryGroupIsRead() - { - var package = Read( -@" + [Fact] + public void EveryGroupIsRead() + { + var package = Read( + @" @@ -313,111 +313,110 @@ public void EveryGroupIsRead() "); - Assert.Equal(new[] { "A", "B" }, package.Dependencies.Select(d => d.Id)); - } + Assert.Equal(new[] { "A", "B" }, package.Dependencies.Select(d => d.Id)); } + } - public class PackageTypesAndFrameworks + public class PackageTypesAndFrameworks + { + [Fact] + public void DefaultsToTheDependencyPackageType() { - [Fact] - public void DefaultsToTheDependencyPackageType() - { - var packageType = Assert.Single(Read().PackageTypes); + var packageType = Assert.Single(Read().PackageTypes); - Assert.Equal("Dependency", packageType.Name); - } + Assert.Equal("Dependency", packageType.Name); + } - [Fact] - public void ReadsADeclaredPackageType() - { - var package = Read( -@" + [Fact] + public void ReadsADeclaredPackageType() + { + var package = Read( + @" "); - Assert.Equal("DotnetTool", Assert.Single(package.PackageTypes).Name); - } + Assert.Equal("DotnetTool", Assert.Single(package.PackageTypes).Name); + } - [Fact] - public void DefaultsToTheAnyFrameworkWhenThereAreNoLibraries() - { - var targetFramework = Assert.Single(Read().TargetFrameworks); + [Fact] + public void DefaultsToTheAnyFrameworkWhenThereAreNoLibraries() + { + var targetFramework = Assert.Single(Read().TargetFrameworks); - Assert.Equal("any", targetFramework.Moniker); - } + Assert.Equal("any", targetFramework.Moniker); + } - [Fact] - public void ReadsTheFrameworkOfALibraryFolder() + [Fact] + public void ReadsTheFrameworkOfALibraryFolder() + { + var package = Read(files: new Dictionary { - var package = Read(files: new Dictionary - { - { "lib/netstandard2.0/Library.dll", "not a real assembly" }, - }); + { "lib/netstandard2.0/Library.dll", "not a real assembly" }, + }); - Assert.Equal("netstandard2.0", Assert.Single(package.TargetFrameworks).Moniker); - } + Assert.Equal("netstandard2.0", Assert.Single(package.TargetFrameworks).Moniker); } + } - public class SemVerLevel + public class SemVerLevel + { + [Fact] + public void IsUnknownForASemVer1Version() { - [Fact] - public void IsUnknownForASemVer1Version() - { - using var stream = TestPackage.CreateMinimal(version: "1.0.0"); - using var reader = new PackageArchiveReader(stream); + using var stream = TestPackage.CreateMinimal(version: "1.0.0"); + using var reader = new PackageArchiveReader(stream); - Assert.Equal(Core.SemVerLevel.Unknown, reader.GetPackageMetadata().SemVerLevel); - } + Assert.Equal(Core.SemVerLevel.Unknown, reader.GetPackageMetadata().SemVerLevel); + } - [Fact] - public void IsSemVer2ForASemVer2Version() - { - using var stream = TestPackage.CreateMinimal(version: "1.0.0-beta.1"); - using var reader = new PackageArchiveReader(stream); + [Fact] + public void IsSemVer2ForASemVer2Version() + { + using var stream = TestPackage.CreateMinimal(version: "1.0.0-beta.1"); + using var reader = new PackageArchiveReader(stream); - Assert.Equal(Core.SemVerLevel.SemVer2, reader.GetPackageMetadata().SemVerLevel); - } + Assert.Equal(Core.SemVerLevel.SemVer2, reader.GetPackageMetadata().SemVerLevel); + } - [Fact] - public void IsSemVer2WhenADependencyRangeIsSemVer2() - { - var package = Read( -@" + [Fact] + public void IsSemVer2WhenADependencyRangeIsSemVer2() + { + var package = Read( + @" "); - Assert.Equal(Core.SemVerLevel.SemVer2, package.SemVerLevel); - } + Assert.Equal(Core.SemVerLevel.SemVer2, package.SemVerLevel); } + } - public class ReadmeAndIcon + public class ReadmeAndIcon + { + [Fact] + public void AreAbsentFromAMinimalPackage() { - [Fact] - public void AreAbsentFromAMinimalPackage() - { - var package = Read(); + var package = Read(); - Assert.False(package.HasReadme); - Assert.False(package.HasEmbeddedIcon); - } + Assert.False(package.HasReadme); + Assert.False(package.HasEmbeddedIcon); + } - [Fact] - public void AreDetectedWhenDeclared() - { - var package = Read( -@" README.md + [Fact] + public void AreDetectedWhenDeclared() + { + var package = Read( + @" README.md icon.png", - new Dictionary - { - { "README.md", "# Readme" }, - { "icon.png", "not a real png" }, - }); + new Dictionary + { + { "README.md", "# Readme" }, + { "icon.png", "not a real png" }, + }); - Assert.True(package.HasReadme); - Assert.True(package.HasEmbeddedIcon); - } + Assert.True(package.HasReadme); + Assert.True(package.HasEmbeddedIcon); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Extensions/StreamExtensionsTests.cs b/tests/BaGet.Core.Tests/Extensions/StreamExtensionsTests.cs index ec01bd3e2..cf9dda839 100644 --- a/tests/BaGet.Core.Tests/Extensions/StreamExtensionsTests.cs +++ b/tests/BaGet.Core.Tests/Extensions/StreamExtensionsTests.cs @@ -3,146 +3,145 @@ using System.Threading.Tasks; using Xunit; -namespace BaGet.Core.Tests.Extensions +namespace BaGet.Core.Tests.Extensions; + +public class StreamExtensionsTests { - public class StreamExtensionsTests - { - private static MemoryStream Stream(string content) - => new MemoryStream(Encoding.UTF8.GetBytes(content)); + private static MemoryStream Stream(string content) + => new MemoryStream(Encoding.UTF8.GetBytes(content)); - public class Matches + public class Matches + { + [Fact] + public void IsTrueForIdenticalContent() { - [Fact] - public void IsTrueForIdenticalContent() - { - using var a = Stream("hello world"); - using var b = Stream("hello world"); + using var a = Stream("hello world"); + using var b = Stream("hello world"); - Assert.True(a.Matches(b)); - } + Assert.True(a.Matches(b)); + } - [Fact] - public void IsFalseForDifferentContent() - { - using var a = Stream("hello world"); - using var b = Stream("hello mars!"); + [Fact] + public void IsFalseForDifferentContent() + { + using var a = Stream("hello world"); + using var b = Stream("hello mars!"); - Assert.False(a.Matches(b)); - } + Assert.False(a.Matches(b)); + } - [Fact] - public void IsFalseForDifferentLengths() - { - using var a = Stream("hello"); - using var b = Stream("hello world"); + [Fact] + public void IsFalseForDifferentLengths() + { + using var a = Stream("hello"); + using var b = Stream("hello world"); - Assert.False(a.Matches(b)); - } + Assert.False(a.Matches(b)); + } - [Fact] - public void IsTrueForTwoEmptyStreams() - { - using var a = Stream(""); - using var b = Stream(""); + [Fact] + public void IsTrueForTwoEmptyStreams() + { + using var a = Stream(""); + using var b = Stream(""); - Assert.True(a.Matches(b)); - } + Assert.True(a.Matches(b)); + } - [Fact] - public void IsFalseWhenOnlyOneStreamIsEmpty() - { - using var a = Stream(""); - using var b = Stream("content"); + [Fact] + public void IsFalseWhenOnlyOneStreamIsEmpty() + { + using var a = Stream(""); + using var b = Stream("content"); - Assert.False(a.Matches(b)); - } + Assert.False(a.Matches(b)); + } - [Fact] - public void ComparesFromTheCurrentPosition() - { - // FileStorageService.PutAsync rewinds the incoming stream before comparing, - // because the hash is computed from wherever the stream currently sits. - using var a = Stream("XXXhello"); - using var b = Stream("hello"); + [Fact] + public void ComparesFromTheCurrentPosition() + { + // FileStorageService.PutAsync rewinds the incoming stream before comparing, + // because the hash is computed from wherever the stream currently sits. + using var a = Stream("XXXhello"); + using var b = Stream("hello"); - a.Position = 3; + a.Position = 3; - Assert.True(a.Matches(b)); - } + Assert.True(a.Matches(b)); + } - [Fact] - public void ConsumesBothStreams() - { - // Documents why a caller cannot compare twice without rewinding. - using var a = Stream("hello"); - using var b = Stream("hello"); + [Fact] + public void ConsumesBothStreams() + { + // Documents why a caller cannot compare twice without rewinding. + using var a = Stream("hello"); + using var b = Stream("hello"); - Assert.True(a.Matches(b)); + Assert.True(a.Matches(b)); - Assert.Equal(a.Length, a.Position); - Assert.Equal(b.Length, b.Position); - } + Assert.Equal(a.Length, a.Position); + Assert.Equal(b.Length, b.Position); } + } - public class AsTemporaryFileStreamAsync + public class AsTemporaryFileStreamAsync + { + [Fact] + public async Task CopiesTheContent() { - [Fact] - public async Task CopiesTheContent() - { - using var original = Stream("the content"); + using var original = Stream("the content"); - using var result = await original.AsTemporaryFileStreamAsync(); + using var result = await original.AsTemporaryFileStreamAsync(); - using var reader = new StreamReader(result, Encoding.UTF8, false, 1024, leaveOpen: true); - Assert.Equal("the content", reader.ReadToEnd()); - } - - [Fact] - public async Task ResetsThePositionToTheBeginning() - { - using var original = Stream("the content"); + using var reader = new StreamReader(result, Encoding.UTF8, false, 1024, leaveOpen: true); + Assert.Equal("the content", reader.ReadToEnd()); + } - using var result = await original.AsTemporaryFileStreamAsync(); + [Fact] + public async Task ResetsThePositionToTheBeginning() + { + using var original = Stream("the content"); - Assert.Equal(0, result.Position); - } + using var result = await original.AsTemporaryFileStreamAsync(); - [Fact] - public async Task CopiesFromTheCurrentPosition() - { - using var original = Stream("SKIPcontent"); - original.Position = 4; + Assert.Equal(0, result.Position); + } - using var result = await original.AsTemporaryFileStreamAsync(); + [Fact] + public async Task CopiesFromTheCurrentPosition() + { + using var original = Stream("SKIPcontent"); + original.Position = 4; - using var reader = new StreamReader(result, Encoding.UTF8, false, 1024, leaveOpen: true); - Assert.Equal("content", reader.ReadToEnd()); - } + using var result = await original.AsTemporaryFileStreamAsync(); - [Fact] - public async Task HandlesAnEmptyStream() - { - using var original = Stream(""); + using var reader = new StreamReader(result, Encoding.UTF8, false, 1024, leaveOpen: true); + Assert.Equal("content", reader.ReadToEnd()); + } - using var result = await original.AsTemporaryFileStreamAsync(); + [Fact] + public async Task HandlesAnEmptyStream() + { + using var original = Stream(""); - Assert.Equal(0, result.Length); - } + using var result = await original.AsTemporaryFileStreamAsync(); - [Fact] - public async Task DeletesTheFileWhenDisposed() - { - string path; + Assert.Equal(0, result.Length); + } - using (var original = Stream("the content")) - using (var result = await original.AsTemporaryFileStreamAsync()) - { - path = result.Name; - Assert.True(File.Exists(path)); - } + [Fact] + public async Task DeletesTheFileWhenDisposed() + { + string path; - Assert.False(File.Exists(path)); + using (var original = Stream("the content")) + using (var result = await original.AsTemporaryFileStreamAsync()) + { + path = result.Name; + Assert.True(File.Exists(path)); } + + Assert.False(File.Exists(path)); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Indexing/FrameworkCompatibilityServiceTests.cs b/tests/BaGet.Core.Tests/Indexing/FrameworkCompatibilityServiceTests.cs index b645bc752..6000b8550 100644 --- a/tests/BaGet.Core.Tests/Indexing/FrameworkCompatibilityServiceTests.cs +++ b/tests/BaGet.Core.Tests/Indexing/FrameworkCompatibilityServiceTests.cs @@ -1,104 +1,103 @@ using Xunit; -namespace BaGet.Core.Tests.Indexing +namespace BaGet.Core.Tests.Indexing; + +public class FrameworkCompatibilityServiceTests { - public class FrameworkCompatibilityServiceTests + private readonly FrameworkCompatibilityService _target = new FrameworkCompatibilityService(); + + [Fact] + public void AlwaysIncludesTheAnyFramework() + { + // A package whose assets are under "any" applies to every target framework. + Assert.Contains("any", _target.FindAllCompatibleFrameworks("net6.0")); + } + + [Fact] + public void IncludesTheTargetFrameworkItself() + { + Assert.Contains("net6.0", _target.FindAllCompatibleFrameworks("net6.0")); + } + + [Theory] + [InlineData("net6.0", "net5.0")] + [InlineData("net5.0", "netcoreapp3.1")] + [InlineData("netstandard2.1", "netstandard2.0")] + [InlineData("netstandard2.0", "netstandard1.0")] + public void IncludesAnEarlierVersionOfTheSameFramework(string target, string earlier) + { + Assert.Contains(earlier, _target.FindAllCompatibleFrameworks(target)); + } + + [Theory] + [InlineData("net5.0", "net6.0")] + [InlineData("netstandard2.0", "netstandard2.1")] + public void ExcludesALaterVersionOfTheSameFramework(string target, string later) + { + Assert.DoesNotContain(later, _target.FindAllCompatibleFrameworks(target)); + } + + [Fact] + public void ANetCoreAppTargetIsCompatibleWithNetStandard() + { + var result = _target.FindAllCompatibleFrameworks("netcoreapp3.1"); + + Assert.Contains("netstandard2.0", result); + } + + [Fact] + public void ANetFrameworkTargetIsCompatibleWithNetStandard() { - private readonly FrameworkCompatibilityService _target = new FrameworkCompatibilityService(); - - [Fact] - public void AlwaysIncludesTheAnyFramework() - { - // A package whose assets are under "any" applies to every target framework. - Assert.Contains("any", _target.FindAllCompatibleFrameworks("net6.0")); - } - - [Fact] - public void IncludesTheTargetFrameworkItself() - { - Assert.Contains("net6.0", _target.FindAllCompatibleFrameworks("net6.0")); - } - - [Theory] - [InlineData("net6.0", "net5.0")] - [InlineData("net5.0", "netcoreapp3.1")] - [InlineData("netstandard2.1", "netstandard2.0")] - [InlineData("netstandard2.0", "netstandard1.0")] - public void IncludesAnEarlierVersionOfTheSameFramework(string target, string earlier) - { - Assert.Contains(earlier, _target.FindAllCompatibleFrameworks(target)); - } - - [Theory] - [InlineData("net5.0", "net6.0")] - [InlineData("netstandard2.0", "netstandard2.1")] - public void ExcludesALaterVersionOfTheSameFramework(string target, string later) - { - Assert.DoesNotContain(later, _target.FindAllCompatibleFrameworks(target)); - } - - [Fact] - public void ANetCoreAppTargetIsCompatibleWithNetStandard() - { - var result = _target.FindAllCompatibleFrameworks("netcoreapp3.1"); - - Assert.Contains("netstandard2.0", result); - } - - [Fact] - public void ANetFrameworkTargetIsCompatibleWithNetStandard() - { - var result = _target.FindAllCompatibleFrameworks("net472"); - - Assert.Contains("netstandard2.0", result); - } - - [Fact] - public void ANetStandardTargetIsNotCompatibleWithNetCoreApp() - { - // A netstandard library cannot consume a netcoreapp asset. - var result = _target.FindAllCompatibleFrameworks("netstandard2.0"); - - Assert.DoesNotContain("netcoreapp3.1", result); - } - - [Theory] - [InlineData("net471")] - [InlineData("net472")] - public void KnowsTheFrameworksAddedOnTopOfCommonFrameworks(string target) - { - // These two are absent from NuGet's CommonFrameworks and are registered by hand, - // so an unknown-framework result would mean the registration was lost. - var result = _target.FindAllCompatibleFrameworks(target); - - Assert.Contains("netstandard2.0", result); - Assert.Contains(target, result); - } - - [Fact] - public void AnUnknownFrameworkFallsBackToItselfAndAny() - { - var result = _target.FindAllCompatibleFrameworks("not-a-framework"); - - Assert.Equal(new[] { "not-a-framework", "any" }, result); - } - - [Fact] - public void RepeatedCallsReturnTheSameResult() - { - // The results are memoised in a static cache shared by every instance. - var first = _target.FindAllCompatibleFrameworks("net6.0"); - var second = new FrameworkCompatibilityService().FindAllCompatibleFrameworks("net6.0"); - - Assert.Equal(first, second); - } - - [Fact] - public void NeverReturnsDuplicates() - { - var result = _target.FindAllCompatibleFrameworks("net6.0"); - - Assert.Equal(result.Count, new System.Collections.Generic.HashSet(result).Count); - } + var result = _target.FindAllCompatibleFrameworks("net472"); + + Assert.Contains("netstandard2.0", result); + } + + [Fact] + public void ANetStandardTargetIsNotCompatibleWithNetCoreApp() + { + // A netstandard library cannot consume a netcoreapp asset. + var result = _target.FindAllCompatibleFrameworks("netstandard2.0"); + + Assert.DoesNotContain("netcoreapp3.1", result); + } + + [Theory] + [InlineData("net471")] + [InlineData("net472")] + public void KnowsTheFrameworksAddedOnTopOfCommonFrameworks(string target) + { + // These two are absent from NuGet's CommonFrameworks and are registered by hand, + // so an unknown-framework result would mean the registration was lost. + var result = _target.FindAllCompatibleFrameworks(target); + + Assert.Contains("netstandard2.0", result); + Assert.Contains(target, result); + } + + [Fact] + public void AnUnknownFrameworkFallsBackToItselfAndAny() + { + var result = _target.FindAllCompatibleFrameworks("not-a-framework"); + + Assert.Equal(new[] { "not-a-framework", "any" }, result); + } + + [Fact] + public void RepeatedCallsReturnTheSameResult() + { + // The results are memoised in a static cache shared by every instance. + var first = _target.FindAllCompatibleFrameworks("net6.0"); + var second = new FrameworkCompatibilityService().FindAllCompatibleFrameworks("net6.0"); + + Assert.Equal(first, second); + } + + [Fact] + public void NeverReturnsDuplicates() + { + var result = _target.FindAllCompatibleFrameworks("net6.0"); + + Assert.Equal(result.Count, new System.Collections.Generic.HashSet(result).Count); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Indexing/PackageChangeNotifierTests.cs b/tests/BaGet.Core.Tests/Indexing/PackageChangeNotifierTests.cs index 5cd65cb0b..54a74817c 100644 --- a/tests/BaGet.Core.Tests/Indexing/PackageChangeNotifierTests.cs +++ b/tests/BaGet.Core.Tests/Indexing/PackageChangeNotifierTests.cs @@ -6,58 +6,57 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests.Indexing +namespace BaGet.Core.Tests.Indexing; + +public class PackageChangeNotifierTests { - public class PackageChangeNotifierTests + private static readonly NuGetVersion Version = NuGetVersion.Parse("1.0.0"); + + [Fact] + public async Task CallsEveryHandler() + { + var first = new Mock(); + var second = new Mock(); + var target = new PackageChangeNotifier(new[] { first.Object, second.Object }, NullLogger.Instance); + + await target.PackageChangedAsync("Id", Version, CancellationToken.None); + await target.PackageDeletedAsync("Id", Version, CancellationToken.None); + + first.Verify(h => h.OnPackageChangedAsync("Id", Version, It.IsAny()), Times.Once); + second.Verify(h => h.OnPackageChangedAsync("Id", Version, It.IsAny()), Times.Once); + first.Verify(h => h.OnPackageDeletedAsync("Id", Version, It.IsAny()), Times.Once); + second.Verify(h => h.OnPackageDeletedAsync("Id", Version, It.IsAny()), Times.Once); + } + + [Fact] + public async Task AFailingHandlerDoesNotFailTheChangeOrStopTheOthers() { - private static readonly NuGetVersion Version = NuGetVersion.Parse("1.0.0"); - - [Fact] - public async Task CallsEveryHandler() - { - var first = new Mock(); - var second = new Mock(); - var target = new PackageChangeNotifier(new[] { first.Object, second.Object }, NullLogger.Instance); - - await target.PackageChangedAsync("Id", Version, CancellationToken.None); - await target.PackageDeletedAsync("Id", Version, CancellationToken.None); - - first.Verify(h => h.OnPackageChangedAsync("Id", Version, It.IsAny()), Times.Once); - second.Verify(h => h.OnPackageChangedAsync("Id", Version, It.IsAny()), Times.Once); - first.Verify(h => h.OnPackageDeletedAsync("Id", Version, It.IsAny()), Times.Once); - second.Verify(h => h.OnPackageDeletedAsync("Id", Version, It.IsAny()), Times.Once); - } - - [Fact] - public async Task AFailingHandlerDoesNotFailTheChangeOrStopTheOthers() - { - // The change is already committed; a handler's failure must not undo or fail it. - var failing = new Mock(); - failing - .Setup(h => h.OnPackageChangedAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .ThrowsAsync(new InvalidOperationException()); - var next = new Mock(); - var target = new PackageChangeNotifier(new[] { failing.Object, next.Object }, NullLogger.Instance); - - await target.PackageChangedAsync("Id", Version, CancellationToken.None); - - next.Verify(h => h.OnPackageChangedAsync("Id", Version, It.IsAny()), Times.Once); - } - - [Fact] - public async Task TheCallersCancellationPropagates() - { - using var cancellation = new CancellationTokenSource(); - cancellation.Cancel(); - - var handler = new Mock(); - handler - .Setup(h => h.OnPackageChangedAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .ThrowsAsync(new OperationCanceledException()); - var target = new PackageChangeNotifier(new[] { handler.Object }, NullLogger.Instance); - - await Assert.ThrowsAsync( - () => target.PackageChangedAsync("Id", Version, cancellation.Token)); - } + // The change is already committed; a handler's failure must not undo or fail it. + var failing = new Mock(); + failing + .Setup(h => h.OnPackageChangedAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException()); + var next = new Mock(); + var target = new PackageChangeNotifier(new[] { failing.Object, next.Object }, NullLogger.Instance); + + await target.PackageChangedAsync("Id", Version, CancellationToken.None); + + next.Verify(h => h.OnPackageChangedAsync("Id", Version, It.IsAny()), Times.Once); + } + + [Fact] + public async Task TheCallersCancellationPropagates() + { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + var handler = new Mock(); + handler + .Setup(h => h.OnPackageChangedAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ThrowsAsync(new OperationCanceledException()); + var target = new PackageChangeNotifier(new[] { handler.Object }, NullLogger.Instance); + + await Assert.ThrowsAsync( + () => target.PackageChangedAsync("Id", Version, cancellation.Token)); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Metadata/ModelTests.cs b/tests/BaGet.Core.Tests/Metadata/ModelTests.cs index 507580ef5..f4eace633 100644 --- a/tests/BaGet.Core.Tests/Metadata/ModelTests.cs +++ b/tests/BaGet.Core.Tests/Metadata/ModelTests.cs @@ -6,256 +6,255 @@ using BaGet.Protocol.Models; using Xunit; -namespace BaGet.Core.Tests.Metadata +namespace BaGet.Core.Tests.Metadata; + +public class ModelTests { - public class ModelTests + /// + /// BaGet extends the NuGet protocol to add more functionality. + /// Since System.Text.Json does not support polymorphic serialization, + /// this was implemented by duplicating the protocol's models from the + /// "BaGet.Protocol" project. These tests ensure that the duplicates + /// stay in sync with the original protocol models. + /// + public static IEnumerable ExtendedModelsData() { - /// - /// BaGet extends the NuGet protocol to add more functionality. - /// Since System.Text.Json does not support polymorphic serialization, - /// this was implemented by duplicating the protocol's models from the - /// "BaGet.Protocol" project. These tests ensure that the duplicates - /// stay in sync with the original protocol models. - /// - public static IEnumerable ExtendedModelsData() + yield return new object[] { - yield return new object[] + new ExtendedModelData { - new ExtendedModelData + OriginalType = typeof(RegistrationIndexResponse), + DerivedType = typeof(BaGetRegistrationIndexResponse), + + AddedProperties = new Dictionary { - OriginalType = typeof(RegistrationIndexResponse), - DerivedType = typeof(BaGetRegistrationIndexResponse), + { "TotalDownloads", typeof(long) }, + }, - AddedProperties = new Dictionary + ModifiedProperties = new Dictionary + { { - { "TotalDownloads", typeof(long) }, + "Pages", + ( + From: typeof(IReadOnlyList), + To: typeof(IReadOnlyList) + ) }, - - ModifiedProperties = new Dictionary - { - { - "Pages", - ( - From: typeof(IReadOnlyList), - To: typeof(IReadOnlyList) - ) - }, - } } - }; + } + }; - yield return new object[] + yield return new object[] + { + new ExtendedModelData { - new ExtendedModelData - { - OriginalType = typeof(RegistrationIndexPage), - DerivedType = typeof(BaGetRegistrationIndexPage), + OriginalType = typeof(RegistrationIndexPage), + DerivedType = typeof(BaGetRegistrationIndexPage), - ModifiedProperties = new Dictionary - { - { - "ItemsOrNull", - ( - From: typeof(IReadOnlyList), - To: typeof(IReadOnlyList) - ) - }, - } - } - }; - - yield return new object[] - { - new ExtendedModelData + ModifiedProperties = new Dictionary { - OriginalType = typeof(RegistrationIndexPageItem), - DerivedType = typeof(BaGetRegistrationIndexPageItem), - - ModifiedProperties = new Dictionary { - { - "PackageMetadata", ( From: typeof(PackageMetadata), To: typeof(BaGetPackageMetadata) ) - }, - } + "ItemsOrNull", + ( + From: typeof(IReadOnlyList), + To: typeof(IReadOnlyList) + ) + }, } - }; + } + }; - yield return new object[] + yield return new object[] + { + new ExtendedModelData { - new ExtendedModelData - { - OriginalType = typeof(PackageMetadata), - DerivedType = typeof(BaGetPackageMetadata), + OriginalType = typeof(RegistrationIndexPageItem), + DerivedType = typeof(BaGetRegistrationIndexPageItem), - AddedProperties = new Dictionary + ModifiedProperties = new Dictionary + { { - { "Downloads", typeof(long) }, - { "HasReadme", typeof(bool) }, - { "PackageTypes", typeof(IReadOnlyList) }, - { "ReleaseNotes", typeof(string) }, - { "RepositoryUrl", typeof(string) }, - { "RepositoryType", typeof(string) }, - } + "PackageMetadata", ( From: typeof(PackageMetadata), To: typeof(BaGetPackageMetadata) ) + }, } - }; - } + } + }; - [Theory] - [MemberData(nameof(ExtendedModelsData))] - public void ValidateExtendedModels(ExtendedModelData data) + yield return new object[] { - IReadOnlyDictionary originalProperties = PropertiesOf(data.OriginalType); - IReadOnlyDictionary derivedProperties = PropertiesOf(data.DerivedType); - - // Check that all properties on the original model are present on the derived model. - var missingProperties = originalProperties.Keys.Where(name => !derivedProperties.ContainsKey(name)); - - Assert.True( - !missingProperties.Any(), - $"The following properties are missing from the derived type: {string.Join(',', missingProperties)}"); - - // Check that all properties on the derived model are as expected compared to the original model. - foreach (var derivedProperty in derivedProperties.Values) + new ExtendedModelData { - // If the property was added, check that it is not on the original type. - if (data.AddedProperties.TryGetValue(derivedProperty.Name, out var addedType)) + OriginalType = typeof(PackageMetadata), + DerivedType = typeof(BaGetPackageMetadata), + + AddedProperties = new Dictionary { - Assert.True( - !originalProperties.ContainsKey(derivedProperty.Name), - $"Added property '{derivedProperty.Name}' exists on the original type {data.OriginalType}"); - Assert.True( - addedType == derivedProperty.PropertyType, - $"Added property '{derivedProperty.Name}' on type {data.DerivedType} has unexpected property type\n" + - $"Expected: {addedType}\n" + - $"Actual: {derivedProperty.PropertyType}"); - continue; + { "Downloads", typeof(long) }, + { "HasReadme", typeof(bool) }, + { "PackageTypes", typeof(IReadOnlyList) }, + { "ReleaseNotes", typeof(string) }, + { "RepositoryUrl", typeof(string) }, + { "RepositoryType", typeof(string) }, } + } + }; + } - // This property should exist on both the original and derived models. - // This property should have the same "JsonPropertyName" attribute values. - var originalProperty = Assert.Contains(derivedProperty.Name, originalProperties); + [Theory] + [MemberData(nameof(ExtendedModelsData))] + public void ValidateExtendedModels(ExtendedModelData data) + { + IReadOnlyDictionary originalProperties = PropertiesOf(data.OriginalType); + IReadOnlyDictionary derivedProperties = PropertiesOf(data.DerivedType); - var originalJsonName = GetAttributeArgs(originalProperty)?.FirstOrDefault(); - var derivedJsonName = GetAttributeArgs(derivedProperty)?.FirstOrDefault(); + // Check that all properties on the original model are present on the derived model. + var missingProperties = originalProperties.Keys.Where(name => !derivedProperties.ContainsKey(name)); + Assert.True( + !missingProperties.Any(), + $"The following properties are missing from the derived type: {string.Join(',', missingProperties)}"); + + // Check that all properties on the derived model are as expected compared to the original model. + foreach (var derivedProperty in derivedProperties.Values) + { + // If the property was added, check that it is not on the original type. + if (data.AddedProperties.TryGetValue(derivedProperty.Name, out var addedType)) + { Assert.True( - originalJsonName != null, - $"Property '{originalProperty.Name}' on type '{data.OriginalType}' " + - "does not have a JsonPropertyName attribute"); - Assert.True( - derivedJsonName != null, - $"Property '{derivedProperty.Name}' on type '{data.DerivedType}' " + - "does not have a JsonPropertyName attribute"); + !originalProperties.ContainsKey(derivedProperty.Name), + $"Added property '{derivedProperty.Name}' exists on the original type {data.OriginalType}"); Assert.True( - originalJsonName.ToString() == derivedJsonName.ToString(), - $"Property '{derivedProperty.Name}' on type '{data.DerivedType}' " + - "has a different JsonPropertyName attribute value than " + - $"on type '{data.OriginalType}'.\nExpected: '{originalJsonName}'\n" + - $"Actual: '{derivedJsonName}'"); + addedType == derivedProperty.PropertyType, + $"Added property '{derivedProperty.Name}' on type {data.DerivedType} has unexpected property type\n" + + $"Expected: {addedType}\n" + + $"Actual: {derivedProperty.PropertyType}"); + continue; + } - var originalJsonConverterArgs = GetAttributeArgs(originalProperty); - var derivedJsonConverterArgs = GetAttributeArgs(derivedProperty); + // This property should exist on both the original and derived models. + // This property should have the same "JsonPropertyName" attribute values. + var originalProperty = Assert.Contains(derivedProperty.Name, originalProperties); - // If the property was modified, check that the property types are expected. - if (data.ModifiedProperties.TryGetValue(derivedProperty.Name, out var modifiedTypes)) - { - Assert.True( - originalProperty.PropertyType == modifiedTypes.From, - $"Modified property '{originalProperty.Name}' on type {data.OriginalType} has unexpected property type\n" + - $"Expected: {modifiedTypes.From}\n" + - $"Actual: {originalProperty.PropertyType}"); - Assert.True( - derivedProperty.PropertyType == modifiedTypes.To, - $"Modified property '{derivedProperty.Name}' on type {data.DerivedType} has unexpected property type\n" + - $"Expected: {modifiedTypes.To}\n" + - $"Actual: {derivedProperty.PropertyType}"); + var originalJsonName = GetAttributeArgs(originalProperty)?.FirstOrDefault(); + var derivedJsonName = GetAttributeArgs(derivedProperty)?.FirstOrDefault(); - if (originalJsonConverterArgs != null || derivedJsonConverterArgs != null) - { - throw new NotSupportedException( - "JSON converters on modified properties is not supported"); - } + Assert.True( + originalJsonName != null, + $"Property '{originalProperty.Name}' on type '{data.OriginalType}' " + + "does not have a JsonPropertyName attribute"); + Assert.True( + derivedJsonName != null, + $"Property '{derivedProperty.Name}' on type '{data.DerivedType}' " + + "does not have a JsonPropertyName attribute"); + Assert.True( + originalJsonName.ToString() == derivedJsonName.ToString(), + $"Property '{derivedProperty.Name}' on type '{data.DerivedType}' " + + "has a different JsonPropertyName attribute value than " + + $"on type '{data.OriginalType}'.\nExpected: '{originalJsonName}'\n" + + $"Actual: '{derivedJsonName}'"); - continue; - } + var originalJsonConverterArgs = GetAttributeArgs(originalProperty); + var derivedJsonConverterArgs = GetAttributeArgs(derivedProperty); - // Otherwise, this property should be identical to the original property. + // If the property was modified, check that the property types are expected. + if (data.ModifiedProperties.TryGetValue(derivedProperty.Name, out var modifiedTypes)) + { Assert.True( - originalProperty.PropertyType == derivedProperty.PropertyType, - $"Property '{derivedProperty.Name}' on type {data.DerivedType} has unexpected property type\n" + - $"Expected: {originalProperty.PropertyType}\n" + - $"Actual: {derivedProperty.PropertyType}"); + originalProperty.PropertyType == modifiedTypes.From, + $"Modified property '{originalProperty.Name}' on type {data.OriginalType} has unexpected property type\n" + + $"Expected: {modifiedTypes.From}\n" + + $"Actual: {originalProperty.PropertyType}"); Assert.True( - originalJsonConverterArgs?.First() == derivedJsonConverterArgs?.First(), - $"Property '{derivedProperty.Name}' on type '{data.DerivedType}' " + - "has unexpected JsonConverter value.\n" + - $"Expected: '{originalJsonConverterArgs?.First()}'\n" + - $"Actual: '{derivedJsonConverterArgs?.First()}'"); + derivedProperty.PropertyType == modifiedTypes.To, + $"Modified property '{derivedProperty.Name}' on type {data.DerivedType} has unexpected property type\n" + + $"Expected: {modifiedTypes.To}\n" + + $"Actual: {derivedProperty.PropertyType}"); + + if (originalJsonConverterArgs != null || derivedJsonConverterArgs != null) + { + throw new NotSupportedException( + "JSON converters on modified properties is not supported"); + } + + continue; } - } - private IList GetAttributeArgs(PropertyInfo property) - { - return property - .CustomAttributes - ?.SingleOrDefault(x => x.AttributeType == typeof(TAttribute)) - ?.ConstructorArguments; + // Otherwise, this property should be identical to the original property. + Assert.True( + originalProperty.PropertyType == derivedProperty.PropertyType, + $"Property '{derivedProperty.Name}' on type {data.DerivedType} has unexpected property type\n" + + $"Expected: {originalProperty.PropertyType}\n" + + $"Actual: {derivedProperty.PropertyType}"); + Assert.True( + originalJsonConverterArgs?.First() == derivedJsonConverterArgs?.First(), + $"Property '{derivedProperty.Name}' on type '{data.DerivedType}' " + + "has unexpected JsonConverter value.\n" + + $"Expected: '{originalJsonConverterArgs?.First()}'\n" + + $"Actual: '{derivedJsonConverterArgs?.First()}'"); } + } - public class ExtendedModelData - { - /// - /// The model's type in the "BaGet.Protocol" project that was extended. - /// - public Type OriginalType { get; set; } + private IList GetAttributeArgs(PropertyInfo property) + { + return property + .CustomAttributes + ?.SingleOrDefault(x => x.AttributeType == typeof(TAttribute)) + ?.ConstructorArguments; + } - /// - /// The model's type in the "BaGet.Core" project that extends a - /// type from the "BaGet.Protocol" project. - /// - public Type DerivedType { get; set; } + public class ExtendedModelData + { + /// + /// The model's type in the "BaGet.Protocol" project that was extended. + /// + public Type OriginalType { get; set; } - /// - /// The properties added by the model type in the "BaGet.Core" project. - /// - public Dictionary AddedProperties { get; set; } = new Dictionary(); + /// + /// The model's type in the "BaGet.Core" project that extends a + /// type from the "BaGet.Protocol" project. + /// + public Type DerivedType { get; set; } - /// - /// The properties whose types were modified by the model type in the - /// "BaGet.Core" project. - /// - public Dictionary ModifiedProperties { get; set; } - = new Dictionary(); - } + /// + /// The properties added by the model type in the "BaGet.Core" project. + /// + public Dictionary AddedProperties { get; set; } = new Dictionary(); /// - /// The public properties of a type, keyed by name. A derived model may shadow a base - /// property with the "new" modifier to change its type, in which case reflection - /// reports one declaration per declaring type; keep the most derived one, which is - /// the declaration that is serialized. + /// The properties whose types were modified by the model type in the + /// "BaGet.Core" project. /// - private static IReadOnlyDictionary PropertiesOf(Type type) + public Dictionary ModifiedProperties { get; set; } + = new Dictionary(); + } + + /// + /// The public properties of a type, keyed by name. A derived model may shadow a base + /// property with the "new" modifier to change its type, in which case reflection + /// reports one declaration per declaring type; keep the most derived one, which is + /// the declaration that is serialized. + /// + private static IReadOnlyDictionary PropertiesOf(Type type) + { + static int InheritanceDepth(Type declaringType) { - static int InheritanceDepth(Type declaringType) + var depth = 0; + for (var current = declaringType; current != null; current = current.BaseType) { - var depth = 0; - for (var current = declaringType; current != null; current = current.BaseType) - { - depth++; - } - - return depth; + depth++; } - return type - .GetProperties() - .GroupBy(p => p.Name) - .ToDictionary( - group => group.Key, - group => group - .OrderByDescending(p => InheritanceDepth(p.DeclaringType)) - .First()); + return depth; } + return type + .GetProperties() + .GroupBy(p => p.Name) + .ToDictionary( + group => group.Key, + group => group + .OrderByDescending(p => InheritanceDepth(p.DeclaringType)) + .First()); } -} + +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Metadata/RegistrationBuilderTests.cs b/tests/BaGet.Core.Tests/Metadata/RegistrationBuilderTests.cs index 361257401..f929d670d 100644 --- a/tests/BaGet.Core.Tests/Metadata/RegistrationBuilderTests.cs +++ b/tests/BaGet.Core.Tests/Metadata/RegistrationBuilderTests.cs @@ -4,63 +4,62 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests.Metadata +namespace BaGet.Core.Tests.Metadata; + +public class RegistrationBuilderTests { - public class RegistrationBuilderTests + private readonly Mock _urlGenerator; + + public RegistrationBuilderTests() { - private readonly Mock _urlGenerator; + _urlGenerator = new Mock(); + } - public RegistrationBuilderTests() - { - _urlGenerator = new Mock(); - } + [Fact] + public void TheRegistrationIndexResponseIsSortedByVersion() + { + // Arrange + var packageId = "BaGet.Test"; + var authors = new string[] { "test" }; - [Fact] - public void TheRegistrationIndexResponseIsSortedByVersion() + var packages = new List { - // Arrange - var packageId = "BaGet.Test"; - var authors = new string[] { "test" }; + GetTestPackage(packageId, "3.1.0"), + GetTestPackage(packageId, "10.0.5"), + GetTestPackage(packageId, "3.2.0"), + GetTestPackage(packageId, "3.1.0-pre"), + GetTestPackage(packageId, "1.0.0-beta1"), + GetTestPackage(packageId, "1.0.0"), + }; - var packages = new List - { - GetTestPackage(packageId, "3.1.0"), - GetTestPackage(packageId, "10.0.5"), - GetTestPackage(packageId, "3.2.0"), - GetTestPackage(packageId, "3.1.0-pre"), - GetTestPackage(packageId, "1.0.0-beta1"), - GetTestPackage(packageId, "1.0.0"), - }; + var registration = new PackageRegistration(packageId, packages); - var registration = new PackageRegistration(packageId, packages); + var registrationBuilder = new RegistrationBuilder(_urlGenerator.Object); - var registrationBuilder = new RegistrationBuilder(_urlGenerator.Object); + // Act + var response = registrationBuilder.BuildIndex(registration); - // Act - var response = registrationBuilder.BuildIndex(registration); - - // Assert - Assert.Equal(packages.Count, response.Pages[0].ItemsOrNull.Count); - var index = 0; - foreach (var package in packages.OrderBy(p => p.Version)) - { - Assert.Equal(package.Version.ToFullString(), response.Pages[0].ItemsOrNull[index++].PackageMetadata.Version); - } + // Assert + Assert.Equal(packages.Count, response.Pages[0].ItemsOrNull.Count); + var index = 0; + foreach (var package in packages.OrderBy(p => p.Version)) + { + Assert.Equal(package.Version.ToFullString(), response.Pages[0].ItemsOrNull[index++].PackageMetadata.Version); } + } - /// - /// Create a fake with the minimum metadata needed by the . - /// - private Package GetTestPackage(string packageId, string version) - { - return new Package - { - Id = packageId, - Authors = new string[] { "test" }, - PackageTypes = new List { new PackageType { Name = "test" } }, - Dependencies = new List { }, - Version = new NuGetVersion(version), - }; - } + /// + /// Create a fake with the minimum metadata needed by the . + /// + private Package GetTestPackage(string packageId, string version) + { + return new Package + { + Id = packageId, + Authors = new string[] { "test" }, + PackageTypes = new List { new PackageType { Name = "test" } }, + Dependencies = new List { }, + Version = new NuGetVersion(version), + }; } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Search/SearchResponseBuilderTests.cs b/tests/BaGet.Core.Tests/Search/SearchResponseBuilderTests.cs index 20b12c3bd..4c817b597 100644 --- a/tests/BaGet.Core.Tests/Search/SearchResponseBuilderTests.cs +++ b/tests/BaGet.Core.Tests/Search/SearchResponseBuilderTests.cs @@ -5,226 +5,225 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests.Search +namespace BaGet.Core.Tests.Search; + +public class SearchResponseBuilderTests { - public class SearchResponseBuilderTests + private readonly Mock _url; + private readonly SearchResponseBuilder _target; + + public SearchResponseBuilderTests() { - private readonly Mock _url; - private readonly SearchResponseBuilder _target; + _url = new Mock(); + _url.Setup(u => u.GetRegistrationIndexUrl(It.IsAny())) + .Returns(id => $"https://test/v3/registration/{id}/index.json"); + _url.Setup(u => u.GetRegistrationLeafUrl(It.IsAny(), It.IsAny())) + .Returns((id, v) => $"https://test/v3/registration/{id}/{v}.json"); + _url.Setup(u => u.GetPackageIconDownloadUrl(It.IsAny(), It.IsAny())) + .Returns((id, v) => $"https://test/v3/package/{id}/{v}/icon"); + _url.Setup(u => u.GetPackageMetadataResourceUrl()) + .Returns("https://test/v3/registration"); + + _target = new SearchResponseBuilder(_url.Object); + } - public SearchResponseBuilderTests() - { - _url = new Mock(); - _url.Setup(u => u.GetRegistrationIndexUrl(It.IsAny())) - .Returns(id => $"https://test/v3/registration/{id}/index.json"); - _url.Setup(u => u.GetRegistrationLeafUrl(It.IsAny(), It.IsAny())) - .Returns((id, v) => $"https://test/v3/registration/{id}/{v}.json"); - _url.Setup(u => u.GetPackageIconDownloadUrl(It.IsAny(), It.IsAny())) - .Returns((id, v) => $"https://test/v3/package/{id}/{v}/icon"); - _url.Setup(u => u.GetPackageMetadataResourceUrl()) - .Returns("https://test/v3/registration"); - - _target = new SearchResponseBuilder(_url.Object); - } - - private static Package Package(string id, string version, long downloads = 0, bool embeddedIcon = false) - => new Package - { - Id = id, - Version = NuGetVersion.Parse(version), - Downloads = downloads, - HasEmbeddedIcon = embeddedIcon, - Listed = true, - Authors = new[] { "author" }, - Tags = new[] { "tag" }, - Description = "description", - Summary = "summary", - Title = "title", - Dependencies = new List(), - PackageTypes = new List(), - TargetFrameworks = new List(), - }; - - private static PackageRegistration Registration(string id, params Package[] packages) - => new PackageRegistration(id, packages); - - [Fact] - public void ReportsTheLatestVersionAsTheResultVersion() + private static Package Package(string id, string version, long downloads = 0, bool embeddedIcon = false) + => new Package + { + Id = id, + Version = NuGetVersion.Parse(version), + Downloads = downloads, + HasEmbeddedIcon = embeddedIcon, + Listed = true, + Authors = new[] { "author" }, + Tags = new[] { "tag" }, + Description = "description", + Summary = "summary", + Title = "title", + Dependencies = new List(), + PackageTypes = new List(), + TargetFrameworks = new List(), + }; + + private static PackageRegistration Registration(string id, params Package[] packages) + => new PackageRegistration(id, packages); + + [Fact] + public void ReportsTheLatestVersionAsTheResultVersion() + { + var response = _target.BuildSearch(new[] { - var response = _target.BuildSearch(new[] - { - Registration("Test", - Package("Test", "1.0.0"), - Package("Test", "3.1.0"), - Package("Test", "2.0.0")), - }, totalHits: 1); - - Assert.Equal("3.1.0", Assert.Single(response.Data).Version); - } - - [Fact] - public void APrereleaseVersionSortsBelowItsRelease() + Registration("Test", + Package("Test", "1.0.0"), + Package("Test", "3.1.0"), + Package("Test", "2.0.0")), + }, totalHits: 1); + + Assert.Equal("3.1.0", Assert.Single(response.Data).Version); + } + + [Fact] + public void APrereleaseVersionSortsBelowItsRelease() + { + var response = _target.BuildSearch(new[] { - var response = _target.BuildSearch(new[] - { - Registration("Test", - Package("Test", "2.0.0-beta"), - Package("Test", "2.0.0")), - }, totalHits: 1); - - Assert.Equal("2.0.0", Assert.Single(response.Data).Version); - } - - [Fact] - public void ComparesVersionsNumericallyNotAsText() + Registration("Test", + Package("Test", "2.0.0-beta"), + Package("Test", "2.0.0")), + }, totalHits: 1); + + Assert.Equal("2.0.0", Assert.Single(response.Data).Version); + } + + [Fact] + public void ComparesVersionsNumericallyNotAsText() + { + var response = _target.BuildSearch(new[] { - var response = _target.BuildSearch(new[] - { - Registration("Test", - Package("Test", "9.0.0"), - Package("Test", "10.0.0")), - }, totalHits: 1); - - Assert.Equal("10.0.0", Assert.Single(response.Data).Version); - } - - [Fact] - public void ListsVersionsNewestFirst() + Registration("Test", + Package("Test", "9.0.0"), + Package("Test", "10.0.0")), + }, totalHits: 1); + + Assert.Equal("10.0.0", Assert.Single(response.Data).Version); + } + + [Fact] + public void ListsVersionsNewestFirst() + { + var response = _target.BuildSearch(new[] { - var response = _target.BuildSearch(new[] - { - Registration("Test", - Package("Test", "1.0.0"), - Package("Test", "3.0.0"), - Package("Test", "2.0.0")), - }, totalHits: 1); - - Assert.Equal( - new[] { "3.0.0", "2.0.0", "1.0.0" }, - Assert.Single(response.Data).Versions.Select(v => v.Version)); - } - - [Fact] - public void TotalDownloadsSumsEveryVersion() + Registration("Test", + Package("Test", "1.0.0"), + Package("Test", "3.0.0"), + Package("Test", "2.0.0")), + }, totalHits: 1); + + Assert.Equal( + new[] { "3.0.0", "2.0.0", "1.0.0" }, + Assert.Single(response.Data).Versions.Select(v => v.Version)); + } + + [Fact] + public void TotalDownloadsSumsEveryVersion() + { + var response = _target.BuildSearch(new[] { - var response = _target.BuildSearch(new[] - { - Registration("Test", - Package("Test", "1.0.0", downloads: 10), - Package("Test", "2.0.0", downloads: 32)), - }, totalHits: 1); - - Assert.Equal(42, Assert.Single(response.Data).TotalDownloads); - } - - [Fact] - public void EachVersionKeepsItsOwnDownloadCount() + Registration("Test", + Package("Test", "1.0.0", downloads: 10), + Package("Test", "2.0.0", downloads: 32)), + }, totalHits: 1); + + Assert.Equal(42, Assert.Single(response.Data).TotalDownloads); + } + + [Fact] + public void EachVersionKeepsItsOwnDownloadCount() + { + var response = _target.BuildSearch(new[] { - var response = _target.BuildSearch(new[] - { - Registration("Test", - Package("Test", "1.0.0", downloads: 10), - Package("Test", "2.0.0", downloads: 32)), - }, totalHits: 1); + Registration("Test", + Package("Test", "1.0.0", downloads: 10), + Package("Test", "2.0.0", downloads: 32)), + }, totalHits: 1); - var versions = Assert.Single(response.Data).Versions; + var versions = Assert.Single(response.Data).Versions; - Assert.Equal(32, versions.First(v => v.Version == "2.0.0").Downloads); - Assert.Equal(10, versions.First(v => v.Version == "1.0.0").Downloads); - } + Assert.Equal(32, versions.First(v => v.Version == "2.0.0").Downloads); + Assert.Equal(10, versions.First(v => v.Version == "1.0.0").Downloads); + } - [Fact] - public void UsesTheGeneratedIconUrlForAnEmbeddedIcon() - { - var package = Package("Test", "1.0.0", embeddedIcon: true); + [Fact] + public void UsesTheGeneratedIconUrlForAnEmbeddedIcon() + { + var package = Package("Test", "1.0.0", embeddedIcon: true); - var response = _target.BuildSearch(new[] { Registration("Test", package) }, totalHits: 1); + var response = _target.BuildSearch(new[] { Registration("Test", package) }, totalHits: 1); - Assert.Equal("https://test/v3/package/Test/1.0.0/icon", Assert.Single(response.Data).IconUrl); - } + Assert.Equal("https://test/v3/package/Test/1.0.0/icon", Assert.Single(response.Data).IconUrl); + } - [Fact] - public void UsesThePackagesOwnIconUrlWhenTheIconIsNotEmbedded() - { - var package = Package("Test", "1.0.0"); - package.IconUrl = new Uri("https://elsewhere.test/icon.png"); + [Fact] + public void UsesThePackagesOwnIconUrlWhenTheIconIsNotEmbedded() + { + var package = Package("Test", "1.0.0"); + package.IconUrl = new Uri("https://elsewhere.test/icon.png"); - var response = _target.BuildSearch(new[] { Registration("Test", package) }, totalHits: 1); + var response = _target.BuildSearch(new[] { Registration("Test", package) }, totalHits: 1); - Assert.Equal("https://elsewhere.test/icon.png", Assert.Single(response.Data).IconUrl); - } + Assert.Equal("https://elsewhere.test/icon.png", Assert.Single(response.Data).IconUrl); + } - [Fact] - public void ReturnsOneResultPerRegistration() + [Fact] + public void ReturnsOneResultPerRegistration() + { + var response = _target.BuildSearch(new[] { - var response = _target.BuildSearch(new[] - { - Registration("A", Package("A", "1.0.0")), - Registration("B", Package("B", "1.0.0")), - }, totalHits: 2); + Registration("A", Package("A", "1.0.0")), + Registration("B", Package("B", "1.0.0")), + }, totalHits: 2); - Assert.Equal(new[] { "A", "B" }, response.Data.Select(d => d.PackageId)); - } + Assert.Equal(new[] { "A", "B" }, response.Data.Select(d => d.PackageId)); + } - [Fact] - public void ReturnsAnEmptyResponseForNoRegistrations() - { - var response = _target.BuildSearch(new PackageRegistration[0], totalHits: 0); + [Fact] + public void ReturnsAnEmptyResponseForNoRegistrations() + { + var response = _target.BuildSearch(new PackageRegistration[0], totalHits: 0); - Assert.Empty(response.Data); - Assert.Equal(0, response.TotalHits); - } + Assert.Empty(response.Data); + Assert.Equal(0, response.TotalHits); + } - [Fact] - public void BuildAutocompleteReturnsTheIdsItWasGiven() - { - var response = _target.BuildAutocomplete(new[] { "First", "Second" }, totalHits: 2); + [Fact] + public void BuildAutocompleteReturnsTheIdsItWasGiven() + { + var response = _target.BuildAutocomplete(new[] { "First", "Second" }, totalHits: 2); - Assert.Equal(new[] { "First", "Second" }, response.Data); - } + Assert.Equal(new[] { "First", "Second" }, response.Data); + } - [Fact] - public void BuildAutocompleteHandlesAnEmptyList() - { - var response = _target.BuildAutocomplete(new string[0], totalHits: 0); + [Fact] + public void BuildAutocompleteHandlesAnEmptyList() + { + var response = _target.BuildAutocomplete(new string[0], totalHits: 0); - Assert.Empty(response.Data); - Assert.Equal(0, response.TotalHits); - } + Assert.Empty(response.Data); + Assert.Equal(0, response.TotalHits); + } - [Fact] - public void TotalHitsIsTheTotalGivenRatherThanThePageSize() - { - // The protocol documents TotalHits as the number of matches disregarding skip - // and take, so a page of one out of fifty reports fifty. - var response = _target.BuildSearch( - new[] { Registration("Test", Package("Test", "1.0.0")) }, - totalHits: 50); - - Assert.Single(response.Data); - Assert.Equal(50, response.TotalHits); - } - - [Fact] - public void AutocompleteTotalHitsIsTheTotalGivenRatherThanThePageSize() - { - var response = _target.BuildAutocomplete(new[] { "Only.One" }, totalHits: 25); + [Fact] + public void TotalHitsIsTheTotalGivenRatherThanThePageSize() + { + // The protocol documents TotalHits as the number of matches disregarding skip + // and take, so a page of one out of fifty reports fifty. + var response = _target.BuildSearch( + new[] { Registration("Test", Package("Test", "1.0.0")) }, + totalHits: 50); + + Assert.Single(response.Data); + Assert.Equal(50, response.TotalHits); + } + + [Fact] + public void AutocompleteTotalHitsIsTheTotalGivenRatherThanThePageSize() + { + var response = _target.BuildAutocomplete(new[] { "Only.One" }, totalHits: 25); - Assert.Single(response.Data); - Assert.Equal(25, response.TotalHits); - } + Assert.Single(response.Data); + Assert.Equal(25, response.TotalHits); + } - [Fact] - public void BuildDependentsReturnsTheDependentsItWasGiven() + [Fact] + public void BuildDependentsReturnsTheDependentsItWasGiven() + { + var dependents = new[] { - var dependents = new[] - { - new PackageDependent { Id = "Dependent", Description = "d", TotalDownloads = 5 }, - }; + new PackageDependent { Id = "Dependent", Description = "d", TotalDownloads = 5 }, + }; - var response = _target.BuildDependents(dependents); + var response = _target.BuildDependents(dependents); - Assert.Equal("Dependent", Assert.Single(response.Data).Id); - } + Assert.Equal("Dependent", Assert.Single(response.Data).Id); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/ServiceIndex/BaGetServiceIndexTests.cs b/tests/BaGet.Core.Tests/ServiceIndex/BaGetServiceIndexTests.cs index d06890308..1cf860f35 100644 --- a/tests/BaGet.Core.Tests/ServiceIndex/BaGetServiceIndexTests.cs +++ b/tests/BaGet.Core.Tests/ServiceIndex/BaGetServiceIndexTests.cs @@ -4,121 +4,120 @@ using Moq; using Xunit; -namespace BaGet.Core.Tests.ServiceIndex +namespace BaGet.Core.Tests.ServiceIndex; + +public class BaGetServiceIndexTests { - public class BaGetServiceIndexTests + private readonly Mock _url; + private readonly BaGetServiceIndex _target; + + public BaGetServiceIndexTests() { - private readonly Mock _url; - private readonly BaGetServiceIndex _target; + _url = new Mock(); + _url.Setup(u => u.GetPackagePublishResourceUrl()).Returns("https://test/api/v2/package"); + _url.Setup(u => u.GetSymbolPublishResourceUrl()).Returns("https://test/api/v2/symbol"); + _url.Setup(u => u.GetSearchResourceUrl()).Returns("https://test/v3/search"); + _url.Setup(u => u.GetPackageMetadataResourceUrl()).Returns("https://test/v3/registration"); + _url.Setup(u => u.GetPackageContentResourceUrl()).Returns("https://test/v3/package"); + _url.Setup(u => u.GetAutocompleteResourceUrl()).Returns("https://test/v3/autocomplete"); + _url.Setup(u => u.GetPackageDetailsUriTemplate()).Returns("https://test/packages/{id}/{version}"); + _url.Setup(u => u.GetReportAbuseUriTemplate()).Returns("https://test/packages/{id}/{version}/report-abuse"); + _url.Setup(u => u.GetVulnerabilityIndexUrl()).Returns("https://test/v3/vulnerabilities/index.json"); + + _target = new BaGetServiceIndex(_url.Object); + } - public BaGetServiceIndexTests() - { - _url = new Mock(); - _url.Setup(u => u.GetPackagePublishResourceUrl()).Returns("https://test/api/v2/package"); - _url.Setup(u => u.GetSymbolPublishResourceUrl()).Returns("https://test/api/v2/symbol"); - _url.Setup(u => u.GetSearchResourceUrl()).Returns("https://test/v3/search"); - _url.Setup(u => u.GetPackageMetadataResourceUrl()).Returns("https://test/v3/registration"); - _url.Setup(u => u.GetPackageContentResourceUrl()).Returns("https://test/v3/package"); - _url.Setup(u => u.GetAutocompleteResourceUrl()).Returns("https://test/v3/autocomplete"); - _url.Setup(u => u.GetPackageDetailsUriTemplate()).Returns("https://test/packages/{id}/{version}"); - _url.Setup(u => u.GetReportAbuseUriTemplate()).Returns("https://test/packages/{id}/{version}/report-abuse"); - _url.Setup(u => u.GetVulnerabilityIndexUrl()).Returns("https://test/v3/vulnerabilities/index.json"); - - _target = new BaGetServiceIndex(_url.Object); - } - - private async Task Types() - { - var response = await _target.GetAsync(CancellationToken.None); + private async Task Types() + { + var response = await _target.GetAsync(CancellationToken.None); - return response.Resources.Select(r => r.Type).ToArray(); - } + return response.Resources.Select(r => r.Type).ToArray(); + } - private async Task UrlOf(string type) - { - var response = await _target.GetAsync(CancellationToken.None); + private async Task UrlOf(string type) + { + var response = await _target.GetAsync(CancellationToken.None); - return response.Resources.Single(r => r.Type == type).ResourceUrl; - } + return response.Resources.Single(r => r.Type == type).ResourceUrl; + } - [Fact] - public async Task TheVersionIsThree() - { - var response = await _target.GetAsync(CancellationToken.None); - - Assert.Equal("3.0.0", response.Version); - } - - [Theory] - [InlineData("PackagePublish/2.0.0")] - [InlineData("SymbolPackagePublish/4.9.0")] - [InlineData("SearchQueryService")] - [InlineData("SearchQueryService/3.0.0-beta")] - [InlineData("SearchQueryService/3.0.0-rc")] - [InlineData("RegistrationsBaseUrl")] - [InlineData("RegistrationsBaseUrl/3.0.0-beta")] - [InlineData("RegistrationsBaseUrl/3.0.0-rc")] - [InlineData("PackageBaseAddress/3.0.0")] - [InlineData("SearchAutocompleteService")] - [InlineData("SearchAutocompleteService/3.0.0-beta")] - [InlineData("SearchAutocompleteService/3.0.0-rc")] - public async Task AdvertisesTheResource(string type) - { - Assert.Contains(type, await Types()); - } - - [Theory] - [InlineData("PackageDetailsUriTemplate/5.1.0")] - [InlineData("ReportAbuseUriTemplate/3.0.0-beta")] - [InlineData("ReportAbuseUriTemplate/3.0.0-rc")] - public async Task AdvertisesTheUriTemplate(string type) - { - // These are the @type strings nuget.org publishes. Note report abuse has no - // "3.0.0" form: only the beta and rc ones. - Assert.Contains(type, await Types()); - } + [Fact] + public async Task TheVersionIsThree() + { + var response = await _target.GetAsync(CancellationToken.None); - [Fact] - public async Task DoesNotAdvertiseAReportAbuseVersionNuGetOrgDoesNot() - { - Assert.DoesNotContain("ReportAbuseUriTemplate/3.0.0", await Types()); - Assert.DoesNotContain("ReportAbuseUriTemplate", await Types()); - } + Assert.Equal("3.0.0", response.Version); + } - [Fact] - public async Task TheUriTemplatesKeepTheirPlaceholders() - { - // A client expands these itself, so the braces must survive verbatim and - // must not be percent-encoded. - var details = await UrlOf("PackageDetailsUriTemplate/5.1.0"); - var reportAbuse = await UrlOf("ReportAbuseUriTemplate/3.0.0-rc"); - - Assert.Contains("{id}", details); - Assert.Contains("{version}", details); - Assert.Contains("{id}", reportAbuse); - Assert.Contains("{version}", reportAbuse); - Assert.DoesNotContain("%7B", details); - Assert.DoesNotContain("%7B", reportAbuse); - } - - [Fact] - public async Task BothReportAbuseVersionsShareOneUrl() - { - Assert.Equal( - await UrlOf("ReportAbuseUriTemplate/3.0.0-beta"), - await UrlOf("ReportAbuseUriTemplate/3.0.0-rc")); - } + [Theory] + [InlineData("PackagePublish/2.0.0")] + [InlineData("SymbolPackagePublish/4.9.0")] + [InlineData("SearchQueryService")] + [InlineData("SearchQueryService/3.0.0-beta")] + [InlineData("SearchQueryService/3.0.0-rc")] + [InlineData("RegistrationsBaseUrl")] + [InlineData("RegistrationsBaseUrl/3.0.0-beta")] + [InlineData("RegistrationsBaseUrl/3.0.0-rc")] + [InlineData("PackageBaseAddress/3.0.0")] + [InlineData("SearchAutocompleteService")] + [InlineData("SearchAutocompleteService/3.0.0-beta")] + [InlineData("SearchAutocompleteService/3.0.0-rc")] + public async Task AdvertisesTheResource(string type) + { + Assert.Contains(type, await Types()); + } + + [Theory] + [InlineData("PackageDetailsUriTemplate/5.1.0")] + [InlineData("ReportAbuseUriTemplate/3.0.0-beta")] + [InlineData("ReportAbuseUriTemplate/3.0.0-rc")] + public async Task AdvertisesTheUriTemplate(string type) + { + // These are the @type strings nuget.org publishes. Note report abuse has no + // "3.0.0" form: only the beta and rc ones. + Assert.Contains(type, await Types()); + } + + [Fact] + public async Task DoesNotAdvertiseAReportAbuseVersionNuGetOrgDoesNot() + { + Assert.DoesNotContain("ReportAbuseUriTemplate/3.0.0", await Types()); + Assert.DoesNotContain("ReportAbuseUriTemplate", await Types()); + } + + [Fact] + public async Task TheUriTemplatesKeepTheirPlaceholders() + { + // A client expands these itself, so the braces must survive verbatim and + // must not be percent-encoded. + var details = await UrlOf("PackageDetailsUriTemplate/5.1.0"); + var reportAbuse = await UrlOf("ReportAbuseUriTemplate/3.0.0-rc"); + + Assert.Contains("{id}", details); + Assert.Contains("{version}", details); + Assert.Contains("{id}", reportAbuse); + Assert.Contains("{version}", reportAbuse); + Assert.DoesNotContain("%7B", details); + Assert.DoesNotContain("%7B", reportAbuse); + } + + [Fact] + public async Task BothReportAbuseVersionsShareOneUrl() + { + Assert.Equal( + await UrlOf("ReportAbuseUriTemplate/3.0.0-beta"), + await UrlOf("ReportAbuseUriTemplate/3.0.0-rc")); + } + + [Fact] + public async Task EveryResourceHasATypeAndAUrl() + { + var response = await _target.GetAsync(CancellationToken.None); - [Fact] - public async Task EveryResourceHasATypeAndAUrl() + Assert.All(response.Resources, resource => { - var response = await _target.GetAsync(CancellationToken.None); - - Assert.All(response.Resources, resource => - { - Assert.False(string.IsNullOrEmpty(resource.Type)); - Assert.False(string.IsNullOrEmpty(resource.ResourceUrl)); - }); - } + Assert.False(string.IsNullOrEmpty(resource.Type)); + Assert.False(string.IsNullOrEmpty(resource.ResourceUrl)); + }); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/FileStorageServiceTests.cs b/tests/BaGet.Core.Tests/Services/FileStorageServiceTests.cs index 2c3028142..a9f338b5d 100644 --- a/tests/BaGet.Core.Tests/Services/FileStorageServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/FileStorageServiceTests.cs @@ -8,288 +8,287 @@ using Moq; using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +public class FileStorageServiceTests { - public class FileStorageServiceTests + public class GetAsync : FactsBase { - public class GetAsync : FactsBase + [Fact] + public async Task ThrowsIfStorePathDoesNotExist() { - [Fact] - public async Task ThrowsIfStorePathDoesNotExist() - { - await Assert.ThrowsAsync(() => - _target.GetAsync("hello.txt")); - } + await Assert.ThrowsAsync(() => + _target.GetAsync("hello.txt")); + } - [Fact] - public async Task ThrowsIfFileDoesNotExist() - { - // Ensure the store path exists. - Directory.CreateDirectory(_storePath); + [Fact] + public async Task ThrowsIfFileDoesNotExist() + { + // Ensure the store path exists. + Directory.CreateDirectory(_storePath); - await Assert.ThrowsAsync(() => - _target.GetAsync("hello.txt")); + await Assert.ThrowsAsync(() => + _target.GetAsync("hello.txt")); - await Assert.ThrowsAsync(() => - _target.GetAsync("hello/world.txt")); - } + await Assert.ThrowsAsync(() => + _target.GetAsync("hello/world.txt")); + } - [Fact] - public async Task GetsStream() + [Fact] + public async Task GetsStream() + { + // Arrange + using (var content = StringStream("Hello world")) { - // Arrange - using (var content = StringStream("Hello world")) - { - await _target.PutAsync("hello.txt", content, "text/plain"); - } + await _target.PutAsync("hello.txt", content, "text/plain"); + } - // Act - var result = await _target.GetAsync("hello.txt"); + // Act + var result = await _target.GetAsync("hello.txt"); - // Assert - Assert.Equal("Hello world", await ToStringAsync(result)); - } + // Assert + Assert.Equal("Hello world", await ToStringAsync(result)); + } - [Fact] - public async Task NoAccessOutsideStorePath() + [Fact] + public async Task NoAccessOutsideStorePath() + { + foreach (var path in OutsideStorePathData) { - foreach (var path in OutsideStorePathData) - { - await Assert.ThrowsAsync(async () => - await _target.GetAsync(path)); - } + await Assert.ThrowsAsync(async () => + await _target.GetAsync(path)); } } + } - public class GetDownloadUriAsync : FactsBase + public class GetDownloadUriAsync : FactsBase + { + [Fact] + public async Task CreatesUriEvenIfDoesntExist() { - [Fact] - public async Task CreatesUriEvenIfDoesntExist() - { - var result = await _target.GetDownloadUriAsync("test.txt"); - var expected = new Uri(Path.Combine(_storePath, "test.txt")); + var result = await _target.GetDownloadUriAsync("test.txt"); + var expected = new Uri(Path.Combine(_storePath, "test.txt")); - Assert.Equal(expected, result); - } + Assert.Equal(expected, result); + } - [Fact] - public async Task NoAccessOutsideStorePath() + [Fact] + public async Task NoAccessOutsideStorePath() + { + foreach (var path in OutsideStorePathData) { - foreach (var path in OutsideStorePathData) - { - await Assert.ThrowsAsync(async () => - await _target.GetDownloadUriAsync(path)); - } + await Assert.ThrowsAsync(async () => + await _target.GetDownloadUriAsync(path)); } } + } - public class PutAsync : FactsBase + public class PutAsync : FactsBase + { + [Fact] + public async Task SavesContent() { - [Fact] - public async Task SavesContent() + StoragePutResult result; + using (var content = StringStream("Hello world")) { - StoragePutResult result; - using (var content = StringStream("Hello world")) - { - result = await _target.PutAsync("test.txt", content, "text/plain"); - } - - var path = Path.Combine(_storePath, "test.txt"); - - Assert.True(File.Exists(path)); - Assert.Equal(StoragePutResult.Success, result); - Assert.Equal("Hello world", await File.ReadAllTextAsync(path)); + result = await _target.PutAsync("test.txt", content, "text/plain"); } - [Fact] - public async Task ReturnsAlreadyExistsIfContentAlreadyExists() - { - // Arrange - var path = Path.Combine(_storePath, "test.txt"); + var path = Path.Combine(_storePath, "test.txt"); - Directory.CreateDirectory(Path.GetDirectoryName(path)); - File.WriteAllText(path, "Hello world"); + Assert.True(File.Exists(path)); + Assert.Equal(StoragePutResult.Success, result); + Assert.Equal("Hello world", await File.ReadAllTextAsync(path)); + } - StoragePutResult result; - using (var content = StringStream("Hello world")) - { - // Act - result = await _target.PutAsync("test.txt", content, "text/plain"); - } + [Fact] + public async Task ReturnsAlreadyExistsIfContentAlreadyExists() + { + // Arrange + var path = Path.Combine(_storePath, "test.txt"); - // Assert - Assert.Equal(StoragePutResult.AlreadyExists, result); - } + Directory.CreateDirectory(Path.GetDirectoryName(path)); + File.WriteAllText(path, "Hello world"); - [Fact] - public async Task ReturnsConflictIfContentAlreadyExistsButContentsDoNotMatch() + StoragePutResult result; + using (var content = StringStream("Hello world")) { - // Arrange - var path = Path.Combine(_storePath, "test.txt"); + // Act + result = await _target.PutAsync("test.txt", content, "text/plain"); + } - Directory.CreateDirectory(Path.GetDirectoryName(path)); - File.WriteAllText(path, "Hello world"); + // Assert + Assert.Equal(StoragePutResult.AlreadyExists, result); + } - StoragePutResult result; - using (var content = StringStream("foo bar")) - { - // Act - result = await _target.PutAsync("test.txt", content, "text/plain"); - } + [Fact] + public async Task ReturnsConflictIfContentAlreadyExistsButContentsDoNotMatch() + { + // Arrange + var path = Path.Combine(_storePath, "test.txt"); + + Directory.CreateDirectory(Path.GetDirectoryName(path)); + File.WriteAllText(path, "Hello world"); - // Assert - Assert.Equal(StoragePutResult.Conflict, result); + StoragePutResult result; + using (var content = StringStream("foo bar")) + { + // Act + result = await _target.PutAsync("test.txt", content, "text/plain"); } - [Fact] - public async Task NoAccessOutsideStorePath() + // Assert + Assert.Equal(StoragePutResult.Conflict, result); + } + + [Fact] + public async Task NoAccessOutsideStorePath() + { + foreach (var path in OutsideStorePathData) { - foreach (var path in OutsideStorePathData) + using (var content = StringStream("Hello world")) { - using (var content = StringStream("Hello world")) - { - await Assert.ThrowsAsync(async () => - await _target.PutAsync(path, content, "text/plain")); - } + await Assert.ThrowsAsync(async () => + await _target.PutAsync(path, content, "text/plain")); } } } + } - public class DeleteAsync : FactsBase + public class DeleteAsync : FactsBase + { + [Fact] + public async Task DoesNotThrowIfPathDoesNotExist() { - [Fact] - public async Task DoesNotThrowIfPathDoesNotExist() - { - await _target.DeleteAsync("test.txt"); - } + await _target.DeleteAsync("test.txt"); + } - [Fact] - public async Task Deletes() - { - // Arrange - var path = Path.Combine(_storePath, "test.txt"); + [Fact] + public async Task Deletes() + { + // Arrange + var path = Path.Combine(_storePath, "test.txt"); - Directory.CreateDirectory(_storePath); - await File.WriteAllTextAsync(path, "Hello world"); + Directory.CreateDirectory(_storePath); + await File.WriteAllTextAsync(path, "Hello world"); - // Act & Assert - await _target.DeleteAsync("test.txt"); + // Act & Assert + await _target.DeleteAsync("test.txt"); - Assert.False(File.Exists(path)); - } + Assert.False(File.Exists(path)); + } - [Fact] - public async Task NoAccessOutsideStorePath() + [Fact] + public async Task NoAccessOutsideStorePath() + { + foreach (var path in OutsideStorePathData) { - foreach (var path in OutsideStorePathData) - { - await Assert.ThrowsAsync(async () => - await _target.DeleteAsync(path)); - } + await Assert.ThrowsAsync(async () => + await _target.DeleteAsync(path)); } } + } - public class ListAsync : FactsBase + public class ListAsync : FactsBase + { + [Fact] + public async Task ListsEveryPathUnderThePrefix() { - [Fact] - public async Task ListsEveryPathUnderThePrefix() - { - await _target.PutAsync("staging/a.json", StringStream("a"), "application/json"); - await _target.PutAsync("staging/nested/b.json", StringStream("b"), "application/json"); - await _target.PutAsync("packages/elsewhere.nupkg", StringStream("c"), "application/octet-stream"); + await _target.PutAsync("staging/a.json", StringStream("a"), "application/json"); + await _target.PutAsync("staging/nested/b.json", StringStream("b"), "application/json"); + await _target.PutAsync("packages/elsewhere.nupkg", StringStream("c"), "application/octet-stream"); - var result = await _target.ListAsync("staging"); + var result = await _target.ListAsync("staging"); - // Store relative and "/" separated, so each path can go straight back to - // GetAsync or DeleteAsync on any platform. - Assert.Equal( - new[] { "staging/a.json", "staging/nested/b.json" }, - result.OrderBy(p => p, StringComparer.Ordinal).ToArray()); - } + // Store relative and "/" separated, so each path can go straight back to + // GetAsync or DeleteAsync on any platform. + Assert.Equal( + new[] { "staging/a.json", "staging/nested/b.json" }, + result.OrderBy(p => p, StringComparer.Ordinal).ToArray()); + } - [Fact] - public async Task IsEmptyWhenThePrefixHoldsNothing() - { - Assert.Empty(await _target.ListAsync("staging")); + [Fact] + public async Task IsEmptyWhenThePrefixHoldsNothing() + { + Assert.Empty(await _target.ListAsync("staging")); - await _target.PutAsync("packages/elsewhere.nupkg", StringStream("c"), "application/octet-stream"); + await _target.PutAsync("packages/elsewhere.nupkg", StringStream("c"), "application/octet-stream"); - Assert.Empty(await _target.ListAsync("staging")); - } + Assert.Empty(await _target.ListAsync("staging")); + } - [Fact] - public async Task NoAccessOutsideStorePath() + [Fact] + public async Task NoAccessOutsideStorePath() + { + foreach (var path in OutsideStorePathData) { - foreach (var path in OutsideStorePathData) - { - await Assert.ThrowsAsync(async () => - await _target.ListAsync(path)); - } + await Assert.ThrowsAsync(async () => + await _target.ListAsync(path)); } } + } - public class FactsBase : IDisposable + public class FactsBase : IDisposable + { + protected readonly string _storePath; + protected readonly Mock> _options; + protected readonly FileStorageService _target; + + public FactsBase() { - protected readonly string _storePath; - protected readonly Mock> _options; - protected readonly FileStorageService _target; + _storePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + _options = new Mock>(); - public FactsBase() - { - _storePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); - _options = new Mock>(); + _options + .Setup(o => o.Value) + .Returns(() => new FileSystemStorageOptions { Path = _storePath }); - _options - .Setup(o => o.Value) - .Returns(() => new FileSystemStorageOptions { Path = _storePath }); + _target = new FileStorageService(_options.Object); + } - _target = new FileStorageService(_options.Object); + public void Dispose() + { + try + { + Directory.Delete(_storePath, recursive: true); } - - public void Dispose() + catch (DirectoryNotFoundException) { - try - { - Directory.Delete(_storePath, recursive: true); - } - catch (DirectoryNotFoundException) - { - } } + } - protected Stream StringStream(string input) - { - var bytes = Encoding.ASCII.GetBytes(input); + protected Stream StringStream(string input) + { + var bytes = Encoding.ASCII.GetBytes(input); - return new MemoryStream(bytes); - } + return new MemoryStream(bytes); + } - protected async Task ToStringAsync(Stream input) + protected async Task ToStringAsync(Stream input) + { + using (var reader = new StreamReader(input)) { - using (var reader = new StreamReader(input)) - { - return await reader.ReadToEndAsync(); - } + return await reader.ReadToEndAsync(); } + } - public IEnumerable OutsideStorePathData + public IEnumerable OutsideStorePathData + { + get { - get - { - var fullPath = Path.GetFullPath(_storePath); - yield return "../file"; - yield return "."; - yield return $"../{Path.GetFileName(_storePath)}"; - yield return $"../{Path.GetFileName(_storePath)}suffix"; - yield return $"../{Path.GetFileName(_storePath)}suffix/file"; - yield return fullPath; - yield return fullPath + Path.DirectorySeparatorChar; - yield return fullPath + Path.DirectorySeparatorChar + ".."; - yield return fullPath + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + "file"; - yield return Path.GetPathRoot(_storePath); - yield return Path.Combine(Path.GetPathRoot(_storePath), "file"); - } + var fullPath = Path.GetFullPath(_storePath); + yield return "../file"; + yield return "."; + yield return $"../{Path.GetFileName(_storePath)}"; + yield return $"../{Path.GetFileName(_storePath)}suffix"; + yield return $"../{Path.GetFileName(_storePath)}suffix/file"; + yield return fullPath; + yield return fullPath + Path.DirectorySeparatorChar; + yield return fullPath + Path.DirectorySeparatorChar + ".."; + yield return fullPath + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + "file"; + yield return Path.GetPathRoot(_storePath); + yield return Path.Combine(Path.GetPathRoot(_storePath), "file"); } } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/PackageDatabaseTests.cs b/tests/BaGet.Core.Tests/Services/PackageDatabaseTests.cs index 1e5574afe..ee022e63f 100644 --- a/tests/BaGet.Core.Tests/Services/PackageDatabaseTests.cs +++ b/tests/BaGet.Core.Tests/Services/PackageDatabaseTests.cs @@ -9,460 +9,459 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +public class PackageDatabaseTests { - public class PackageDatabaseTests + public class AddAsync : FactsBase { - public class AddAsync : FactsBase + [Fact] + public async Task ReturnsPackageAlreadyExistsOnUniqueConstraintViolation() { - [Fact] - public async Task ReturnsPackageAlreadyExistsOnUniqueConstraintViolation() - { - // "Package" 1.0.0 is already in the database. - var result = await _target.AddAsync(CreatePackage("Package", "1.0.0"), Cancellation); + // "Package" 1.0.0 is already in the database. + var result = await _target.AddAsync(CreatePackage("Package", "1.0.0"), Cancellation); - Assert.Equal(PackageAddResult.PackageAlreadyExists, result); - } + Assert.Equal(PackageAddResult.PackageAlreadyExists, result); + } - [Fact] - public async Task AddsPackage() - { - var result = await _target.AddAsync(CreatePackage("New.Package", "2.0.0"), Cancellation); + [Fact] + public async Task AddsPackage() + { + var result = await _target.AddAsync(CreatePackage("New.Package", "2.0.0"), Cancellation); - Assert.Equal(PackageAddResult.Success, result); - Assert.True(await _target.ExistsAsync("New.Package", NuGetVersion.Parse("2.0.0"), Cancellation)); - } + Assert.Equal(PackageAddResult.Success, result); + Assert.True(await _target.ExistsAsync("New.Package", NuGetVersion.Parse("2.0.0"), Cancellation)); + } - [Fact] - public async Task AnotherVersionOfAnExistingPackageIsNotAConflict() - { - var result = await _target.AddAsync(CreatePackage("Package", "2.0.0"), Cancellation); + [Fact] + public async Task AnotherVersionOfAnExistingPackageIsNotAConflict() + { + var result = await _target.AddAsync(CreatePackage("Package", "2.0.0"), Cancellation); - Assert.Equal(PackageAddResult.Success, result); - } + Assert.Equal(PackageAddResult.Success, result); + } - [Fact] - public async Task StoresTheNormalizedVersion() - { - await _target.AddAsync(CreatePackage("New.Package", "1.2.3.0"), Cancellation); + [Fact] + public async Task StoresTheNormalizedVersion() + { + await _target.AddAsync(CreatePackage("New.Package", "1.2.3.0"), Cancellation); - var package = await _target.FindOrNullAsync( - "New.Package", NuGetVersion.Parse("1.2.3"), includeUnlisted: true, Cancellation); + var package = await _target.FindOrNullAsync( + "New.Package", NuGetVersion.Parse("1.2.3"), includeUnlisted: true, Cancellation); - Assert.NotNull(package); - Assert.Equal("1.2.3", package.NormalizedVersionString); - } + Assert.NotNull(package); + Assert.Equal("1.2.3", package.NormalizedVersionString); } + } - public class ExistsAsync : FactsBase + public class ExistsAsync : FactsBase + { + [Theory] + [InlineData("Package", "1.0.0", true)] + [InlineData("Package", "1.0.0.0", true)] + [InlineData("Unlisted.Package", "1.0.0", true)] + [InlineData("Fake.Package", "1.0.0", false)] + public async Task ReturnsTrueIfPackageExists(string packageId, string packageVersion, bool exists) { - [Theory] - [InlineData("Package", "1.0.0", true)] - [InlineData("Package", "1.0.0.0", true)] - [InlineData("Unlisted.Package", "1.0.0", true)] - [InlineData("Fake.Package", "1.0.0", false)] - public async Task ReturnsTrueIfPackageExists(string packageId, string packageVersion, bool exists) - { - var result = await _target.ExistsAsync( - packageId, NuGetVersion.Parse(packageVersion), Cancellation); + var result = await _target.ExistsAsync( + packageId, NuGetVersion.Parse(packageVersion), Cancellation); - Assert.Equal(exists, result); - } + Assert.Equal(exists, result); + } - [Theory] - [InlineData("Package", true)] - [InlineData("Unlisted.Package", true)] - [InlineData("Fake.Package", false)] - public async Task TheIdOnlyOverloadIgnoresTheVersion(string packageId, bool exists) - { - Assert.Equal(exists, await _target.ExistsAsync(packageId, Cancellation)); - } + [Theory] + [InlineData("Package", true)] + [InlineData("Unlisted.Package", true)] + [InlineData("Fake.Package", false)] + public async Task TheIdOnlyOverloadIgnoresTheVersion(string packageId, bool exists) + { + Assert.Equal(exists, await _target.ExistsAsync(packageId, Cancellation)); + } - [Fact] - public async Task IsFalseForAVersionThatDoesNotExist() - { - Assert.False(await _target.ExistsAsync( - "Package", NuGetVersion.Parse("9.9.9"), Cancellation)); - } + [Fact] + public async Task IsFalseForAVersionThatDoesNotExist() + { + Assert.False(await _target.ExistsAsync( + "Package", NuGetVersion.Parse("9.9.9"), Cancellation)); } + } - public class FindAsync : FactsBase + public class FindAsync : FactsBase + { + [Fact] + public async Task ReturnsEmptyListIfPackageDoesNotExist() { - [Fact] - public async Task ReturnsEmptyListIfPackageDoesNotExist() - { - var result = await _target.FindAsync("Fake.Package", includeUnlisted: true, Cancellation); + var result = await _target.FindAsync("Fake.Package", includeUnlisted: true, Cancellation); - Assert.Empty(result); - } + Assert.Empty(result); + } - [Theory] - [MemberData(nameof(ReturnsPackagesData))] - public async Task ReturnsPackages(string packageId, string packageVersion, bool includeUnlisted, bool exists) - { - var result = await _target.FindAsync(packageId, includeUnlisted, Cancellation); + [Theory] + [MemberData(nameof(ReturnsPackagesData))] + public async Task ReturnsPackages(string packageId, string packageVersion, bool includeUnlisted, bool exists) + { + var result = await _target.FindAsync(packageId, includeUnlisted, Cancellation); - var version = NuGetVersion.Parse(packageVersion).ToNormalizedString(); - Assert.Equal( - exists, - result.Any(p => p.NormalizedVersionString == version)); - } + var version = NuGetVersion.Parse(packageVersion).ToNormalizedString(); + Assert.Equal( + exists, + result.Any(p => p.NormalizedVersionString == version)); + } - [Fact] - public async Task ReturnsEveryVersionOfThePackage() - { - await _target.AddAsync(CreatePackage("Package", "2.0.0"), Cancellation); + [Fact] + public async Task ReturnsEveryVersionOfThePackage() + { + await _target.AddAsync(CreatePackage("Package", "2.0.0"), Cancellation); - var result = await _target.FindAsync("Package", includeUnlisted: true, Cancellation); + var result = await _target.FindAsync("Package", includeUnlisted: true, Cancellation); - Assert.Equal( - new[] { "1.0.0", "2.0.0" }, - result.Select(p => p.NormalizedVersionString).OrderBy(v => v)); - } + Assert.Equal( + new[] { "1.0.0", "2.0.0" }, + result.Select(p => p.NormalizedVersionString).OrderBy(v => v)); + } - [Fact] - public async Task LoadsTheRelatedCollections() - { - var result = await _target.FindAsync("Package", includeUnlisted: true, Cancellation); + [Fact] + public async Task LoadsTheRelatedCollections() + { + var result = await _target.FindAsync("Package", includeUnlisted: true, Cancellation); - var package = Assert.Single(result); - Assert.Equal("Other.Package", Assert.Single(package.Dependencies).Id); - Assert.Equal("netstandard2.0", Assert.Single(package.TargetFrameworks).Moniker); - Assert.Equal("Dependency", Assert.Single(package.PackageTypes).Name); - } + var package = Assert.Single(result); + Assert.Equal("Other.Package", Assert.Single(package.Dependencies).Id); + Assert.Equal("netstandard2.0", Assert.Single(package.TargetFrameworks).Moniker); + Assert.Equal("Dependency", Assert.Single(package.PackageTypes).Name); + } - public static IEnumerable ReturnsPackagesData() + public static IEnumerable ReturnsPackagesData() + { + object[] ReturnsPackagesHelper(string packageId, string packageVersion, bool includeUnlisted, bool exists) { - object[] ReturnsPackagesHelper(string packageId, string packageVersion, bool includeUnlisted, bool exists) - { - return new object[] { packageId, packageVersion, includeUnlisted, exists }; - } + return new object[] { packageId, packageVersion, includeUnlisted, exists }; + } - // A package that doesn't exist should never be returned - yield return ReturnsPackagesHelper("Fake.Package", "1.0.0", includeUnlisted: true, exists: false); + // A package that doesn't exist should never be returned + yield return ReturnsPackagesHelper("Fake.Package", "1.0.0", includeUnlisted: true, exists: false); - // A listed package should be returned regardless of the "includeUnlisted" parameter - yield return ReturnsPackagesHelper("Package", "1.0.0", includeUnlisted: false, exists: true); - yield return ReturnsPackagesHelper("Package", "1.0.0", includeUnlisted: true, exists: true); + // A listed package should be returned regardless of the "includeUnlisted" parameter + yield return ReturnsPackagesHelper("Package", "1.0.0", includeUnlisted: false, exists: true); + yield return ReturnsPackagesHelper("Package", "1.0.0", includeUnlisted: true, exists: true); - // The inputted package version should be normalized - yield return ReturnsPackagesHelper("Package", "1.0.0.0", includeUnlisted: false, exists: true); + // The inputted package version should be normalized + yield return ReturnsPackagesHelper("Package", "1.0.0.0", includeUnlisted: false, exists: true); - // Unlisted packages should only be returned if "includeUnlisted" is true - yield return ReturnsPackagesHelper("Unlisted.Package", "1.0.0", includeUnlisted: false, exists: false); - yield return ReturnsPackagesHelper("Unlisted.Package", "1.0.0", includeUnlisted: true, exists: true); - } + // Unlisted packages should only be returned if "includeUnlisted" is true + yield return ReturnsPackagesHelper("Unlisted.Package", "1.0.0", includeUnlisted: false, exists: false); + yield return ReturnsPackagesHelper("Unlisted.Package", "1.0.0", includeUnlisted: true, exists: true); } + } - public class FindOrNullAsync : FactsBase + public class FindOrNullAsync : FactsBase + { + [Fact] + public async Task ReturnsNullIfPackageDoesNotExist() { - [Fact] - public async Task ReturnsNullIfPackageDoesNotExist() - { - var result = await _target.FindOrNullAsync( - "Fake.Package", NuGetVersion.Parse("1.0.0"), includeUnlisted: true, Cancellation); + var result = await _target.FindOrNullAsync( + "Fake.Package", NuGetVersion.Parse("1.0.0"), includeUnlisted: true, Cancellation); - Assert.Null(result); - } + Assert.Null(result); + } - [Fact] - public async Task ReturnsNullIfTheVersionDoesNotExist() - { - var result = await _target.FindOrNullAsync( - "Package", NuGetVersion.Parse("9.9.9"), includeUnlisted: true, Cancellation); + [Fact] + public async Task ReturnsNullIfTheVersionDoesNotExist() + { + var result = await _target.FindOrNullAsync( + "Package", NuGetVersion.Parse("9.9.9"), includeUnlisted: true, Cancellation); - Assert.Null(result); - } + Assert.Null(result); + } - [Theory] - [MemberData(nameof(ReturnsPackageData))] - public async Task ReturnsPackage(string packageId, string packageVersion, bool includeUnlisted, bool exists) - { - var result = await _target.FindOrNullAsync( - packageId, NuGetVersion.Parse(packageVersion), includeUnlisted, Cancellation); + [Theory] + [MemberData(nameof(ReturnsPackageData))] + public async Task ReturnsPackage(string packageId, string packageVersion, bool includeUnlisted, bool exists) + { + var result = await _target.FindOrNullAsync( + packageId, NuGetVersion.Parse(packageVersion), includeUnlisted, Cancellation); - if (!exists) - { - Assert.Null(result); - return; - } - - Assert.NotNull(result); - Assert.Equal(packageId, result.Id); - Assert.Equal( - NuGetVersion.Parse(packageVersion).ToNormalizedString(), - result.NormalizedVersionString); + if (!exists) + { + Assert.Null(result); + return; } - [Fact] - public async Task LoadsTheDependenciesAndFrameworks() - { - var result = await _target.FindOrNullAsync( - "Package", NuGetVersion.Parse("1.0.0"), includeUnlisted: true, Cancellation); + Assert.NotNull(result); + Assert.Equal(packageId, result.Id); + Assert.Equal( + NuGetVersion.Parse(packageVersion).ToNormalizedString(), + result.NormalizedVersionString); + } - Assert.Equal("Other.Package", Assert.Single(result.Dependencies).Id); - Assert.Equal("netstandard2.0", Assert.Single(result.TargetFrameworks).Moniker); - } + [Fact] + public async Task LoadsTheDependenciesAndFrameworks() + { + var result = await _target.FindOrNullAsync( + "Package", NuGetVersion.Parse("1.0.0"), includeUnlisted: true, Cancellation); - public static IEnumerable ReturnsPackageData() + Assert.Equal("Other.Package", Assert.Single(result.Dependencies).Id); + Assert.Equal("netstandard2.0", Assert.Single(result.TargetFrameworks).Moniker); + } + + public static IEnumerable ReturnsPackageData() + { + object[] ReturnsPackageHelper(string packageId, string packageVersion, bool includeUnlisted, bool exists) { - object[] ReturnsPackageHelper(string packageId, string packageVersion, bool includeUnlisted, bool exists) - { - return new object[] { packageId, packageVersion, includeUnlisted, exists }; - } + return new object[] { packageId, packageVersion, includeUnlisted, exists }; + } - // A package that doesn't exist should never be returned - yield return ReturnsPackageHelper("Fake.Package", "1.0.0", includeUnlisted: true, exists: false); + // A package that doesn't exist should never be returned + yield return ReturnsPackageHelper("Fake.Package", "1.0.0", includeUnlisted: true, exists: false); - // A listed package should be returned regardless of the "includeUnlisted" parameter - yield return ReturnsPackageHelper("Package", "1.0.0", includeUnlisted: false, exists: true); - yield return ReturnsPackageHelper("Package", "1.0.0", includeUnlisted: true, exists: true); + // A listed package should be returned regardless of the "includeUnlisted" parameter + yield return ReturnsPackageHelper("Package", "1.0.0", includeUnlisted: false, exists: true); + yield return ReturnsPackageHelper("Package", "1.0.0", includeUnlisted: true, exists: true); - // The inputted package version should be normalized - yield return ReturnsPackageHelper("Package", "1.0.0.0", includeUnlisted: false, exists: true); + // The inputted package version should be normalized + yield return ReturnsPackageHelper("Package", "1.0.0.0", includeUnlisted: false, exists: true); - // Unlisted packages should only be returned if "includeUnlisted" is true - yield return ReturnsPackageHelper("Unlisted.Package", "1.0.0", includeUnlisted: false, exists: false); - yield return ReturnsPackageHelper("Unlisted.Package", "1.0.0", includeUnlisted: true, exists: true); - } + // Unlisted packages should only be returned if "includeUnlisted" is true + yield return ReturnsPackageHelper("Unlisted.Package", "1.0.0", includeUnlisted: false, exists: false); + yield return ReturnsPackageHelper("Unlisted.Package", "1.0.0", includeUnlisted: true, exists: true); } + } - public class UnlistPackageAsync : FactsBase + public class UnlistPackageAsync : FactsBase + { + [Fact] + public async Task ReturnsFalseIfPackageDoesNotExist() { - [Fact] - public async Task ReturnsFalseIfPackageDoesNotExist() - { - Assert.False(await _target.UnlistPackageAsync( - "Fake.Package", NuGetVersion.Parse("1.0.0"), Cancellation)); - } + Assert.False(await _target.UnlistPackageAsync( + "Fake.Package", NuGetVersion.Parse("1.0.0"), Cancellation)); + } - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task UnlistsPackage(bool listed) - { - // Unlisting is idempotent: it succeeds whatever the current state. - var id = listed ? "Package" : "Unlisted.Package"; + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task UnlistsPackage(bool listed) + { + // Unlisting is idempotent: it succeeds whatever the current state. + var id = listed ? "Package" : "Unlisted.Package"; - var result = await _target.UnlistPackageAsync(id, NuGetVersion.Parse("1.0.0"), Cancellation); + var result = await _target.UnlistPackageAsync(id, NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.True(result); - Assert.False(await IsListed(id, "1.0.0")); - } + Assert.True(result); + Assert.False(await IsListed(id, "1.0.0")); } + } - public class RelistPackageAsync : FactsBase + public class RelistPackageAsync : FactsBase + { + [Fact] + public async Task ReturnsFalseIfPackageDoesNotExist() { - [Fact] - public async Task ReturnsFalseIfPackageDoesNotExist() - { - Assert.False(await _target.RelistPackageAsync( - "Fake.Package", NuGetVersion.Parse("1.0.0"), Cancellation)); - } + Assert.False(await _target.RelistPackageAsync( + "Fake.Package", NuGetVersion.Parse("1.0.0"), Cancellation)); + } - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task RelistsPackage(bool listed) - { - // Relisting is idempotent: it succeeds whatever the current state. - var id = listed ? "Package" : "Unlisted.Package"; + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RelistsPackage(bool listed) + { + // Relisting is idempotent: it succeeds whatever the current state. + var id = listed ? "Package" : "Unlisted.Package"; - var result = await _target.RelistPackageAsync(id, NuGetVersion.Parse("1.0.0"), Cancellation); + var result = await _target.RelistPackageAsync(id, NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.True(result); - Assert.True(await IsListed(id, "1.0.0")); - } + Assert.True(result); + Assert.True(await IsListed(id, "1.0.0")); } + } - public class AddDownloadAsync : FactsBase + public class AddDownloadAsync : FactsBase + { + [Fact] + public async Task DoesNothingIfPackageDoesNotExist() { - [Fact] - public async Task DoesNothingIfPackageDoesNotExist() - { - await _target.AddDownloadAsync("Fake.Package", NuGetVersion.Parse("1.0.0"), Cancellation); + await _target.AddDownloadAsync("Fake.Package", NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.False(await _target.ExistsAsync("Fake.Package", Cancellation)); - } + Assert.False(await _target.ExistsAsync("Fake.Package", Cancellation)); + } - [Fact] - public async Task IncrementsPackageDownloads() - { - await _target.AddDownloadAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); + [Fact] + public async Task IncrementsPackageDownloads() + { + await _target.AddDownloadAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.Equal(1, await Downloads("Package", "1.0.0")); - } + Assert.Equal(1, await Downloads("Package", "1.0.0")); + } - [Fact] - public async Task IncrementsOncePerCall() - { - await _target.AddDownloadAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); - await _target.AddDownloadAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); - await _target.AddDownloadAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); + [Fact] + public async Task IncrementsOncePerCall() + { + await _target.AddDownloadAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); + await _target.AddDownloadAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); + await _target.AddDownloadAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.Equal(3, await Downloads("Package", "1.0.0")); - } + Assert.Equal(3, await Downloads("Package", "1.0.0")); + } - [Fact] - public async Task CountsAnUnlistedPackagesDownloads() - { - await _target.AddDownloadAsync("Unlisted.Package", NuGetVersion.Parse("1.0.0"), Cancellation); + [Fact] + public async Task CountsAnUnlistedPackagesDownloads() + { + await _target.AddDownloadAsync("Unlisted.Package", NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.Equal(1, await Downloads("Unlisted.Package", "1.0.0")); - } + Assert.Equal(1, await Downloads("Unlisted.Package", "1.0.0")); } + } - public class HardDeletePackageAsync : FactsBase + public class HardDeletePackageAsync : FactsBase + { + [Fact] + public async Task ReturnsFalseIfPackageDoesNotExist() { - [Fact] - public async Task ReturnsFalseIfPackageDoesNotExist() - { - Assert.False(await _target.HardDeletePackageAsync( - "Fake.Package", NuGetVersion.Parse("1.0.0"), Cancellation)); - } + Assert.False(await _target.HardDeletePackageAsync( + "Fake.Package", NuGetVersion.Parse("1.0.0"), Cancellation)); + } - [Fact] - public async Task DeletesPackage() - { - var result = await _target.HardDeletePackageAsync( - "Package", NuGetVersion.Parse("1.0.0"), Cancellation); + [Fact] + public async Task DeletesPackage() + { + var result = await _target.HardDeletePackageAsync( + "Package", NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.True(result); - Assert.False(await _target.ExistsAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation)); - } + Assert.True(result); + Assert.False(await _target.ExistsAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation)); + } - [Fact] - public async Task DeletesTheDependentRows() - { - // The rows belong to the package: they must go with it, rather than being - // left behind with a null package reference. - await _target.HardDeletePackageAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); - - var dependencies = await _context.PackageDependencies - .AsNoTracking() - .Include(d => d.Package) - .ToListAsync(); - var frameworks = await _context.TargetFrameworks - .AsNoTracking() - .Include(f => f.Package) - .ToListAsync(); - - Assert.DoesNotContain(dependencies, d => d.Package == null || d.Package.Id == "Package"); - Assert.DoesNotContain(frameworks, f => f.Package == null || f.Package.Id == "Package"); - - // The other package keeps its own rows. - Assert.Single(dependencies); - Assert.Single(frameworks); - } + [Fact] + public async Task DeletesTheDependentRows() + { + // The rows belong to the package: they must go with it, rather than being + // left behind with a null package reference. + await _target.HardDeletePackageAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); + + var dependencies = await _context.PackageDependencies + .AsNoTracking() + .Include(d => d.Package) + .ToListAsync(); + var frameworks = await _context.TargetFrameworks + .AsNoTracking() + .Include(f => f.Package) + .ToListAsync(); + + Assert.DoesNotContain(dependencies, d => d.Package == null || d.Package.Id == "Package"); + Assert.DoesNotContain(frameworks, f => f.Package == null || f.Package.Id == "Package"); + + // The other package keeps its own rows. + Assert.Single(dependencies); + Assert.Single(frameworks); + } - [Fact] - public async Task LeavesOtherPackagesAlone() - { - await _target.HardDeletePackageAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); + [Fact] + public async Task LeavesOtherPackagesAlone() + { + await _target.HardDeletePackageAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.True(await _target.ExistsAsync( - "Unlisted.Package", NuGetVersion.Parse("1.0.0"), Cancellation)); - } + Assert.True(await _target.ExistsAsync( + "Unlisted.Package", NuGetVersion.Parse("1.0.0"), Cancellation)); + } - [Fact] - public async Task DeletesOnlyTheRequestedVersion() - { - await _target.AddAsync(CreatePackage("Package", "2.0.0"), Cancellation); + [Fact] + public async Task DeletesOnlyTheRequestedVersion() + { + await _target.AddAsync(CreatePackage("Package", "2.0.0"), Cancellation); - await _target.HardDeletePackageAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); + await _target.HardDeletePackageAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation); - Assert.False(await _target.ExistsAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation)); - Assert.True(await _target.ExistsAsync("Package", NuGetVersion.Parse("2.0.0"), Cancellation)); - } + Assert.False(await _target.ExistsAsync("Package", NuGetVersion.Parse("1.0.0"), Cancellation)); + Assert.True(await _target.ExistsAsync("Package", NuGetVersion.Parse("2.0.0"), Cancellation)); } + } - public class FactsBase : IDisposable - { - protected static readonly CancellationToken Cancellation = CancellationToken.None; + public class FactsBase : IDisposable + { + protected static readonly CancellationToken Cancellation = CancellationToken.None; - private readonly SqliteConnection _connection; - protected readonly SqliteContext _context; - protected readonly PackageDatabase _target; + private readonly SqliteConnection _connection; + protected readonly SqliteContext _context; + protected readonly PackageDatabase _target; - public FactsBase() - { - // A real database, so the queries themselves are covered. - _connection = new SqliteConnection("DataSource=:memory:"); - _connection.Open(); + public FactsBase() + { + // A real database, so the queries themselves are covered. + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); - _context = new SqliteContext( - new DbContextOptionsBuilder() - .UseSqlite(_connection) - .Options); - _context.Database.EnsureCreated(); + _context = new SqliteContext( + new DbContextOptionsBuilder() + .UseSqlite(_connection) + .Options); + _context.Database.EnsureCreated(); - _context.Packages.Add(CreatePackage("Package", "1.0.0")); - _context.Packages.Add(CreatePackage("Unlisted.Package", "1.0.0", listed: false)); - _context.SaveChanges(); + _context.Packages.Add(CreatePackage("Package", "1.0.0")); + _context.Packages.Add(CreatePackage("Unlisted.Package", "1.0.0", listed: false)); + _context.SaveChanges(); - _target = new PackageDatabase(_context); - } + _target = new PackageDatabase(_context); + } - protected static Package CreatePackage(string id, string version, bool listed = true) - => new Package + protected static Package CreatePackage(string id, string version, bool listed = true) + => new Package + { + Id = id, + Version = NuGetVersion.Parse(version), + Listed = listed, + Downloads = 0, + Authors = new[] { "author" }, + Tags = new string[0], + Description = "A test package.", + Language = string.Empty, + MinClientVersion = string.Empty, + ReleaseNotes = string.Empty, + Published = DateTime.UtcNow, + SemVerLevel = SemVerLevel.Unknown, + Dependencies = new List { - Id = id, - Version = NuGetVersion.Parse(version), - Listed = listed, - Downloads = 0, - Authors = new[] { "author" }, - Tags = new string[0], - Description = "A test package.", - Language = string.Empty, - MinClientVersion = string.Empty, - ReleaseNotes = string.Empty, - Published = DateTime.UtcNow, - SemVerLevel = SemVerLevel.Unknown, - Dependencies = new List - { - new PackageDependency - { - Id = "Other.Package", - VersionRange = "[1.0.0, )", - TargetFramework = "netstandard2.0", - }, - }, - PackageTypes = new List + new PackageDependency { - new PackageType { Name = "Dependency", Version = "0.0" }, + Id = "Other.Package", + VersionRange = "[1.0.0, )", + TargetFramework = "netstandard2.0", }, - TargetFrameworks = new List - { - new TargetFramework { Moniker = "netstandard2.0" }, - }, - }; + }, + PackageTypes = new List + { + new PackageType { Name = "Dependency", Version = "0.0" }, + }, + TargetFrameworks = new List + { + new TargetFramework { Moniker = "netstandard2.0" }, + }, + }; - protected async Task IsListed(string id, string version) - { - var package = await Reread(id, version); - return package.Listed; - } + protected async Task IsListed(string id, string version) + { + var package = await Reread(id, version); + return package.Listed; + } - protected async Task Downloads(string id, string version) - { - var package = await Reread(id, version); - return package.Downloads; - } + protected async Task Downloads(string id, string version) + { + var package = await Reread(id, version); + return package.Downloads; + } - private async Task Reread(string id, string version) - { - var normalized = NuGetVersion.Parse(version).ToNormalizedString(); + private async Task Reread(string id, string version) + { + var normalized = NuGetVersion.Parse(version).ToNormalizedString(); - return await _context.Packages - .AsNoTracking() - .FirstAsync(p => p.Id == id && p.NormalizedVersionString == normalized); - } + return await _context.Packages + .AsNoTracking() + .FirstAsync(p => p.Id == id && p.NormalizedVersionString == normalized); + } - public void Dispose() - { - _context?.Dispose(); - _connection?.Dispose(); - } + public void Dispose() + { + _context?.Dispose(); + _connection?.Dispose(); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/PackageDeletionServiceTests.cs b/tests/BaGet.Core.Tests/Services/PackageDeletionServiceTests.cs index 76d1c6f98..5490b6cb3 100644 --- a/tests/BaGet.Core.Tests/Services/PackageDeletionServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/PackageDeletionServiceTests.cs @@ -6,109 +6,108 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +public class PackageDeletionServiceTests { - public class PackageDeletionServiceTests + private static readonly string PackageId = "Package"; + private static readonly NuGetVersion PackageVersion = new NuGetVersion("1.0.0"); + + private readonly Mock _packages; + private readonly Mock _storage; + + private readonly BaGetOptions _options; + private readonly PackageDeletionService _target; + + public PackageDeletionServiceTests() + { + _packages = new Mock(); + _storage = new Mock(); + _options = new BaGetOptions(); + + var optionsSnapshot = new Mock>(); + optionsSnapshot.Setup(o => o.Value).Returns(_options); + + _target = new PackageDeletionService( + _packages.Object, + _storage.Object, + optionsSnapshot.Object, + Mock.Of>()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task WhenUnlist_ReturnsTrueOnlyIfPackageExists(bool packageExists) + { + // Arrange + var cancellationToken = CancellationToken.None; + _options.PackageDeletionBehavior = PackageDeletionBehavior.Unlist; + + _packages + .Setup(p => p.UnlistPackageAsync(PackageId, PackageVersion, cancellationToken)) + .ReturnsAsync(packageExists); + + // Act + var result = await _target.TryDeletePackageAsync(PackageId, PackageVersion, cancellationToken); + + // Assert + Assert.Equal(packageExists, result); + + _packages.Verify( + p => p.UnlistPackageAsync(PackageId, PackageVersion, cancellationToken), + Times.Once); + + _packages.Verify( + p => p.HardDeletePackageAsync(It.IsAny(), It.IsAny(), It.IsAny()), + Times.Never); + _storage.Verify( + s => s.DeleteAsync(It.IsAny(), It.IsAny(), It.IsAny()), + Times.Never); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task WhenHardDelete_ReturnsTrueOnlyIfPackageExists(bool packageExists) { - private static readonly string PackageId = "Package"; - private static readonly NuGetVersion PackageVersion = new NuGetVersion("1.0.0"); - - private readonly Mock _packages; - private readonly Mock _storage; - - private readonly BaGetOptions _options; - private readonly PackageDeletionService _target; - - public PackageDeletionServiceTests() - { - _packages = new Mock(); - _storage = new Mock(); - _options = new BaGetOptions(); - - var optionsSnapshot = new Mock>(); - optionsSnapshot.Setup(o => o.Value).Returns(_options); - - _target = new PackageDeletionService( - _packages.Object, - _storage.Object, - optionsSnapshot.Object, - Mock.Of>()); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task WhenUnlist_ReturnsTrueOnlyIfPackageExists(bool packageExists) - { - // Arrange - var cancellationToken = CancellationToken.None; - _options.PackageDeletionBehavior = PackageDeletionBehavior.Unlist; - - _packages - .Setup(p => p.UnlistPackageAsync(PackageId, PackageVersion, cancellationToken)) - .ReturnsAsync(packageExists); - - // Act - var result = await _target.TryDeletePackageAsync(PackageId, PackageVersion, cancellationToken); - - // Assert - Assert.Equal(packageExists, result); - - _packages.Verify( - p => p.UnlistPackageAsync(PackageId, PackageVersion, cancellationToken), - Times.Once); - - _packages.Verify( - p => p.HardDeletePackageAsync(It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); - _storage.Verify( - s => s.DeleteAsync(It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task WhenHardDelete_ReturnsTrueOnlyIfPackageExists(bool packageExists) - { - // Arrange - _options.PackageDeletionBehavior = PackageDeletionBehavior.HardDelete; - - var step = 0; - var databaseStep = -1; - var storageStep = -1; - var cancellationToken = CancellationToken.None; - - _packages - .Setup(p => p.HardDeletePackageAsync(PackageId, PackageVersion, cancellationToken)) - .Callback(() => databaseStep = step++) - .ReturnsAsync(packageExists); - - _storage - .Setup(s => s.DeleteAsync(PackageId, PackageVersion, cancellationToken)) - .Callback(() => storageStep = step++) - .Returns(Task.CompletedTask); - - // Act - var result = await _target.TryDeletePackageAsync(PackageId, PackageVersion, cancellationToken); - - // Assert - The database step MUST happen before the storage step. - Assert.Equal(packageExists, result); - Assert.Equal(0, databaseStep); - Assert.Equal(1, storageStep); - - // The storage deletion should happen even if the package couldn't - // be found in the database. This ensures consistency. - _packages.Verify( - p => p.HardDeletePackageAsync(PackageId, PackageVersion, cancellationToken), - Times.Once); - _storage.Verify( - s => s.DeleteAsync(PackageId, PackageVersion, cancellationToken), - Times.Once); - - _packages.Verify( - p => p.UnlistPackageAsync(It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); - } + // Arrange + _options.PackageDeletionBehavior = PackageDeletionBehavior.HardDelete; + + var step = 0; + var databaseStep = -1; + var storageStep = -1; + var cancellationToken = CancellationToken.None; + + _packages + .Setup(p => p.HardDeletePackageAsync(PackageId, PackageVersion, cancellationToken)) + .Callback(() => databaseStep = step++) + .ReturnsAsync(packageExists); + + _storage + .Setup(s => s.DeleteAsync(PackageId, PackageVersion, cancellationToken)) + .Callback(() => storageStep = step++) + .Returns(Task.CompletedTask); + + // Act + var result = await _target.TryDeletePackageAsync(PackageId, PackageVersion, cancellationToken); + + // Assert - The database step MUST happen before the storage step. + Assert.Equal(packageExists, result); + Assert.Equal(0, databaseStep); + Assert.Equal(1, storageStep); + + // The storage deletion should happen even if the package couldn't + // be found in the database. This ensures consistency. + _packages.Verify( + p => p.HardDeletePackageAsync(PackageId, PackageVersion, cancellationToken), + Times.Once); + _storage.Verify( + s => s.DeleteAsync(PackageId, PackageVersion, cancellationToken), + Times.Once); + + _packages.Verify( + p => p.UnlistPackageAsync(It.IsAny(), It.IsAny(), It.IsAny()), + Times.Never); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/PackageIndexingServiceTests.cs b/tests/BaGet.Core.Tests/Services/PackageIndexingServiceTests.cs index 70c379fa5..db659d2c8 100644 --- a/tests/BaGet.Core.Tests/Services/PackageIndexingServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/PackageIndexingServiceTests.cs @@ -12,420 +12,400 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +public class PackageIndexingServiceTests { - public class PackageIndexingServiceTests + private const string PackageId = "Test.Package"; + private const string PackageVersion = "1.0.0"; + + private static readonly DateTime PublishedTime = new DateTime(2020, 1, 2, 3, 4, 5, DateTimeKind.Utc); + + private readonly Mock _packages; + private readonly Mock _storage; + private readonly Mock _search; + private readonly Mock _time; + private readonly BaGetOptions _options; + private readonly PackageIndexingService _target; + + private Package _savedPackage; + private byte[] _savedNuspec; + private byte[] _savedReadme; + private byte[] _savedIcon; + private bool _nuspecStreamWasNull; + private bool _readmeStreamWasNull; + private bool _iconStreamWasNull; + + public PackageIndexingServiceTests() + { + _packages = new Mock(); + _storage = new Mock(); + _search = new Mock(); + _time = new Mock(); + _options = new BaGetOptions(); + + _time.Setup(t => t.UtcNow).Returns(PublishedTime); + + _packages + .Setup(p => p.AddAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(PackageAddResult.Success); + + _storage + .Setup(s => s.SavePackageContentAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Callback( + (package, packageStream, nuspecStream, readmeStream, iconStream, _) => + { + // The streams are only guaranteed to be usable for the duration of the + // call, so their content is captured here instead of the streams themselves. + _savedPackage = package; + _nuspecStreamWasNull = nuspecStream == null; + _readmeStreamWasNull = readmeStream == null; + _iconStreamWasNull = iconStream == null; + _savedNuspec = ReadAllBytes(nuspecStream); + _savedReadme = ReadAllBytes(readmeStream); + _savedIcon = ReadAllBytes(iconStream); + }) + .ReturnsAsync(PackageSaveResult.Success); + + var options = new Mock>(); + options.Setup(o => o.Value).Returns(_options); + + _target = new PackageIndexingService( + _packages.Object, + _storage.Object, + _search.Object, + _time.Object, + options.Object, + Mock.Of>()); + } + + [Fact] + public async Task WhenStreamIsNotAZipArchive_ReturnsInvalidPackage() { - private const string PackageId = "Test.Package"; - private const string PackageVersion = "1.0.0"; - - private static readonly DateTime PublishedTime = new DateTime(2020, 1, 2, 3, 4, 5, DateTimeKind.Utc); - - private readonly Mock _packages; - private readonly Mock _storage; - private readonly Mock _search; - private readonly Mock _time; - private readonly BaGetOptions _options; - private readonly PackageIndexingService _target; - - private Package _savedPackage; - private byte[] _savedNuspec; - private byte[] _savedReadme; - private byte[] _savedIcon; - private bool _nuspecStreamWasNull; - private bool _readmeStreamWasNull; - private bool _iconStreamWasNull; - - public PackageIndexingServiceTests() + using (var stream = TestPackage.NotAZipArchive()) { - _packages = new Mock(); - _storage = new Mock(); - _search = new Mock(); - _time = new Mock(); - _options = new BaGetOptions(); - - _time.Setup(t => t.UtcNow).Returns(PublishedTime); - - _packages - .Setup(p => p.AddAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(PackageAddResult.Success); - - _storage - .Setup(s => s.SavePackageContentAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback( - (package, packageStream, nuspecStream, readmeStream, iconStream, _) => - { - // The streams are only guaranteed to be usable for the duration of the - // call, so their content is captured here instead of the streams themselves. - _savedPackage = package; - _nuspecStreamWasNull = nuspecStream == null; - _readmeStreamWasNull = readmeStream == null; - _iconStreamWasNull = iconStream == null; - _savedNuspec = ReadAllBytes(nuspecStream); - _savedReadme = ReadAllBytes(readmeStream); - _savedIcon = ReadAllBytes(iconStream); - }) - .ReturnsAsync(PackageSaveResult.Success); - - var options = new Mock>(); - options.Setup(o => o.Value).Returns(_options); - - _target = new PackageIndexingService( - _packages.Object, - _storage.Object, - _search.Object, - _time.Object, - options.Object, - Mock.Of>()); + var result = await _target.IndexAsync(stream, CancellationToken.None); + + Assert.Equal(PackageIndexingResult.InvalidPackage, result); + AssertNothingWasPersisted(); } + } - [Fact] - public async Task WhenStreamIsNotAZipArchive_ReturnsInvalidPackage() + [Fact] + public async Task WhenPackageHasNoNuspec_ReturnsInvalidPackage() + { + using (var stream = TestPackage.CreateWithoutNuspec( + new Dictionary { ["lib/net10.0/Test.dll"] = "not a real assembly" })) { - using (var stream = TestPackage.NotAZipArchive()) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.InvalidPackage, result); - AssertNothingWasPersisted(); - } + Assert.Equal(PackageIndexingResult.InvalidPackage, result); + AssertNothingWasPersisted(); } + } - [Fact] - public async Task WhenPackageHasNoNuspec_ReturnsInvalidPackage() + [Fact] + public async Task WhenNuspecIsNotValidXml_ReturnsInvalidPackage() + { + // The unterminated element breaks the nuspec document as a whole. + using (var stream = TestPackage.Create(" Test.Package { ["lib/net10.0/Test.dll"] = "not a real assembly" })) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.InvalidPackage, result); - AssertNothingWasPersisted(); - } + Assert.Equal(PackageIndexingResult.InvalidPackage, result); + AssertNothingWasPersisted(); } + } - [Fact] - public async Task WhenNuspecIsNotValidXml_ReturnsInvalidPackage() + [Theory] + [InlineData("id")] + [InlineData("version")] + public async Task WhenNuspecIsMissingARequiredElement_ReturnsInvalidPackage(string missingElement) + { + using (var stream = TestPackage.Create(MetadataWithout(missingElement))) { - // The unterminated element breaks the nuspec document as a whole. - using (var stream = TestPackage.Create(" Test.Packagereadme.md")) { - using (var stream = TestPackage.Create(MetadataWithout(missingElement))) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.InvalidPackage, result); - AssertNothingWasPersisted(); - } + Assert.Equal(PackageIndexingResult.InvalidPackage, result); + AssertNothingWasPersisted(); } + } - [Fact] - public async Task WhenPackageDeclaresAReadmeThatIsNotInTheArchive_ReturnsInvalidPackage() + [Theory] + [InlineData("../escaped.dll")] + [InlineData("../../escaped.dll")] + [InlineData("lib/../../escaped.dll")] + public async Task WhenPackageHasEntryThatExtractsOutsideOfExtractionPath_ReturnsInvalidPackage(string path) + { + using (var stream = TestPackage.CreateMinimal( + files: new Dictionary { [path] = "escaped" })) { - using (var stream = TestPackage.CreateMinimal(extraMetadata: " readme.md")) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.InvalidPackage, result); - AssertNothingWasPersisted(); - } + Assert.Equal(PackageIndexingResult.InvalidPackage, result); + AssertNothingWasPersisted(); } + } + + [Fact] + public async Task WhenPackageAlreadyExists_ReturnsPackageAlreadyExists() + { + _options.AllowPackageOverwrites = false; + _packages + .Setup(p => p.ExistsAsync(PackageId, NuGetVersion.Parse(PackageVersion), It.IsAny())) + .ReturnsAsync(true); - [Theory] - [InlineData("../escaped.dll")] - [InlineData("../../escaped.dll")] - [InlineData("lib/../../escaped.dll")] - public async Task WhenPackageHasEntryThatExtractsOutsideOfExtractionPath_ReturnsInvalidPackage(string path) + using (var stream = TestPackage.CreateMinimal()) { - using (var stream = TestPackage.CreateMinimal( - files: new Dictionary { [path] = "escaped" })) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.InvalidPackage, result); - AssertNothingWasPersisted(); - } + Assert.Equal(PackageIndexingResult.PackageAlreadyExists, result); + AssertNothingWasPersisted(); + _packages.Verify( + p => p.HardDeletePackageAsync( + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Never); } + } - [Fact] - public async Task WhenPackageAlreadyExists_ReturnsPackageAlreadyExists() + [Fact] + public async Task WhenPackageAlreadyExistsAndOverwritesAreAllowed_DeletesTheExistingPackageAndIndexes() + { + _options.AllowPackageOverwrites = true; + _packages + .Setup(p => p.ExistsAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(true); + + using (var stream = TestPackage.CreateMinimal()) { - _options.AllowPackageOverwrites = false; - _packages - .Setup(p => p.ExistsAsync(PackageId, NuGetVersion.Parse(PackageVersion), It.IsAny())) - .ReturnsAsync(true); + var result = await _target.IndexAsync(stream, CancellationToken.None); - using (var stream = TestPackage.CreateMinimal()) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); - - Assert.Equal(PackageIndexingResult.PackageAlreadyExists, result); - AssertNothingWasPersisted(); - _packages.Verify( - p => p.HardDeletePackageAsync( - It.IsAny(), - It.IsAny(), - It.IsAny()), - Times.Never); - } + Assert.Equal(PackageIndexingResult.Success, result); + _packages.Verify( + p => p.HardDeletePackageAsync( + PackageId, + NuGetVersion.Parse(PackageVersion), + It.IsAny()), + Times.Once); + _storage.Verify( + s => s.DeleteAsync( + PackageId, + NuGetVersion.Parse(PackageVersion), + It.IsAny()), + Times.Once); } + } + + [Fact] + public async Task WhenDatabaseAddFailsBecausePackageAlreadyExists_ReturnsPackageAlreadyExists() + { + _packages + .Setup(p => p.AddAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(PackageAddResult.PackageAlreadyExists); - [Fact] - public async Task WhenPackageAlreadyExistsAndOverwritesAreAllowed_DeletesTheExistingPackageAndIndexes() + using (var stream = TestPackage.CreateMinimal()) { - _options.AllowPackageOverwrites = true; - _packages - .Setup(p => p.ExistsAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .ReturnsAsync(true); + var result = await _target.IndexAsync(stream, CancellationToken.None); - using (var stream = TestPackage.CreateMinimal()) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); - - Assert.Equal(PackageIndexingResult.Success, result); - _packages.Verify( - p => p.HardDeletePackageAsync( - PackageId, - NuGetVersion.Parse(PackageVersion), - It.IsAny()), - Times.Once); - _storage.Verify( - s => s.DeleteAsync( - PackageId, - NuGetVersion.Parse(PackageVersion), - It.IsAny()), - Times.Once); - } + Assert.Equal(PackageIndexingResult.PackageAlreadyExists, result); + _search.Verify( + s => s.IndexAsync(It.IsAny(), It.IsAny()), + Times.Never); } + } - [Fact] - public async Task WhenDatabaseAddFailsBecausePackageAlreadyExists_ReturnsPackageAlreadyExists() - { - _packages - .Setup(p => p.AddAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(PackageAddResult.PackageAlreadyExists); + [Fact] + public async Task WhenDatabaseAddReturnsAnUnknownResult_Throws() + { + _packages + .Setup(p => p.AddAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync((PackageAddResult)int.MaxValue); - using (var stream = TestPackage.CreateMinimal()) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + using (var stream = TestPackage.CreateMinimal()) + { + await Assert.ThrowsAsync( + () => _target.IndexAsync(stream, CancellationToken.None)); - Assert.Equal(PackageIndexingResult.PackageAlreadyExists, result); - _search.Verify( - s => s.IndexAsync(It.IsAny(), It.IsAny()), - Times.Never); - } + _search.Verify( + s => s.IndexAsync(It.IsAny(), It.IsAny()), + Times.Never); } + } - [Fact] - public async Task WhenDatabaseAddReturnsAnUnknownResult_Throws() + [Fact] + public async Task IndexesPackage() + { + using (var stream = TestPackage.CreateMinimal(id: "My.Package", version: "1.2.3-beta.1")) { - _packages - .Setup(p => p.AddAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync((PackageAddResult)int.MaxValue); + var expectedNuspec = ReadEntry(stream, TestPackage.NuspecPath); - using (var stream = TestPackage.CreateMinimal()) - { - await Assert.ThrowsAsync( - () => _target.IndexAsync(stream, CancellationToken.None)); + var result = await _target.IndexAsync(stream, CancellationToken.None); - _search.Verify( - s => s.IndexAsync(It.IsAny(), It.IsAny()), - Times.Never); - } - } + Assert.Equal(PackageIndexingResult.Success, result); - [Fact] - public async Task IndexesPackage() - { - using (var stream = TestPackage.CreateMinimal(id: "My.Package", version: "1.2.3-beta.1")) - { - var expectedNuspec = ReadEntry(stream, TestPackage.NuspecPath); - - var result = await _target.IndexAsync(stream, CancellationToken.None); - - Assert.Equal(PackageIndexingResult.Success, result); - - Assert.NotNull(_savedPackage); - Assert.Equal("My.Package", _savedPackage.Id); - Assert.Equal(NuGetVersion.Parse("1.2.3-beta.1"), _savedPackage.Version); - Assert.True(_savedPackage.IsPrerelease); - Assert.Equal(PublishedTime, _savedPackage.Published); - Assert.False(_nuspecStreamWasNull); - Assert.Equal(expectedNuspec, _savedNuspec); - - _packages.Verify( - p => p.AddAsync( - It.Is(x => x.Id == "My.Package" && x.Published == PublishedTime), - It.IsAny()), - Times.Once); - _search.Verify( - s => s.IndexAsync( - It.Is(x => x.Id == "My.Package"), - It.IsAny()), - Times.Once); - } + Assert.NotNull(_savedPackage); + Assert.Equal("My.Package", _savedPackage.Id); + Assert.Equal(NuGetVersion.Parse("1.2.3-beta.1"), _savedPackage.Version); + Assert.True(_savedPackage.IsPrerelease); + Assert.Equal(PublishedTime, _savedPackage.Published); + Assert.False(_nuspecStreamWasNull); + Assert.Equal(expectedNuspec, _savedNuspec); + + _packages.Verify( + p => p.AddAsync( + It.Is(x => x.Id == "My.Package" && x.Published == PublishedTime), + It.IsAny()), + Times.Once); + _search.Verify( + s => s.IndexAsync( + It.Is(x => x.Id == "My.Package"), + It.IsAny()), + Times.Once); } + } - [Fact] - public async Task SavesThePackageStreamFromItsBeginning() - { - byte[] actual = null; - long positionAtSave = -1; - - _storage - .Setup(s => s.SavePackageContentAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback( - (_, packageStream, __, ___, ____, _____) => + [Fact] + public async Task SavesThePackageStreamFromItsBeginning() + { + byte[] actual = null; + long positionAtSave = -1; + + _storage + .Setup(s => s.SavePackageContentAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Callback( + (_, packageStream, __, ___, ____, _____) => + { + positionAtSave = packageStream.Position; + + // Copied from wherever the service left the stream, not from the beginning. + using (var buffer = new MemoryStream()) { - positionAtSave = packageStream.Position; - - // Copied from wherever the service left the stream, not from the beginning. - using (var buffer = new MemoryStream()) - { - packageStream.CopyTo(buffer); - actual = buffer.ToArray(); - } - }) - .ReturnsAsync(PackageSaveResult.Success); - - using (var stream = TestPackage.CreateMinimal()) - { - var expected = stream.ToArray(); + packageStream.CopyTo(buffer); + actual = buffer.ToArray(); + } + }) + .ReturnsAsync(PackageSaveResult.Success); - // Leave the stream at its end: the service is responsible for rewinding it. - stream.Position = stream.Length; + using (var stream = TestPackage.CreateMinimal()) + { + var expected = stream.ToArray(); - var result = await _target.IndexAsync(stream, CancellationToken.None); + // Leave the stream at its end: the service is responsible for rewinding it. + stream.Position = stream.Length; - Assert.Equal(PackageIndexingResult.Success, result); - Assert.Equal(0, positionAtSave); - Assert.Equal(expected, actual); - } + var result = await _target.IndexAsync(stream, CancellationToken.None); + + Assert.Equal(PackageIndexingResult.Success, result); + Assert.Equal(0, positionAtSave); + Assert.Equal(expected, actual); } + } - [Fact] - public async Task WhenPackageHasNoReadme_SavesNullReadmeStream() + [Fact] + public async Task WhenPackageHasNoReadme_SavesNullReadmeStream() + { + using (var stream = TestPackage.CreateMinimal()) { - using (var stream = TestPackage.CreateMinimal()) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.Success, result); - Assert.False(_savedPackage.HasReadme); - Assert.True(_readmeStreamWasNull); - Assert.Null(_savedReadme); - } + Assert.Equal(PackageIndexingResult.Success, result); + Assert.False(_savedPackage.HasReadme); + Assert.True(_readmeStreamWasNull); + Assert.Null(_savedReadme); } + } - [Fact] - public async Task WhenPackageHasReadme_SavesReadmeStream() + [Fact] + public async Task WhenPackageHasReadme_SavesReadmeStream() + { + using (var stream = TestPackage.CreateMinimal( + extraMetadata: " docs/readme.md", + files: new Dictionary { ["docs/readme.md"] = "# Hello" })) { - using (var stream = TestPackage.CreateMinimal( - extraMetadata: " docs/readme.md", - files: new Dictionary { ["docs/readme.md"] = "# Hello" })) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.Success, result); - Assert.True(_savedPackage.HasReadme); - Assert.False(_readmeStreamWasNull); - Assert.Equal("# Hello", Encoding.UTF8.GetString(_savedReadme)); - } + Assert.Equal(PackageIndexingResult.Success, result); + Assert.True(_savedPackage.HasReadme); + Assert.False(_readmeStreamWasNull); + Assert.Equal("# Hello", Encoding.UTF8.GetString(_savedReadme)); } + } - [Fact] - public async Task WhenPackageHasNoEmbeddedIcon_SavesNullIconStream() + [Fact] + public async Task WhenPackageHasNoEmbeddedIcon_SavesNullIconStream() + { + using (var stream = TestPackage.CreateMinimal()) { - using (var stream = TestPackage.CreateMinimal()) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.Success, result); - Assert.False(_savedPackage.HasEmbeddedIcon); - Assert.True(_iconStreamWasNull); - Assert.Null(_savedIcon); - } + Assert.Equal(PackageIndexingResult.Success, result); + Assert.False(_savedPackage.HasEmbeddedIcon); + Assert.True(_iconStreamWasNull); + Assert.Null(_savedIcon); } + } - [Fact] - public async Task WhenPackageHasEmbeddedIcon_SavesIconStream() + [Fact] + public async Task WhenPackageHasEmbeddedIcon_SavesIconStream() + { + using (var stream = TestPackage.CreateMinimal( + extraMetadata: " images/icon.png", + files: new Dictionary { ["images/icon.png"] = "icon content" })) { - using (var stream = TestPackage.CreateMinimal( - extraMetadata: " images/icon.png", - files: new Dictionary { ["images/icon.png"] = "icon content" })) - { - var result = await _target.IndexAsync(stream, CancellationToken.None); + var result = await _target.IndexAsync(stream, CancellationToken.None); - Assert.Equal(PackageIndexingResult.Success, result); - Assert.True(_savedPackage.HasEmbeddedIcon); - Assert.False(_iconStreamWasNull); - Assert.Equal("icon content", Encoding.UTF8.GetString(_savedIcon)); - } + Assert.Equal(PackageIndexingResult.Success, result); + Assert.True(_savedPackage.HasEmbeddedIcon); + Assert.False(_iconStreamWasNull); + Assert.Equal("icon content", Encoding.UTF8.GetString(_savedIcon)); } + } - [Fact] - public async Task ThrowsWhenStorageSaveThrows() + [Fact] + public async Task ThrowsWhenStorageSaveThrows() + { + _storage + .Setup(s => s.SavePackageContentAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Concurrent push")); + + using (var stream = TestPackage.CreateMinimal()) { - _storage - .Setup(s => s.SavePackageContentAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .ThrowsAsync(new InvalidOperationException("Concurrent push")); - - using (var stream = TestPackage.CreateMinimal()) - { - var exception = await Assert.ThrowsAsync( - () => _target.IndexAsync(stream, CancellationToken.None)); - - Assert.Equal("Concurrent push", exception.Message); - _packages.Verify( - p => p.AddAsync(It.IsAny(), It.IsAny()), - Times.Never); - _search.Verify( - s => s.IndexAsync(It.IsAny(), It.IsAny()), - Times.Never); - } - } + var exception = await Assert.ThrowsAsync( + () => _target.IndexAsync(stream, CancellationToken.None)); - private void AssertNothingWasPersisted() - { - _storage.Verify( - s => s.SavePackageContentAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny()), - Times.Never); + Assert.Equal("Concurrent push", exception.Message); _packages.Verify( p => p.AddAsync(It.IsAny(), It.IsAny()), Times.Never); @@ -433,53 +413,72 @@ private void AssertNothingWasPersisted() s => s.IndexAsync(It.IsAny(), It.IsAny()), Times.Never); } + } - private static string MetadataWithout(string element) - { - var metadata = new StringBuilder(); + private void AssertNothingWasPersisted() + { + _storage.Verify( + s => s.SavePackageContentAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Never); + _packages.Verify( + p => p.AddAsync(It.IsAny(), It.IsAny()), + Times.Never); + _search.Verify( + s => s.IndexAsync(It.IsAny(), It.IsAny()), + Times.Never); + } - if (element != "id") metadata.AppendLine($" {PackageId}"); - if (element != "version") metadata.AppendLine($" {PackageVersion}"); - if (element != "authors") metadata.AppendLine(" Test Author"); - if (element != "description") metadata.AppendLine(" A test package."); + private static string MetadataWithout(string element) + { + var metadata = new StringBuilder(); - return metadata.ToString(); - } + if (element != "id") metadata.AppendLine($" {PackageId}"); + if (element != "version") metadata.AppendLine($" {PackageVersion}"); + if (element != "authors") metadata.AppendLine(" Test Author"); + if (element != "description") metadata.AppendLine(" A test package."); - private static byte[] ReadEntry(MemoryStream packageStream, string path) - { - var position = packageStream.Position; + return metadata.ToString(); + } - try - { - packageStream.Position = 0; + private static byte[] ReadEntry(MemoryStream packageStream, string path) + { + var position = packageStream.Position; - using (var archive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true)) - using (var entry = archive.GetEntry(path).Open()) - { - return ReadAllBytes(entry); - } - } - finally + try + { + packageStream.Position = 0; + + using (var archive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true)) + using (var entry = archive.GetEntry(path).Open()) { - packageStream.Position = position; + return ReadAllBytes(entry); } } - - private static byte[] ReadAllBytes(Stream stream) + finally { - if (stream == null) return null; + packageStream.Position = position; + } + } - if (stream.CanSeek) - { - stream.Position = 0; - } + private static byte[] ReadAllBytes(Stream stream) + { + if (stream == null) return null; - using (var buffer = new MemoryStream()) - { - stream.CopyTo(buffer); - return buffer.ToArray(); - } + if (stream.CanSeek) + { + stream.Position = 0; + } + + using (var buffer = new MemoryStream()) + { + stream.CopyTo(buffer); + return buffer.ToArray(); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/PackageServiceTests.cs b/tests/BaGet.Core.Tests/Services/PackageServiceTests.cs index 8bbcb1d94..2d1937188 100644 --- a/tests/BaGet.Core.Tests/Services/PackageServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/PackageServiceTests.cs @@ -9,379 +9,378 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests +namespace BaGet.Core.Tests; + +public class PackageServiceTests { - public class PackageServiceTests + public class FindPackageVersionsAsync : FactsBase { - public class FindPackageVersionsAsync : FactsBase + [Fact] + public async Task ReturnsEmpty() + { + Setup(); + + var results = await _target.FindPackageVersionsAsync( + "MyPackage", + _cancellationToken); + + Assert.Empty(results); + } + + [Fact] + public async Task ReturnsLocalVersions() { - [Fact] - public async Task ReturnsEmpty() + Setup(localPackages: new List { - Setup(); + new Package { Version = new NuGetVersion("1.0.0") }, + new Package { Version = new NuGetVersion("2.0.0") }, + }); - var results = await _target.FindPackageVersionsAsync( - "MyPackage", - _cancellationToken); + var results = await _target.FindPackageVersionsAsync( + "MyPackage", + _cancellationToken); - Assert.Empty(results); - } + Assert.Equal(2, results.Count); + Assert.Equal("1.0.0", results[0].OriginalVersion); + Assert.Equal("2.0.0", results[1].OriginalVersion); + } - [Fact] - public async Task ReturnsLocalVersions() + [Fact] + public async Task ReturnsUpstreamVersions() + { + Setup(upstreamPackages: new List { - Setup(localPackages: new List + new NuGetVersion("1.0.0"), + new NuGetVersion("2.0.0"), + }); + + var results = await _target.FindPackageVersionsAsync( + "MyPackage", + _cancellationToken); + + Assert.Equal(2, results.Count); + Assert.Equal("1.0.0", results[0].OriginalVersion); + Assert.Equal("2.0.0", results[1].OriginalVersion); + } + + [Fact] + public async Task MergesLocalAndUpstreamVersions() + { + Setup( + localPackages: new List { new Package { Version = new NuGetVersion("1.0.0") }, new Package { Version = new NuGetVersion("2.0.0") }, + }, + upstreamPackages: new List + { + new NuGetVersion("2.0.0"), + new NuGetVersion("3.0.0"), }); - var results = await _target.FindPackageVersionsAsync( - "MyPackage", - _cancellationToken); + var results = await _target.FindPackageVersionsAsync( + "MyPackage", + _cancellationToken); - Assert.Equal(2, results.Count); - Assert.Equal("1.0.0", results[0].OriginalVersion); - Assert.Equal("2.0.0", results[1].OriginalVersion); - } + var ordered = results.OrderBy(v => v).ToList(); - [Fact] - public async Task ReturnsUpstreamVersions() - { - Setup(upstreamPackages: new List - { - new NuGetVersion("1.0.0"), - new NuGetVersion("2.0.0"), - }); + Assert.Equal(3, ordered.Count); + Assert.Equal("1.0.0", ordered[0].OriginalVersion); + Assert.Equal("2.0.0", ordered[1].OriginalVersion); + Assert.Equal("3.0.0", ordered[2].OriginalVersion); + } - var results = await _target.FindPackageVersionsAsync( - "MyPackage", - _cancellationToken); + private void Setup( + IReadOnlyList localPackages = null, + IReadOnlyList upstreamPackages = null) + { + localPackages = localPackages ?? new List(); + upstreamPackages = upstreamPackages ?? new List(); - Assert.Equal(2, results.Count); - Assert.Equal("1.0.0", results[0].OriginalVersion); - Assert.Equal("2.0.0", results[1].OriginalVersion); - } + _db + .Setup(p => p.FindAsync( + "MyPackage", + /*includeUnlisted: */ true, + _cancellationToken)) + .ReturnsAsync(localPackages); - [Fact] - public async Task MergesLocalAndUpstreamVersions() - { - Setup( - localPackages: new List - { - new Package { Version = new NuGetVersion("1.0.0") }, - new Package { Version = new NuGetVersion("2.0.0") }, - }, - upstreamPackages: new List - { - new NuGetVersion("2.0.0"), - new NuGetVersion("3.0.0"), - }); - - var results = await _target.FindPackageVersionsAsync( + _upstream + .Setup(u => u.ListPackageVersionsAsync( "MyPackage", - _cancellationToken); + _cancellationToken)) + .ReturnsAsync(upstreamPackages); + } + } - var ordered = results.OrderBy(v => v).ToList(); + public class FindPackagesAsync : FactsBase + { + [Fact] + public async Task ReturnsEmpty() + { + Setup(); - Assert.Equal(3, ordered.Count); - Assert.Equal("1.0.0", ordered[0].OriginalVersion); - Assert.Equal("2.0.0", ordered[1].OriginalVersion); - Assert.Equal("3.0.0", ordered[2].OriginalVersion); - } + var results = await _target.FindPackagesAsync("MyPackage", _cancellationToken); - private void Setup( - IReadOnlyList localPackages = null, - IReadOnlyList upstreamPackages = null) + Assert.Empty(results); + } + + [Fact] + public async Task ReturnsLocalPackages() + { + Setup(localPackages: new List { - localPackages = localPackages ?? new List(); - upstreamPackages = upstreamPackages ?? new List(); + new Package { Version = new NuGetVersion("1.0.0") }, + new Package { Version = new NuGetVersion("2.0.0") }, + }); - _db - .Setup(p => p.FindAsync( - "MyPackage", - /*includeUnlisted: */ true, - _cancellationToken)) - .ReturnsAsync(localPackages); + var results = await _target.FindPackagesAsync("MyPackage", _cancellationToken); - _upstream - .Setup(u => u.ListPackageVersionsAsync( - "MyPackage", - _cancellationToken)) - .ReturnsAsync(upstreamPackages); - } + Assert.Equal(2, results.Count); + Assert.Equal("1.0.0", results[0].Version.OriginalVersion); + Assert.Equal("2.0.0", results[1].Version.OriginalVersion); } - public class FindPackagesAsync : FactsBase + [Fact] + public async Task ReturnsUpstreamPackages() { - [Fact] - public async Task ReturnsEmpty() + Setup(upstreamPackages: new List { - Setup(); + new Package { Version = new NuGetVersion("1.0.0") }, + new Package { Version = new NuGetVersion("2.0.0") }, + }); - var results = await _target.FindPackagesAsync("MyPackage", _cancellationToken); + var results = await _target.FindPackagesAsync("MyPackage", _cancellationToken); - Assert.Empty(results); - } + Assert.Equal(2, results.Count); + Assert.Equal("1.0.0", results[0].Version.OriginalVersion); + Assert.Equal("2.0.0", results[1].Version.OriginalVersion); + } - [Fact] - public async Task ReturnsLocalPackages() - { - Setup(localPackages: new List + [Fact] + public async Task MergesLocalAndUpstreamPackages() + { + Setup( + localPackages: new List { new Package { Version = new NuGetVersion("1.0.0") }, new Package { Version = new NuGetVersion("2.0.0") }, + }, + upstreamPackages: new List + { + new Package { Version = new NuGetVersion("2.0.0") }, + new Package { Version = new NuGetVersion("3.0.0") }, }); - var results = await _target.FindPackagesAsync("MyPackage", _cancellationToken); + var results = await _target.FindPackagesAsync("MyPackage", _cancellationToken); + var ordered = results.OrderBy(p => p.Version).ToList(); - Assert.Equal(2, results.Count); - Assert.Equal("1.0.0", results[0].Version.OriginalVersion); - Assert.Equal("2.0.0", results[1].Version.OriginalVersion); - } + Assert.Equal(3, ordered.Count); + Assert.Equal("1.0.0", ordered[0].Version.OriginalVersion); + Assert.Equal("2.0.0", ordered[1].Version.OriginalVersion); + Assert.Equal("3.0.0", ordered[2].Version.OriginalVersion); + } - [Fact] - public async Task ReturnsUpstreamPackages() - { - Setup(upstreamPackages: new List - { - new Package { Version = new NuGetVersion("1.0.0") }, - new Package { Version = new NuGetVersion("2.0.0") }, - }); + private void Setup( + IReadOnlyList localPackages = null, + IReadOnlyList upstreamPackages = null) + { + localPackages = localPackages ?? new List(); + upstreamPackages = upstreamPackages ?? new List(); - var results = await _target.FindPackagesAsync("MyPackage", _cancellationToken); + _db + .Setup(p => p.FindAsync( + "MyPackage", + /*includeUnlisted: */ true, + _cancellationToken)) + .ReturnsAsync(localPackages); - Assert.Equal(2, results.Count); - Assert.Equal("1.0.0", results[0].Version.OriginalVersion); - Assert.Equal("2.0.0", results[1].Version.OriginalVersion); - } + _upstream + .Setup(u => u.ListPackagesAsync( + "MyPackage", + _cancellationToken)) + .ReturnsAsync(upstreamPackages); + } + } - [Fact] - public async Task MergesLocalAndUpstreamPackages() - { - Setup( - localPackages: new List - { - new Package { Version = new NuGetVersion("1.0.0") }, - new Package { Version = new NuGetVersion("2.0.0") }, - }, - upstreamPackages: new List - { - new Package { Version = new NuGetVersion("2.0.0") }, - new Package { Version = new NuGetVersion("3.0.0") }, - }); - - var results = await _target.FindPackagesAsync("MyPackage", _cancellationToken); - var ordered = results.OrderBy(p => p.Version).ToList(); - - Assert.Equal(3, ordered.Count); - Assert.Equal("1.0.0", ordered[0].Version.OriginalVersion); - Assert.Equal("2.0.0", ordered[1].Version.OriginalVersion); - Assert.Equal("3.0.0", ordered[2].Version.OriginalVersion); - } + public class FindPackageOrNullAsync : MirrorAsync + { + protected override async Task TargetAsync() + => await _target.FindPackageOrNullAsync(_id, _version, _cancellationToken); - private void Setup( - IReadOnlyList localPackages = null, - IReadOnlyList upstreamPackages = null) - { - localPackages = localPackages ?? new List(); - upstreamPackages = upstreamPackages ?? new List(); + [Fact] + public async Task ExistsInDatabase() + { + var expected = new Package(); - _db - .Setup(p => p.FindAsync( - "MyPackage", - /*includeUnlisted: */ true, - _cancellationToken)) - .ReturnsAsync(localPackages); + _db + .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) + .ReturnsAsync(true); + _db + .Setup(p => p.FindOrNullAsync(_id, _version, /*includeUnlisted:*/ true, _cancellationToken)) + .ReturnsAsync(expected); - _upstream - .Setup(u => u.ListPackagesAsync( - "MyPackage", - _cancellationToken)) - .ReturnsAsync(upstreamPackages); - } + var result = await _target.FindPackageOrNullAsync(_id, _version, _cancellationToken); + + Assert.Same(expected, result); } - public class FindPackageOrNullAsync : MirrorAsync + [Fact] + public async Task DoesNotExistInDatabase() { - protected override async Task TargetAsync() - => await _target.FindPackageOrNullAsync(_id, _version, _cancellationToken); - - [Fact] - public async Task ExistsInDatabase() - { - var expected = new Package(); + _db + .Setup(p => p.FindOrNullAsync(_id, _version, /*includeUnlisted:*/ true, _cancellationToken)) + .ReturnsAsync((Package)null); - _db - .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) - .ReturnsAsync(true); - _db - .Setup(p => p.FindOrNullAsync(_id, _version, /*includeUnlisted:*/ true, _cancellationToken)) - .ReturnsAsync(expected); + var result = await _target.FindPackageOrNullAsync(_id, _version, _cancellationToken); - var result = await _target.FindPackageOrNullAsync(_id, _version, _cancellationToken); + Assert.Null(result); + } + } - Assert.Same(expected, result); - } + public class ExistsAsync : MirrorAsync + { + protected override async Task TargetAsync() => await _target.ExistsAsync(_id, _version, _cancellationToken); - [Fact] - public async Task DoesNotExistInDatabase() - { - _db - .Setup(p => p.FindOrNullAsync(_id, _version, /*includeUnlisted:*/ true, _cancellationToken)) - .ReturnsAsync((Package)null); + [Fact] + public async Task ExistsInDatabase() + { + _db + .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) + .ReturnsAsync(true); - var result = await _target.FindPackageOrNullAsync(_id, _version, _cancellationToken); + var result = await _target.ExistsAsync(_id, _version, _cancellationToken); - Assert.Null(result); - } + Assert.True(result); } - public class ExistsAsync : MirrorAsync + [Fact] + public async Task DoesNotExistInDatabase() { - protected override async Task TargetAsync() => await _target.ExistsAsync(_id, _version, _cancellationToken); + _db + .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) + .ReturnsAsync(false); - [Fact] - public async Task ExistsInDatabase() - { - _db - .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) - .ReturnsAsync(true); + var result = await _target.ExistsAsync(_id, _version, _cancellationToken); - var result = await _target.ExistsAsync(_id, _version, _cancellationToken); + Assert.False(result); + } + } - Assert.True(result); - } + public abstract class MirrorAsync : FactsBase + { + protected readonly string _id = "MyPackage"; + protected readonly NuGetVersion _version = new NuGetVersion("1.0.0"); - [Fact] - public async Task DoesNotExistInDatabase() - { - _db - .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) - .ReturnsAsync(false); + protected abstract Task TargetAsync(); - var result = await _target.ExistsAsync(_id, _version, _cancellationToken); + [Fact] + public async Task SkipsIfAlreadyMirrored() + { + _db + .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) + .ReturnsAsync(true); - Assert.False(result); - } + await TargetAsync(); + + _indexer.Verify( + i => i.IndexAsync(It.IsAny(), _cancellationToken), + Times.Never); } - public abstract class MirrorAsync : FactsBase + [Fact] + public async Task SkipsIfUpstreamDoesntHavePackage() { - protected readonly string _id = "MyPackage"; - protected readonly NuGetVersion _version = new NuGetVersion("1.0.0"); + _db + .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) + .ReturnsAsync(false); - protected abstract Task TargetAsync(); + _upstream + .Setup(u => u.DownloadPackageOrNullAsync(_id, _version, _cancellationToken)) + .ReturnsAsync((Stream)null); - [Fact] - public async Task SkipsIfAlreadyMirrored() - { - _db - .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) - .ReturnsAsync(true); + await TargetAsync(); - await TargetAsync(); + _indexer.Verify( + i => i.IndexAsync(It.IsAny(), _cancellationToken), + Times.Never); + } - _indexer.Verify( - i => i.IndexAsync(It.IsAny(), _cancellationToken), - Times.Never); - } + [Fact] + public async Task SkipsIfUpstreamThrows() + { + _db + .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) + .ReturnsAsync(false); - [Fact] - public async Task SkipsIfUpstreamDoesntHavePackage() - { - _db - .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) - .ReturnsAsync(false); + _upstream + .Setup(u => u.DownloadPackageOrNullAsync(_id, _version, _cancellationToken)) + .ThrowsAsync(new InvalidOperationException("Hello world")); - _upstream - .Setup(u => u.DownloadPackageOrNullAsync(_id, _version, _cancellationToken)) - .ReturnsAsync((Stream)null); + await TargetAsync(); - await TargetAsync(); + _indexer.Verify( + i => i.IndexAsync(It.IsAny(), _cancellationToken), + Times.Never); + } - _indexer.Verify( - i => i.IndexAsync(It.IsAny(), _cancellationToken), - Times.Never); - } + [Fact] + public async Task MirrorsPackage() + { + _db + .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) + .ReturnsAsync(false); - [Fact] - public async Task SkipsIfUpstreamThrows() + using (var downloadStream = new MemoryStream()) { - _db - .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) - .ReturnsAsync(false); - _upstream .Setup(u => u.DownloadPackageOrNullAsync(_id, _version, _cancellationToken)) - .ThrowsAsync(new InvalidOperationException("Hello world")); + .ReturnsAsync(downloadStream); await TargetAsync(); _indexer.Verify( i => i.IndexAsync(It.IsAny(), _cancellationToken), - Times.Never); - } - - [Fact] - public async Task MirrorsPackage() - { - _db - .Setup(p => p.ExistsAsync(_id, _version, _cancellationToken)) - .ReturnsAsync(false); - - using (var downloadStream = new MemoryStream()) - { - _upstream - .Setup(u => u.DownloadPackageOrNullAsync(_id, _version, _cancellationToken)) - .ReturnsAsync(downloadStream); - - await TargetAsync(); - - _indexer.Verify( - i => i.IndexAsync(It.IsAny(), _cancellationToken), - Times.Once); - } + Times.Once); } } + } - public class AddDownloadAsync : FactsBase + public class AddDownloadAsync : FactsBase + { + [Fact] + public async Task AddsDownload() { - [Fact] - public async Task AddsDownload() - { - var id = "Hello"; - var version = new NuGetVersion("1.2.3"); + var id = "Hello"; + var version = new NuGetVersion("1.2.3"); - await _target.AddDownloadAsync(id, version, _cancellationToken); + await _target.AddDownloadAsync(id, version, _cancellationToken); - _db.Verify( - db => db.AddDownloadAsync(id, version, _cancellationToken), - Times.Once); - } + _db.Verify( + db => db.AddDownloadAsync(id, version, _cancellationToken), + Times.Once); } + } - public class FactsBase - { - protected readonly Mock _db; - protected readonly Mock _upstream; - protected readonly Mock _indexer; + public class FactsBase + { + protected readonly Mock _db; + protected readonly Mock _upstream; + protected readonly Mock _indexer; - protected readonly CancellationToken _cancellationToken = CancellationToken.None; - protected readonly PackageService _target; + protected readonly CancellationToken _cancellationToken = CancellationToken.None; + protected readonly PackageService _target; - protected FactsBase() - { - _db = new Mock(); - _upstream = new Mock(); - _indexer = new Mock(); - - _target = new PackageService( - _db.Object, - _upstream.Object, - _indexer.Object, - Mock.Of>()); - } + protected FactsBase() + { + _db = new Mock(); + _upstream = new Mock(); + _indexer = new Mock(); + + _target = new PackageService( + _db.Object, + _upstream.Object, + _indexer.Object, + Mock.Of>()); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/PackageStorageServiceTests.cs b/tests/BaGet.Core.Tests/Services/PackageStorageServiceTests.cs index d99eec39c..199753420 100644 --- a/tests/BaGet.Core.Tests/Services/PackageStorageServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/PackageStorageServiceTests.cs @@ -10,575 +10,574 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +public class PackageStorageServiceTests { - public class PackageStorageServiceTests + public class SavePackageContentAsync : FactsBase { - public class SavePackageContentAsync : FactsBase + [Fact] + public async Task ThrowsIfPackageIsNull() { - [Fact] - public async Task ThrowsIfPackageIsNull() - { - await Assert.ThrowsAsync( - () => _target.SavePackageContentAsync( - null, - packageStream: Stream.Null, - nuspecStream: Stream.Null, - readmeStream: Stream.Null, - iconStream: Stream.Null)); - } + await Assert.ThrowsAsync( + () => _target.SavePackageContentAsync( + null, + packageStream: Stream.Null, + nuspecStream: Stream.Null, + readmeStream: Stream.Null, + iconStream: Stream.Null)); + } + + [Fact] + public async Task ThrowsIfPackageStreamIsNull() + { + await Assert.ThrowsAsync( + () => _target.SavePackageContentAsync( + _package, + packageStream: null, + nuspecStream: Stream.Null, + readmeStream: Stream.Null, + iconStream: Stream.Null)); + } + + [Fact] + public async Task ThrowsIfNuspecStreamIsNull() + { + await Assert.ThrowsAsync( + () => _target.SavePackageContentAsync( + _package, + packageStream: Stream.Null, + nuspecStream: null, + readmeStream: Stream.Null, + iconStream: Stream.Null)); + } + + [Fact] + public async Task SavesContent() + { + // Arrange + SetupPutResult(StoragePutResult.Success); - [Fact] - public async Task ThrowsIfPackageStreamIsNull() + using (var packageStream = StringStream("My package")) + using (var nuspecStream = StringStream("My nuspec")) + using (var readmeStream = StringStream("My readme")) + using (var iconStream = StringStream("My icon")) { - await Assert.ThrowsAsync( - () => _target.SavePackageContentAsync( - _package, - packageStream: null, - nuspecStream: Stream.Null, - readmeStream: Stream.Null, - iconStream: Stream.Null)); + // Act + await _target.SavePackageContentAsync( + _package, + packageStream: packageStream, + nuspecStream: nuspecStream, + readmeStream: readmeStream, + iconStream: iconStream); + + // Assert + Assert.True(_puts.ContainsKey(PackagePath)); + Assert.Equal("My package", await ToStringAsync(_puts[PackagePath].Content)); + Assert.Equal("binary/octet-stream", _puts[PackagePath].ContentType); + + Assert.True(_puts.ContainsKey(NuspecPath)); + Assert.Equal("My nuspec", await ToStringAsync(_puts[NuspecPath].Content)); + Assert.Equal("text/plain", _puts[NuspecPath].ContentType); + + Assert.True(_puts.ContainsKey(ReadmePath)); + Assert.Equal("My readme", await ToStringAsync(_puts[ReadmePath].Content)); + Assert.Equal("text/markdown", _puts[ReadmePath].ContentType); + + Assert.True(_puts.ContainsKey(IconPath)); + Assert.Equal("My icon", await ToStringAsync(_puts[IconPath].Content)); + Assert.Equal("image/xyz", _puts[IconPath].ContentType); } + } + + [Fact] + public async Task DoesNotSaveReadmeIfItIsNull() + { + // Arrange + SetupPutResult(StoragePutResult.Success); - [Fact] - public async Task ThrowsIfNuspecStreamIsNull() + using (var packageStream = StringStream("My package")) + using (var nuspecStream = StringStream("My nuspec")) { - await Assert.ThrowsAsync( - () => _target.SavePackageContentAsync( - _package, - packageStream: Stream.Null, - nuspecStream: null, - readmeStream: Stream.Null, - iconStream: Stream.Null)); + // Act + await _target.SavePackageContentAsync( + _package, + packageStream: packageStream, + nuspecStream: nuspecStream, + readmeStream: null, + iconStream: null); } - [Fact] - public async Task SavesContent() - { - // Arrange - SetupPutResult(StoragePutResult.Success); + // Assert + Assert.False(_puts.ContainsKey(ReadmePath)); + } - using (var packageStream = StringStream("My package")) - using (var nuspecStream = StringStream("My nuspec")) - using (var readmeStream = StringStream("My readme")) - using (var iconStream = StringStream("My icon")) - { - // Act - await _target.SavePackageContentAsync( - _package, - packageStream: packageStream, - nuspecStream: nuspecStream, - readmeStream: readmeStream, - iconStream: iconStream); - - // Assert - Assert.True(_puts.ContainsKey(PackagePath)); - Assert.Equal("My package", await ToStringAsync(_puts[PackagePath].Content)); - Assert.Equal("binary/octet-stream", _puts[PackagePath].ContentType); - - Assert.True(_puts.ContainsKey(NuspecPath)); - Assert.Equal("My nuspec", await ToStringAsync(_puts[NuspecPath].Content)); - Assert.Equal("text/plain", _puts[NuspecPath].ContentType); - - Assert.True(_puts.ContainsKey(ReadmePath)); - Assert.Equal("My readme", await ToStringAsync(_puts[ReadmePath].Content)); - Assert.Equal("text/markdown", _puts[ReadmePath].ContentType); - - Assert.True(_puts.ContainsKey(IconPath)); - Assert.Equal("My icon", await ToStringAsync(_puts[IconPath].Content)); - Assert.Equal("image/xyz", _puts[IconPath].ContentType); - } - } + [Fact] + public async Task NormalizesVersionWhenContentIsSaved() + { + // Arrange + SetupPutResult(StoragePutResult.Success); - [Fact] - public async Task DoesNotSaveReadmeIfItIsNull() + _package.Version = new NuGetVersion("1.2.3.0"); + using (var packageStream = StringStream("My package")) + using (var nuspecStream = StringStream("My nuspec")) + using (var readmeStream = StringStream("My readme")) + using (var iconStream = StringStream("My icon")) { - // Arrange - SetupPutResult(StoragePutResult.Success); - - using (var packageStream = StringStream("My package")) - using (var nuspecStream = StringStream("My nuspec")) - { - // Act - await _target.SavePackageContentAsync( - _package, - packageStream: packageStream, - nuspecStream: nuspecStream, - readmeStream: null, - iconStream: null); - } + // Act + await _target.SavePackageContentAsync( + _package, + packageStream: packageStream, + nuspecStream: nuspecStream, + readmeStream: readmeStream, + iconStream: iconStream); + } + + // Assert + Assert.True(_puts.ContainsKey(PackagePath)); + Assert.True(_puts.ContainsKey(NuspecPath)); + Assert.True(_puts.ContainsKey(ReadmePath)); + } - // Assert - Assert.False(_puts.ContainsKey(ReadmePath)); - } + [Fact] + public async Task DoesNotThrowIfContentAlreadyExistsAndContentsMatch() + { + // Arrange + SetupPutResult(StoragePutResult.AlreadyExists); - [Fact] - public async Task NormalizesVersionWhenContentIsSaved() + using (var packageStream = StringStream("My package")) + using (var nuspecStream = StringStream("My nuspec")) + using (var readmeStream = StringStream("My readme")) + using (var iconStream = StringStream("My icon")) { - // Arrange - SetupPutResult(StoragePutResult.Success); - - _package.Version = new NuGetVersion("1.2.3.0"); - using (var packageStream = StringStream("My package")) - using (var nuspecStream = StringStream("My nuspec")) - using (var readmeStream = StringStream("My readme")) - using (var iconStream = StringStream("My icon")) - { - // Act - await _target.SavePackageContentAsync( - _package, - packageStream: packageStream, - nuspecStream: nuspecStream, - readmeStream: readmeStream, - iconStream: iconStream); - } + var result = await _target.SavePackageContentAsync( + _package, + packageStream: packageStream, + nuspecStream: nuspecStream, + readmeStream: readmeStream, + iconStream: iconStream); // Assert + Assert.Equal(PackageSaveResult.Success, result); + Assert.True(_puts.ContainsKey(PackagePath)); + Assert.Equal("My package", await ToStringAsync(_puts[PackagePath].Content)); + Assert.Equal("binary/octet-stream", _puts[PackagePath].ContentType); + Assert.True(_puts.ContainsKey(NuspecPath)); - Assert.True(_puts.ContainsKey(ReadmePath)); - } + Assert.Equal("My nuspec", await ToStringAsync(_puts[NuspecPath].Content)); + Assert.Equal("text/plain", _puts[NuspecPath].ContentType); - [Fact] - public async Task DoesNotThrowIfContentAlreadyExistsAndContentsMatch() - { - // Arrange - SetupPutResult(StoragePutResult.AlreadyExists); + Assert.True(_puts.ContainsKey(ReadmePath)); + Assert.Equal("My readme", await ToStringAsync(_puts[ReadmePath].Content)); + Assert.Equal("text/markdown", _puts[ReadmePath].ContentType); - using (var packageStream = StringStream("My package")) - using (var nuspecStream = StringStream("My nuspec")) - using (var readmeStream = StringStream("My readme")) - using (var iconStream = StringStream("My icon")) - { - var result = await _target.SavePackageContentAsync( - _package, - packageStream: packageStream, - nuspecStream: nuspecStream, - readmeStream: readmeStream, - iconStream: iconStream); - - // Assert - Assert.Equal(PackageSaveResult.Success, result); - - Assert.True(_puts.ContainsKey(PackagePath)); - Assert.Equal("My package", await ToStringAsync(_puts[PackagePath].Content)); - Assert.Equal("binary/octet-stream", _puts[PackagePath].ContentType); - - Assert.True(_puts.ContainsKey(NuspecPath)); - Assert.Equal("My nuspec", await ToStringAsync(_puts[NuspecPath].Content)); - Assert.Equal("text/plain", _puts[NuspecPath].ContentType); - - Assert.True(_puts.ContainsKey(ReadmePath)); - Assert.Equal("My readme", await ToStringAsync(_puts[ReadmePath].Content)); - Assert.Equal("text/markdown", _puts[ReadmePath].ContentType); - - Assert.True(_puts.ContainsKey(IconPath)); - Assert.Equal("My icon", await ToStringAsync(_puts[IconPath].Content)); - Assert.Equal("image/xyz", _puts[IconPath].ContentType); - } + Assert.True(_puts.ContainsKey(IconPath)); + Assert.Equal("My icon", await ToStringAsync(_puts[IconPath].Content)); + Assert.Equal("image/xyz", _puts[IconPath].ContentType); } + } - [Fact] - public async Task ReturnsConflictIfContentAlreadyExistsButContentsDoNotMatch() + [Fact] + public async Task ReturnsConflictIfContentAlreadyExistsButContentsDoNotMatch() + { + // Arrange + SetupPutResult(StoragePutResult.Conflict); + + using (var packageStream = StringStream("My package")) + using (var nuspecStream = StringStream("My nuspec")) + using (var readmeStream = StringStream("My readme")) + using (var iconStream = StringStream("My icon")) { - // Arrange - SetupPutResult(StoragePutResult.Conflict); + // Act + var result = await _target.SavePackageContentAsync( + _package, + packageStream: packageStream, + nuspecStream: nuspecStream, + readmeStream: readmeStream, + iconStream: iconStream); - using (var packageStream = StringStream("My package")) - using (var nuspecStream = StringStream("My nuspec")) - using (var readmeStream = StringStream("My readme")) - using (var iconStream = StringStream("My icon")) - { - // Act - var result = await _target.SavePackageContentAsync( - _package, - packageStream: packageStream, - nuspecStream: nuspecStream, - readmeStream: readmeStream, - iconStream: iconStream); - - // Assert - Assert.Equal(PackageSaveResult.Conflict, result); - } + // Assert + Assert.Equal(PackageSaveResult.Conflict, result); } } + } + + public class GetPackageStreamAsync : FactsBase + { + [Fact] + public async Task ThrowsIfStorageThrows() + { + // Arrange + var cancellationToken = CancellationToken.None; + _storage + .Setup(s => s.GetAsync(PackagePath, cancellationToken)) + .ThrowsAsync(new DirectoryNotFoundException()); + + // Act + await Assert.ThrowsAsync(() => + _target.GetPackageStreamAsync(_package.Id, _package.Version, cancellationToken)); + } - public class GetPackageStreamAsync : FactsBase + [Fact] + public async Task GetsStream() { - [Fact] - public async Task ThrowsIfStorageThrows() + // Arrange + var cancellationToken = CancellationToken.None; + using (var packageStream = StringStream("My package")) { - // Arrange - var cancellationToken = CancellationToken.None; _storage .Setup(s => s.GetAsync(PackagePath, cancellationToken)) - .ThrowsAsync(new DirectoryNotFoundException()); + .ReturnsAsync(packageStream); // Act - await Assert.ThrowsAsync(() => - _target.GetPackageStreamAsync(_package.Id, _package.Version, cancellationToken)); - } + var result = await _target.GetPackageStreamAsync(_package.Id, _package.Version, cancellationToken); - [Fact] - public async Task GetsStream() - { - // Arrange - var cancellationToken = CancellationToken.None; - using (var packageStream = StringStream("My package")) - { - _storage - .Setup(s => s.GetAsync(PackagePath, cancellationToken)) - .ReturnsAsync(packageStream); - - // Act - var result = await _target.GetPackageStreamAsync(_package.Id, _package.Version, cancellationToken); - - // Assert - Assert.Equal("My package", await ToStringAsync(result)); + // Assert + Assert.Equal("My package", await ToStringAsync(result)); - _storage.Verify(s => s.GetAsync(PackagePath, cancellationToken), Times.Once); - } + _storage.Verify(s => s.GetAsync(PackagePath, cancellationToken), Times.Once); } } + } + + public class GetNuspecStreamAsync : FactsBase + { + [Fact] + public async Task ThrowsIfDoesntExist() + { + // Arrange + var cancellationToken = CancellationToken.None; + _storage + .Setup(s => s.GetAsync(NuspecPath, cancellationToken)) + .ThrowsAsync(new DirectoryNotFoundException()); + + // Act + await Assert.ThrowsAsync(() => + _target.GetNuspecStreamAsync(_package.Id, _package.Version, cancellationToken)); + } - public class GetNuspecStreamAsync : FactsBase + [Fact] + public async Task GetsStream() { - [Fact] - public async Task ThrowsIfDoesntExist() + // Arrange + var cancellationToken = CancellationToken.None; + using (var nuspecStream = StringStream("My nuspec")) { - // Arrange - var cancellationToken = CancellationToken.None; _storage .Setup(s => s.GetAsync(NuspecPath, cancellationToken)) - .ThrowsAsync(new DirectoryNotFoundException()); + .ReturnsAsync(nuspecStream); // Act - await Assert.ThrowsAsync(() => - _target.GetNuspecStreamAsync(_package.Id, _package.Version, cancellationToken)); - } + var result = await _target.GetNuspecStreamAsync(_package.Id, _package.Version, cancellationToken); - [Fact] - public async Task GetsStream() - { - // Arrange - var cancellationToken = CancellationToken.None; - using (var nuspecStream = StringStream("My nuspec")) - { - _storage - .Setup(s => s.GetAsync(NuspecPath, cancellationToken)) - .ReturnsAsync(nuspecStream); - - // Act - var result = await _target.GetNuspecStreamAsync(_package.Id, _package.Version, cancellationToken); - - // Assert - Assert.Equal("My nuspec", await ToStringAsync(result)); + // Assert + Assert.Equal("My nuspec", await ToStringAsync(result)); - _storage.Verify(s => s.GetAsync(NuspecPath, cancellationToken), Times.Once); - } + _storage.Verify(s => s.GetAsync(NuspecPath, cancellationToken), Times.Once); } } + } + + public class GetReadmeStreamAsync : FactsBase + { + [Fact] + public async Task ThrowsIfDoesntExist() + { + // Arrange + var cancellationToken = CancellationToken.None; + _storage + .Setup(s => s.GetAsync(ReadmePath, cancellationToken)) + .ThrowsAsync(new DirectoryNotFoundException()); + + // Act + await Assert.ThrowsAsync(() => + _target.GetReadmeStreamAsync(_package.Id, _package.Version, cancellationToken)); + } - public class GetReadmeStreamAsync : FactsBase + [Fact] + public async Task GetsStream() { - [Fact] - public async Task ThrowsIfDoesntExist() + // Arrange + var cancellationToken = CancellationToken.None; + using (var readmeStream = StringStream("My readme")) { - // Arrange - var cancellationToken = CancellationToken.None; _storage .Setup(s => s.GetAsync(ReadmePath, cancellationToken)) - .ThrowsAsync(new DirectoryNotFoundException()); + .ReturnsAsync(readmeStream); // Act - await Assert.ThrowsAsync(() => - _target.GetReadmeStreamAsync(_package.Id, _package.Version, cancellationToken)); - } + var result = await _target.GetReadmeStreamAsync(_package.Id, _package.Version, cancellationToken); - [Fact] - public async Task GetsStream() - { - // Arrange - var cancellationToken = CancellationToken.None; - using (var readmeStream = StringStream("My readme")) - { - _storage - .Setup(s => s.GetAsync(ReadmePath, cancellationToken)) - .ReturnsAsync(readmeStream); - - // Act - var result = await _target.GetReadmeStreamAsync(_package.Id, _package.Version, cancellationToken); - - // Assert - Assert.Equal("My readme", await ToStringAsync(result)); + // Assert + Assert.Equal("My readme", await ToStringAsync(result)); - _storage.Verify(s => s.GetAsync(ReadmePath, cancellationToken), Times.Once); - } + _storage.Verify(s => s.GetAsync(ReadmePath, cancellationToken), Times.Once); } } + } - public class DeleteAsync : FactsBase + public class DeleteAsync : FactsBase + { + [Fact] + public async Task Deletes() { - [Fact] - public async Task Deletes() - { - // Act - var cancellationToken = CancellationToken.None; - await _target.DeleteAsync(_package.Id, _package.Version, cancellationToken); + // Act + var cancellationToken = CancellationToken.None; + await _target.DeleteAsync(_package.Id, _package.Version, cancellationToken); - _storage.Verify(s => s.DeleteAsync(PackagePath, cancellationToken), Times.Once); - _storage.Verify(s => s.DeleteAsync(NuspecPath, cancellationToken), Times.Once); - _storage.Verify(s => s.DeleteAsync(ReadmePath, cancellationToken), Times.Once); - } + _storage.Verify(s => s.DeleteAsync(PackagePath, cancellationToken), Times.Once); + _storage.Verify(s => s.DeleteAsync(NuspecPath, cancellationToken), Times.Once); + _storage.Verify(s => s.DeleteAsync(ReadmePath, cancellationToken), Times.Once); } + } - /// - /// These facts run on top of the real file system, - /// through , the way does. - /// - public class SavePackageContentAsyncOnFileSystem : FileSystemFactsBase + /// + /// These facts run on top of the real file system, + /// through , the way does. + /// + public class SavePackageContentAsyncOnFileSystem : FileSystemFactsBase + { + [Fact] + public async Task WhenContentIsNew_Succeeds() { - [Fact] - public async Task WhenContentIsNew_Succeeds() - { - // Act - var result = await SaveAsync( - package: "My package", - nuspec: "My nuspec", - readme: "My readme", - icon: "My icon"); - - // Assert - Assert.Equal(PackageSaveResult.Success, result); - Assert.Equal("My package", await ReadAsync(PackagePath)); - Assert.Equal("My nuspec", await ReadAsync(NuspecPath)); - Assert.Equal("My readme", await ReadAsync(ReadmePath)); - Assert.Equal("My icon", await ReadAsync(IconPath)); - } + // Act + var result = await SaveAsync( + package: "My package", + nuspec: "My nuspec", + readme: "My readme", + icon: "My icon"); + + // Assert + Assert.Equal(PackageSaveResult.Success, result); + Assert.Equal("My package", await ReadAsync(PackagePath)); + Assert.Equal("My nuspec", await ReadAsync(NuspecPath)); + Assert.Equal("My readme", await ReadAsync(ReadmePath)); + Assert.Equal("My icon", await ReadAsync(IconPath)); + } - [Fact] - public async Task WhenIdenticalContentIsAlreadyStored_Succeeds() - { - // Arrange - await SaveAsync("My package", "My nuspec", "My readme", "My icon"); + [Fact] + public async Task WhenIdenticalContentIsAlreadyStored_Succeeds() + { + // Arrange + await SaveAsync("My package", "My nuspec", "My readme", "My icon"); - // Act - var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); + // Act + var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); - // Assert - Assert.Equal(PackageSaveResult.Success, result); - Assert.Equal("My package", await ReadAsync(PackagePath)); - } + // Assert + Assert.Equal(PackageSaveResult.Success, result); + Assert.Equal("My package", await ReadAsync(PackagePath)); + } - [Fact] - public async Task WhenStoredPackageContentDiffers_ReturnsConflict() - { - // Arrange - await WriteAsync(PackagePath, "Other package"); + [Fact] + public async Task WhenStoredPackageContentDiffers_ReturnsConflict() + { + // Arrange + await WriteAsync(PackagePath, "Other package"); - // Act - var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); + // Act + var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); - // Assert - Assert.Equal(PackageSaveResult.Conflict, result); - Assert.Equal("Other package", await ReadAsync(PackagePath)); - Assert.False(File.Exists(FullPath(NuspecPath))); - } + // Assert + Assert.Equal(PackageSaveResult.Conflict, result); + Assert.Equal("Other package", await ReadAsync(PackagePath)); + Assert.False(File.Exists(FullPath(NuspecPath))); + } - [Fact] - public async Task WhenStoredNuspecContentDiffers_ReturnsConflict() - { - // Arrange - await WriteAsync(NuspecPath, "Other nuspec"); + [Fact] + public async Task WhenStoredNuspecContentDiffers_ReturnsConflict() + { + // Arrange + await WriteAsync(NuspecPath, "Other nuspec"); - // Act - var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); + // Act + var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); - // Assert - Assert.Equal(PackageSaveResult.Conflict, result); - Assert.Equal("Other nuspec", await ReadAsync(NuspecPath)); - Assert.False(File.Exists(FullPath(ReadmePath))); - } + // Assert + Assert.Equal(PackageSaveResult.Conflict, result); + Assert.Equal("Other nuspec", await ReadAsync(NuspecPath)); + Assert.False(File.Exists(FullPath(ReadmePath))); + } - [Fact] - public async Task WhenStoredReadmeContentDiffers_ReturnsConflict() - { - // Arrange - await WriteAsync(ReadmePath, "Other readme"); + [Fact] + public async Task WhenStoredReadmeContentDiffers_ReturnsConflict() + { + // Arrange + await WriteAsync(ReadmePath, "Other readme"); - // Act - var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); + // Act + var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); - // Assert - Assert.Equal(PackageSaveResult.Conflict, result); - Assert.Equal("Other readme", await ReadAsync(ReadmePath)); - Assert.False(File.Exists(FullPath(IconPath))); - } + // Assert + Assert.Equal(PackageSaveResult.Conflict, result); + Assert.Equal("Other readme", await ReadAsync(ReadmePath)); + Assert.False(File.Exists(FullPath(IconPath))); + } - [Fact] - public async Task WhenStoredIconContentDiffers_ReturnsConflict() - { - // Arrange - await WriteAsync(IconPath, "Other icon"); + [Fact] + public async Task WhenStoredIconContentDiffers_ReturnsConflict() + { + // Arrange + await WriteAsync(IconPath, "Other icon"); - // Act - var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); + // Act + var result = await SaveAsync("My package", "My nuspec", "My readme", "My icon"); - // Assert - Assert.Equal(PackageSaveResult.Conflict, result); - Assert.Equal("Other icon", await ReadAsync(IconPath)); - } + // Assert + Assert.Equal(PackageSaveResult.Conflict, result); + Assert.Equal("Other icon", await ReadAsync(IconPath)); + } - [Fact] - public async Task WhenPackageHasNoReadmeOrIcon_Succeeds() - { - // Act - var result = await SaveAsync("My package", "My nuspec", readme: null, icon: null); + [Fact] + public async Task WhenPackageHasNoReadmeOrIcon_Succeeds() + { + // Act + var result = await SaveAsync("My package", "My nuspec", readme: null, icon: null); - // Assert - Assert.Equal(PackageSaveResult.Success, result); - Assert.False(File.Exists(FullPath(ReadmePath))); - Assert.False(File.Exists(FullPath(IconPath))); - } + // Assert + Assert.Equal(PackageSaveResult.Success, result); + Assert.False(File.Exists(FullPath(ReadmePath))); + Assert.False(File.Exists(FullPath(IconPath))); } + } - public class FileSystemFactsBase : IDisposable + public class FileSystemFactsBase : IDisposable + { + protected readonly Package _package = new Package { - protected readonly Package _package = new Package - { - Id = "My.Package", - Version = new NuGetVersion("1.2.3") - }; + Id = "My.Package", + Version = new NuGetVersion("1.2.3") + }; - private readonly string _storePath; - private readonly PackageStorageService _target; + private readonly string _storePath; + private readonly PackageStorageService _target; - public FileSystemFactsBase() - { - _storePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + public FileSystemFactsBase() + { + _storePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); - var options = new Mock>(); - options - .Setup(o => o.Value) - .Returns(() => new FileSystemStorageOptions { Path = _storePath }); + var options = new Mock>(); + options + .Setup(o => o.Value) + .Returns(() => new FileSystemStorageOptions { Path = _storePath }); - _target = new PackageStorageService( - new FileStorageService(options.Object), - Mock.Of>()); - } + _target = new PackageStorageService( + new FileStorageService(options.Object), + Mock.Of>()); + } - public void Dispose() + public void Dispose() + { + try + { + Directory.Delete(_storePath, recursive: true); + } + catch (DirectoryNotFoundException) { - try - { - Directory.Delete(_storePath, recursive: true); - } - catch (DirectoryNotFoundException) - { - } } + } - protected string PackagePath => Path.Combine("packages", "my.package", "1.2.3", "my.package.1.2.3.nupkg"); - protected string NuspecPath => Path.Combine("packages", "my.package", "1.2.3", "my.package.nuspec"); - protected string ReadmePath => Path.Combine("packages", "my.package", "1.2.3", "readme"); - protected string IconPath => Path.Combine("packages", "my.package", "1.2.3", "icon"); + protected string PackagePath => Path.Combine("packages", "my.package", "1.2.3", "my.package.1.2.3.nupkg"); + protected string NuspecPath => Path.Combine("packages", "my.package", "1.2.3", "my.package.nuspec"); + protected string ReadmePath => Path.Combine("packages", "my.package", "1.2.3", "readme"); + protected string IconPath => Path.Combine("packages", "my.package", "1.2.3", "icon"); - protected string FullPath(string path) => Path.Combine(_storePath, path); + protected string FullPath(string path) => Path.Combine(_storePath, path); - protected async Task SaveAsync(string package, string nuspec, string readme, string icon) - { - using (var packageStream = StringStream(package)) - using (var nuspecStream = StringStream(nuspec)) - using (var readmeStream = StringStream(readme)) - using (var iconStream = StringStream(icon)) - { - return await _target.SavePackageContentAsync( - _package, - packageStream, - nuspecStream, - readmeStream, - iconStream, - CancellationToken.None); - } + protected async Task SaveAsync(string package, string nuspec, string readme, string icon) + { + using (var packageStream = StringStream(package)) + using (var nuspecStream = StringStream(nuspec)) + using (var readmeStream = StringStream(readme)) + using (var iconStream = StringStream(icon)) + { + return await _target.SavePackageContentAsync( + _package, + packageStream, + nuspecStream, + readmeStream, + iconStream, + CancellationToken.None); } + } - protected async Task WriteAsync(string path, string content) - { - var fullPath = FullPath(path); + protected async Task WriteAsync(string path, string content) + { + var fullPath = FullPath(path); - Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); - await File.WriteAllTextAsync(fullPath, content); - } + Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); + await File.WriteAllTextAsync(fullPath, content); + } - protected Task ReadAsync(string path) - { - return File.ReadAllTextAsync(FullPath(path)); - } + protected Task ReadAsync(string path) + { + return File.ReadAllTextAsync(FullPath(path)); + } - private Stream StringStream(string input) - { - if (input == null) return null; + private Stream StringStream(string input) + { + if (input == null) return null; - return new MemoryStream(Encoding.ASCII.GetBytes(input)); - } + return new MemoryStream(Encoding.ASCII.GetBytes(input)); } + } - public class FactsBase + public class FactsBase + { + protected readonly Package _package = new Package { - protected readonly Package _package = new Package - { - Id = "My.Package", - Version = new NuGetVersion("1.2.3") - }; + Id = "My.Package", + Version = new NuGetVersion("1.2.3") + }; - protected readonly Mock _storage; - protected readonly PackageStorageService _target; + protected readonly Mock _storage; + protected readonly PackageStorageService _target; - protected readonly Dictionary _puts; + protected readonly Dictionary _puts; - public FactsBase() - { - _storage = new Mock(); - _target = new PackageStorageService(_storage.Object, Mock.Of>()); + public FactsBase() + { + _storage = new Mock(); + _target = new PackageStorageService(_storage.Object, Mock.Of>()); - _puts = new Dictionary(); - } + _puts = new Dictionary(); + } - protected string PackagePath => Path.Combine("packages", "my.package", "1.2.3", "my.package.1.2.3.nupkg"); - protected string NuspecPath => Path.Combine("packages", "my.package", "1.2.3", "my.package.nuspec"); - protected string ReadmePath => Path.Combine("packages", "my.package", "1.2.3", "readme"); - protected string IconPath => Path.Combine("packages", "my.package", "1.2.3", "icon"); + protected string PackagePath => Path.Combine("packages", "my.package", "1.2.3", "my.package.1.2.3.nupkg"); + protected string NuspecPath => Path.Combine("packages", "my.package", "1.2.3", "my.package.nuspec"); + protected string ReadmePath => Path.Combine("packages", "my.package", "1.2.3", "readme"); + protected string IconPath => Path.Combine("packages", "my.package", "1.2.3", "icon"); - protected Stream StringStream(string input) - { - var bytes = Encoding.ASCII.GetBytes(input); + protected Stream StringStream(string input) + { + var bytes = Encoding.ASCII.GetBytes(input); - return new MemoryStream(bytes); - } + return new MemoryStream(bytes); + } - protected async Task ToStringAsync(Stream input) + protected async Task ToStringAsync(Stream input) + { + using (var reader = new StreamReader(input)) { - using (var reader = new StreamReader(input)) - { - return await reader.ReadToEndAsync(); - } + return await reader.ReadToEndAsync(); } + } - protected void SetupPutResult(StoragePutResult result) - { - _storage - .Setup( - s => s.PutAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback((string path, Stream content, string contentType, CancellationToken cancellationToken) => - { - _puts[path] = (content, contentType); - }) - .ReturnsAsync(result); - } + protected void SetupPutResult(StoragePutResult result) + { + _storage + .Setup( + s => s.PutAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Callback((string path, Stream content, string contentType, CancellationToken cancellationToken) => + { + _puts[path] = (content, contentType); + }) + .ReturnsAsync(result); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/StoragePackageStagingServiceTests.cs b/tests/BaGet.Core.Tests/Services/StoragePackageStagingServiceTests.cs index ee22b47a2..4579f1fdf 100644 --- a/tests/BaGet.Core.Tests/Services/StoragePackageStagingServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/StoragePackageStagingServiceTests.cs @@ -11,310 +11,309 @@ using Moq; using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +public class StoragePackageStagingServiceTests { - public class StoragePackageStagingServiceTests + public class StageAsync : FactsBase { - public class StageAsync : FactsBase + [Fact] + public async Task StagesAnUploadItsOwnerCanReopen() { - [Fact] - public async Task StagesAnUploadItsOwnerCanReopen() - { - var token = await _target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); + var token = await _target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); - using var reopened = await _target.OpenAsync(token, "alice", CancellationToken.None); - Assert.Equal("a package", await ToStringAsync(reopened)); - } + using var reopened = await _target.OpenAsync(token, "alice", CancellationToken.None); + Assert.Equal("a package", await ToStringAsync(reopened)); + } - [Fact] - public async Task TokensAreUnguessable() + [Fact] + public async Task TokensAreUnguessable() + { + var tokens = new List(); + for (var i = 0; i < 8; i++) { - var tokens = new List(); - for (var i = 0; i < 8; i++) - { - tokens.Add(await _target.StageAsync(StringStream("a package"), "alice", CancellationToken.None)); - } - - Assert.Equal(tokens.Count, tokens.Distinct(StringComparer.Ordinal).Count()); - foreach (var token in tokens) - { - // 128 random bits, hex encoded: not a counter, a name, or a timestamp. - Assert.Equal(32, token.Length); - Assert.All(token, c => Assert.True("0123456789abcdef".Contains(c), c + " is not lowercase hex")); - } + tokens.Add(await _target.StageAsync(StringStream("a package"), "alice", CancellationToken.None)); } - [Fact] - public async Task RejectsANullPackage() + Assert.Equal(tokens.Count, tokens.Distinct(StringComparer.Ordinal).Count()); + foreach (var token in tokens) { - await Assert.ThrowsAsync( - () => _target.StageAsync(null, "alice", CancellationToken.None)); + // 128 random bits, hex encoded: not a counter, a name, or a timestamp. + Assert.Equal(32, token.Length); + Assert.All(token, c => Assert.True("0123456789abcdef".Contains(c), c + " is not lowercase hex")); } + } - [Fact] - public async Task NeverLogsTheTokenAboveDebug() - { - // The token is the whole capability over a staged upload. A log at - // Information is on by default and usually shipped to a store read by more - // people than the uploader, so the token must not travel there. - var logger = new RecordingLogger(); - var target = new StoragePackageStagingService(_storage, _time.Object, logger); + [Fact] + public async Task RejectsANullPackage() + { + await Assert.ThrowsAsync( + () => _target.StageAsync(null, "alice", CancellationToken.None)); + } - var token = await target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); - await target.OpenAsync(token, "bob", CancellationToken.None); - await target.SweepAsync(_now.AddDays(1), CancellationToken.None); + [Fact] + public async Task NeverLogsTheTokenAboveDebug() + { + // The token is the whole capability over a staged upload. A log at + // Information is on by default and usually shipped to a store read by more + // people than the uploader, so the token must not travel there. + var logger = new RecordingLogger(); + var target = new StoragePackageStagingService(_storage, _time.Object, logger); - Assert.Empty(logger.Entries.Where(e => e.Level > LogLevel.Debug && e.Message.Contains(token))); - } + var token = await target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); + await target.OpenAsync(token, "bob", CancellationToken.None); + await target.SweepAsync(_now.AddDays(1), CancellationToken.None); + + Assert.Empty(logger.Entries.Where(e => e.Level > LogLevel.Debug && e.Message.Contains(token))); } + } - public class OpenAsync : FactsBase + public class OpenAsync : FactsBase + { + [Fact] + public async Task AnotherUserCannotOpenAStagedUpload() { - [Fact] - public async Task AnotherUserCannotOpenAStagedUpload() - { - var token = await _target.StageAsync(StringStream("a staged package"), "alice", CancellationToken.None); + var token = await _target.StageAsync(StringStream("a staged package"), "alice", CancellationToken.None); - Assert.Null(await _target.OpenAsync(token, "bob", CancellationToken.None)); + Assert.Null(await _target.OpenAsync(token, "bob", CancellationToken.None)); - // Bob's attempt must not have consumed or damaged Alice's upload. - using var reopened = await _target.OpenAsync(token, "alice", CancellationToken.None); - Assert.Equal("a staged package", await ToStringAsync(reopened)); - } + // Bob's attempt must not have consumed or damaged Alice's upload. + using var reopened = await _target.OpenAsync(token, "alice", CancellationToken.None); + Assert.Equal("a staged package", await ToStringAsync(reopened)); + } - [Fact] - public async Task AnUnknownTokenIsNull() - { - Assert.Null(await _target.OpenAsync("0123456789abcdef0123456789abcdef", "alice", CancellationToken.None)); - } + [Fact] + public async Task AnUnknownTokenIsNull() + { + Assert.Null(await _target.OpenAsync("0123456789abcdef0123456789abcdef", "alice", CancellationToken.None)); + } - [Fact] - public async Task AMalformedTokenCannotReachOutsideStaging() + [Fact] + public async Task AMalformedTokenCannotReachOutsideStaging() + { + // A token becomes a storage path, so a caller-supplied one that is not a + // token must be refused before it gets there. + await _storage.PutAsync("packages/secret.nupkg", StringStream("not yours"), "application/octet-stream"); + + var malformed = new[] + { + null, + "", + " ", + "../packages/secret", + "..", + "ALICE", + "alice.json", + "0123456789abcdef0123456789abcdeff", + }; + + foreach (var token in malformed) { - // A token becomes a storage path, so a caller-supplied one that is not a - // token must be refused before it gets there. - await _storage.PutAsync("packages/secret.nupkg", StringStream("not yours"), "application/octet-stream"); - - var malformed = new[] - { - null, - "", - " ", - "../packages/secret", - "..", - "ALICE", - "alice.json", - "0123456789abcdef0123456789abcdeff", - }; - - foreach (var token in malformed) - { - Assert.Null(await _target.OpenAsync(token, "alice", CancellationToken.None)); - } + Assert.Null(await _target.OpenAsync(token, "alice", CancellationToken.None)); } + } - [Fact] - public async Task AStoreThatForgetsTheUploadIsAnUnknownToken() - { - // "Storage:Type=Null" stores nothing and reads back nothing, so a staged - // upload must report itself unknown rather than hand back a null stream. - var target = new StoragePackageStagingService( - new NullStorageService(), - _time.Object, - new RecordingLogger()); + [Fact] + public async Task AStoreThatForgetsTheUploadIsAnUnknownToken() + { + // "Storage:Type=Null" stores nothing and reads back nothing, so a staged + // upload must report itself unknown rather than hand back a null stream. + var target = new StoragePackageStagingService( + new NullStorageService(), + _time.Object, + new RecordingLogger()); - var token = await target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); + var token = await target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); - Assert.Null(await target.OpenAsync(token, "alice", CancellationToken.None)); - } + Assert.Null(await target.OpenAsync(token, "alice", CancellationToken.None)); } + } - public class RemoveAsync : FactsBase + public class RemoveAsync : FactsBase + { + [Fact] + public async Task ForgetsTheUploadAndLeavesNothingStored() { - [Fact] - public async Task ForgetsTheUploadAndLeavesNothingStored() - { - var token = await _target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); + var token = await _target.StageAsync(StringStream("a package"), "alice", CancellationToken.None); - Assert.True(await _target.RemoveAsync(token, "alice", CancellationToken.None)); + Assert.True(await _target.RemoveAsync(token, "alice", CancellationToken.None)); - Assert.Null(await _target.OpenAsync(token, "alice", CancellationToken.None)); - Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); - } + Assert.Null(await _target.OpenAsync(token, "alice", CancellationToken.None)); + Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); + } - [Fact] - public async Task AnotherUserCannotForgetAStagedUpload() - { - // The token is the only handle on a staged upload, so anyone who learned one - // could otherwise make its owner upload the whole file again. - var token = await _target.StageAsync(StringStream("a staged package"), "alice", CancellationToken.None); + [Fact] + public async Task AnotherUserCannotForgetAStagedUpload() + { + // The token is the only handle on a staged upload, so anyone who learned one + // could otherwise make its owner upload the whole file again. + var token = await _target.StageAsync(StringStream("a staged package"), "alice", CancellationToken.None); - Assert.False(await _target.RemoveAsync(token, "bob", CancellationToken.None)); + Assert.False(await _target.RemoveAsync(token, "bob", CancellationToken.None)); - using var kept = await _target.OpenAsync(token, "alice", CancellationToken.None); - Assert.Equal("a staged package", await ToStringAsync(kept)); - } + using var kept = await _target.OpenAsync(token, "alice", CancellationToken.None); + Assert.Equal("a staged package", await ToStringAsync(kept)); + } - [Fact] - public async Task AnUnknownTokenIsNotAnError() - { - Assert.False(await _target.RemoveAsync("0123456789abcdef0123456789abcdef", "alice", CancellationToken.None)); - Assert.False(await _target.RemoveAsync("../packages/secret", "alice", CancellationToken.None)); - } + [Fact] + public async Task AnUnknownTokenIsNotAnError() + { + Assert.False(await _target.RemoveAsync("0123456789abcdef0123456789abcdef", "alice", CancellationToken.None)); + Assert.False(await _target.RemoveAsync("../packages/secret", "alice", CancellationToken.None)); } + } - public class SweepAsync : FactsBase + public class SweepAsync : FactsBase + { + [Fact] + public async Task RemovesUploadsStagedBeforeTheCutoffOnly() { - [Fact] - public async Task RemovesUploadsStagedBeforeTheCutoffOnly() - { - var abandoned = await _target.StageAsync(StringStream("abandoned"), "alice", CancellationToken.None); + var abandoned = await _target.StageAsync(StringStream("abandoned"), "alice", CancellationToken.None); - _now = _now.AddHours(12); - var recent = await _target.StageAsync(StringStream("recent"), "alice", CancellationToken.None); + _now = _now.AddHours(12); + var recent = await _target.StageAsync(StringStream("recent"), "alice", CancellationToken.None); - var swept = await _target.SweepAsync(_now.AddHours(-6), CancellationToken.None); + var swept = await _target.SweepAsync(_now.AddHours(-6), CancellationToken.None); - Assert.Equal(1, swept); - Assert.Null(await _target.OpenAsync(abandoned, "alice", CancellationToken.None)); + Assert.Equal(1, swept); + Assert.Null(await _target.OpenAsync(abandoned, "alice", CancellationToken.None)); - using var kept = await _target.OpenAsync(recent, "alice", CancellationToken.None); - Assert.Equal("recent", await ToStringAsync(kept)); - } + using var kept = await _target.OpenAsync(recent, "alice", CancellationToken.None); + Assert.Equal("recent", await ToStringAsync(kept)); + } - [Fact] - public async Task LeavesNothingBehindForWhatItSwept() - { - await _target.StageAsync(StringStream("abandoned"), "alice", CancellationToken.None); + [Fact] + public async Task LeavesNothingBehindForWhatItSwept() + { + await _target.StageAsync(StringStream("abandoned"), "alice", CancellationToken.None); - Assert.Equal(1, await _target.SweepAsync(_now.AddDays(1), CancellationToken.None)); + Assert.Equal(1, await _target.SweepAsync(_now.AddDays(1), CancellationToken.None)); - Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); - } + Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); + } - [Fact] - public async Task SweepsNothingWhenStagingIsEmpty() - { - Assert.Equal(0, await _target.SweepAsync(_now.AddDays(1), CancellationToken.None)); - } + [Fact] + public async Task SweepsNothingWhenStagingIsEmpty() + { + Assert.Equal(0, await _target.SweepAsync(_now.AddDays(1), CancellationToken.None)); + } - [Fact] - public async Task TouchesNothingOutsideStaging() - { - await _storage.PutAsync("packages/keep.nupkg", StringStream("keep"), "application/octet-stream"); - await _target.StageAsync(StringStream("abandoned"), "alice", CancellationToken.None); + [Fact] + public async Task TouchesNothingOutsideStaging() + { + await _storage.PutAsync("packages/keep.nupkg", StringStream("keep"), "application/octet-stream"); + await _target.StageAsync(StringStream("abandoned"), "alice", CancellationToken.None); - await _target.SweepAsync(_now.AddDays(1), CancellationToken.None); + await _target.SweepAsync(_now.AddDays(1), CancellationToken.None); - Assert.Equal( - "packages/keep.nupkg", - Assert.Single(await _storage.ListAsync("packages", CancellationToken.None))); - } + Assert.Equal( + "packages/keep.nupkg", + Assert.Single(await _storage.ListAsync("packages", CancellationToken.None))); + } - [Fact] - public async Task KeepsAnUploadWhoseMetadataCannotBeReadRightNow() + [Fact] + public async Task KeepsAnUploadWhoseMetadataCannotBeReadRightNow() + { + // A metadata read can fail for reasons that have nothing to do with the + // upload being abandoned - a backup or a scanner holding the file, a store + // that is briefly unreachable. Collecting it then would discard an upload + // staged a minute ago, whose preview is still open. + var token = await _target.StageAsync(StringStream("staged a moment ago"), "alice", CancellationToken.None); + var metadataPath = Path.Combine(_storePath, "staging", token + ".json"); + + using (File.Open(metadataPath, FileMode.Open, FileAccess.Read, FileShare.None)) { - // A metadata read can fail for reasons that have nothing to do with the - // upload being abandoned - a backup or a scanner holding the file, a store - // that is briefly unreachable. Collecting it then would discard an upload - // staged a minute ago, whose preview is still open. - var token = await _target.StageAsync(StringStream("staged a moment ago"), "alice", CancellationToken.None); - var metadataPath = Path.Combine(_storePath, "staging", token + ".json"); - - using (File.Open(metadataPath, FileMode.Open, FileAccess.Read, FileShare.None)) - { - Assert.Equal(0, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); - } - - using var kept = await _target.OpenAsync(token, "alice", CancellationToken.None); - Assert.Equal("staged a moment ago", await ToStringAsync(kept)); + Assert.Equal(0, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); } - [Fact] - public async Task CollectsAnUploadWhoseMetadataIsGone() - { - // Nobody can open an upload whose metadata is absent, so there is nothing to - // keep: the owner it belonged to is unknowable. - var token = await _target.StageAsync(StringStream("half staged"), "alice", CancellationToken.None); - File.Delete(Path.Combine(_storePath, "staging", token + ".json")); + using var kept = await _target.OpenAsync(token, "alice", CancellationToken.None); + Assert.Equal("staged a moment ago", await ToStringAsync(kept)); + } - Assert.Equal(1, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); - Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); - } + [Fact] + public async Task CollectsAnUploadWhoseMetadataIsGone() + { + // Nobody can open an upload whose metadata is absent, so there is nothing to + // keep: the owner it belonged to is unknowable. + var token = await _target.StageAsync(StringStream("half staged"), "alice", CancellationToken.None); + File.Delete(Path.Combine(_storePath, "staging", token + ".json")); - [Fact] - public async Task CollectsAnUploadWhoseMetadataCanNeverBeRead() - { - // Unreadable content, unlike an unreadable file, does not become readable on - // the next pass. - var token = await _target.StageAsync(StringStream("corrupt"), "alice", CancellationToken.None); - File.WriteAllText(Path.Combine(_storePath, "staging", token + ".json"), "not json"); + Assert.Equal(1, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); + Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); + } - Assert.Equal(1, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); - Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); - } + [Fact] + public async Task CollectsAnUploadWhoseMetadataCanNeverBeRead() + { + // Unreadable content, unlike an unreadable file, does not become readable on + // the next pass. + var token = await _target.StageAsync(StringStream("corrupt"), "alice", CancellationToken.None); + File.WriteAllText(Path.Combine(_storePath, "staging", token + ".json"), "not json"); - [Fact] - public async Task SaysSoWhenTheStoreCannotBeSwept() - { - // A store that cannot list what it holds cannot be swept. Degrade loudly: - // silence here means staged uploads accumulating unnoticed. - var logger = new RecordingLogger(); - var target = new StoragePackageStagingService(Mock.Of(), _time.Object, logger); + Assert.Equal(1, await _target.SweepAsync(_now.AddHours(-1), CancellationToken.None)); + Assert.Empty(await _storage.ListAsync("staging", CancellationToken.None)); + } - Assert.Equal(0, await target.SweepAsync(_now, CancellationToken.None)); + [Fact] + public async Task SaysSoWhenTheStoreCannotBeSwept() + { + // A store that cannot list what it holds cannot be swept. Degrade loudly: + // silence here means staged uploads accumulating unnoticed. + var logger = new RecordingLogger(); + var target = new StoragePackageStagingService(Mock.Of(), _time.Object, logger); - var warning = Assert.Single(logger.Entries.Where(e => e.Level == LogLevel.Warning)); - Assert.Contains("sweep", warning.Message, StringComparison.OrdinalIgnoreCase); - } + Assert.Equal(0, await target.SweepAsync(_now, CancellationToken.None)); + + var warning = Assert.Single(logger.Entries.Where(e => e.Level == LogLevel.Warning)); + Assert.Contains("sweep", warning.Message, StringComparison.OrdinalIgnoreCase); } + } - public class FactsBase : IDisposable + public class FactsBase : IDisposable + { + protected readonly string _storePath; + protected readonly FileStorageService _storage; + protected readonly Mock _time; + protected readonly StoragePackageStagingService _target; + + protected DateTime _now = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public FactsBase() { - protected readonly string _storePath; - protected readonly FileStorageService _storage; - protected readonly Mock _time; - protected readonly StoragePackageStagingService _target; + _storePath = Path.Combine(Path.GetTempPath(), "BaGetStagingTests", Guid.NewGuid().ToString("N")); - protected DateTime _now = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var options = new Mock>(); + options.Setup(o => o.Value).Returns(() => new FileSystemStorageOptions { Path = _storePath }); - public FactsBase() - { - _storePath = Path.Combine(Path.GetTempPath(), "BaGetStagingTests", Guid.NewGuid().ToString("N")); + _storage = new FileStorageService(options.Object); - var options = new Mock>(); - options.Setup(o => o.Value).Returns(() => new FileSystemStorageOptions { Path = _storePath }); + _time = new Mock(); + _time.Setup(t => t.UtcNow).Returns(() => _now); - _storage = new FileStorageService(options.Object); + _target = new StoragePackageStagingService( + _storage, + _time.Object, + new RecordingLogger()); + } - _time = new Mock(); - _time.Setup(t => t.UtcNow).Returns(() => _now); + protected Stream StringStream(string input) => new MemoryStream(Encoding.UTF8.GetBytes(input)); - _target = new StoragePackageStagingService( - _storage, - _time.Object, - new RecordingLogger()); - } + protected async Task ToStringAsync(Stream input) + { + using var reader = new StreamReader(input); - protected Stream StringStream(string input) => new MemoryStream(Encoding.UTF8.GetBytes(input)); + return await reader.ReadToEndAsync(); + } - protected async Task ToStringAsync(Stream input) + public void Dispose() + { + try { - using var reader = new StreamReader(input); - - return await reader.ReadToEndAsync(); + Directory.Delete(_storePath, recursive: true); } - - public void Dispose() + catch (DirectoryNotFoundException) { - try - { - Directory.Delete(_storePath, recursive: true); - } - catch (DirectoryNotFoundException) - { - } } } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/SymbolFileValidationTests.cs b/tests/BaGet.Core.Tests/Services/SymbolFileValidationTests.cs index 8fb853c71..a2ebc6ab9 100644 --- a/tests/BaGet.Core.Tests/Services/SymbolFileValidationTests.cs +++ b/tests/BaGet.Core.Tests/Services/SymbolFileValidationTests.cs @@ -1,113 +1,112 @@ using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +/// +/// Entry paths inside a package are matched case-insensitively throughout NuGet, and a +/// symbol package built on a case-sensitive file system can legitimately carry +/// "Library.PDB". These cover the extension checks that decide whether a symbol package +/// is accepted and which of its entries are indexed as PDBs. +/// +public class SymbolFileValidationTests { - /// - /// Entry paths inside a package are matched case-insensitively throughout NuGet, and a - /// symbol package built on a case-sensitive file system can legitimately carry - /// "Library.PDB". These cover the extension checks that decide whether a symbol package - /// is accepted and which of its entries are indexed as PDBs. - /// - public class SymbolFileValidationTests + public class AreSymbolFilesValid { - public class AreSymbolFilesValid + [Theory] + [InlineData("lib/net8.0/Library.pdb")] + [InlineData("Library.nuspec")] + [InlineData("lib/net8.0/Library.xml")] + [InlineData("package/services/metadata/core-properties/abc.psmdcp")] + [InlineData("_rels/.rels")] + [InlineData("Library.p7s")] + public void AcceptsAnAllowedExtension(string entry) { - [Theory] - [InlineData("lib/net8.0/Library.pdb")] - [InlineData("Library.nuspec")] - [InlineData("lib/net8.0/Library.xml")] - [InlineData("package/services/metadata/core-properties/abc.psmdcp")] - [InlineData("_rels/.rels")] - [InlineData("Library.p7s")] - public void AcceptsAnAllowedExtension(string entry) - { - Assert.True(SymbolIndexingService.AreSymbolFilesValid(new[] { entry })); - } + Assert.True(SymbolIndexingService.AreSymbolFilesValid(new[] { entry })); + } - [Theory] - [InlineData("lib/net8.0/Library.PDB")] - [InlineData("lib/net8.0/Library.Pdb")] - [InlineData("Library.NUSPEC")] - [InlineData("lib/net8.0/Library.XML")] - public void AcceptsAnAllowedExtensionRegardlessOfCase(string entry) - { - Assert.True(SymbolIndexingService.AreSymbolFilesValid(new[] { entry })); - } + [Theory] + [InlineData("lib/net8.0/Library.PDB")] + [InlineData("lib/net8.0/Library.Pdb")] + [InlineData("Library.NUSPEC")] + [InlineData("lib/net8.0/Library.XML")] + public void AcceptsAnAllowedExtensionRegardlessOfCase(string entry) + { + Assert.True(SymbolIndexingService.AreSymbolFilesValid(new[] { entry })); + } - [Theory] - [InlineData("lib/net8.0/Library.dll")] - [InlineData("lib/net8.0/Library.exe")] - [InlineData("script.ps1")] - public void RejectsADisallowedExtension(string entry) - { - Assert.False(SymbolIndexingService.AreSymbolFilesValid(new[] { entry })); - } + [Theory] + [InlineData("lib/net8.0/Library.dll")] + [InlineData("lib/net8.0/Library.exe")] + [InlineData("script.ps1")] + public void RejectsADisallowedExtension(string entry) + { + Assert.False(SymbolIndexingService.AreSymbolFilesValid(new[] { entry })); + } - [Fact] - public void RejectsAnEntryWithNoExtension() - { - Assert.False(SymbolIndexingService.AreSymbolFilesValid(new[] { "README" })); - } + [Fact] + public void RejectsAnEntryWithNoExtension() + { + Assert.False(SymbolIndexingService.AreSymbolFilesValid(new[] { "README" })); + } - [Fact] - public void RejectsTheWholePackageWhenAnyEntryIsDisallowed() + [Fact] + public void RejectsTheWholePackageWhenAnyEntryIsDisallowed() + { + Assert.False(SymbolIndexingService.AreSymbolFilesValid(new[] { - Assert.False(SymbolIndexingService.AreSymbolFilesValid(new[] - { - "lib/net8.0/Library.pdb", - "lib/net8.0/Library.dll", - })); - } + "lib/net8.0/Library.pdb", + "lib/net8.0/Library.dll", + })); + } - [Fact] - public void AcceptsAPackageWhoseEntriesAreAllAllowed() + [Fact] + public void AcceptsAPackageWhoseEntriesAreAllAllowed() + { + Assert.True(SymbolIndexingService.AreSymbolFilesValid(new[] { - Assert.True(SymbolIndexingService.AreSymbolFilesValid(new[] - { - "Library.nuspec", - "lib/net8.0/Library.pdb", - "lib/net8.0/Library.xml", - "_rels/.rels", - })); - } + "Library.nuspec", + "lib/net8.0/Library.pdb", + "lib/net8.0/Library.xml", + "_rels/.rels", + })); + } - [Fact] - public void AcceptsAnEmptyPackage() - { - Assert.True(SymbolIndexingService.AreSymbolFilesValid(new string[0])); - } + [Fact] + public void AcceptsAnEmptyPackage() + { + Assert.True(SymbolIndexingService.AreSymbolFilesValid(new string[0])); } + } - public class IsPdbPath + public class IsPdbPath + { + [Theory] + [InlineData("lib/net8.0/Library.pdb")] + [InlineData("Library.pdb")] + public void IsTrueForAPdb(string path) { - [Theory] - [InlineData("lib/net8.0/Library.pdb")] - [InlineData("Library.pdb")] - public void IsTrueForAPdb(string path) - { - Assert.True(SymbolIndexingService.IsPdbPath(path)); - } + Assert.True(SymbolIndexingService.IsPdbPath(path)); + } - [Theory] - [InlineData("lib/net8.0/Library.PDB")] - [InlineData("lib/net8.0/Library.Pdb")] - public void IsTrueForAPdbRegardlessOfCase(string path) - { - // Otherwise the entry passes validation but is never indexed, and the - // symbol server silently serves nothing for it. - Assert.True(SymbolIndexingService.IsPdbPath(path)); - } + [Theory] + [InlineData("lib/net8.0/Library.PDB")] + [InlineData("lib/net8.0/Library.Pdb")] + public void IsTrueForAPdbRegardlessOfCase(string path) + { + // Otherwise the entry passes validation but is never indexed, and the + // symbol server silently serves nothing for it. + Assert.True(SymbolIndexingService.IsPdbPath(path)); + } - [Theory] - [InlineData("lib/net8.0/Library.dll")] - [InlineData("Library.nuspec")] - [InlineData("README")] - [InlineData("pdb")] - [InlineData("Library.pdb.txt")] - public void IsFalseForAnythingElse(string path) - { - Assert.False(SymbolIndexingService.IsPdbPath(path)); - } + [Theory] + [InlineData("lib/net8.0/Library.dll")] + [InlineData("Library.nuspec")] + [InlineData("README")] + [InlineData("pdb")] + [InlineData("Library.pdb.txt")] + public void IsFalseForAnythingElse(string path) + { + Assert.False(SymbolIndexingService.IsPdbPath(path)); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/SymbolIndexingServiceTests.cs b/tests/BaGet.Core.Tests/Services/SymbolIndexingServiceTests.cs index 06a47b2e0..725ca6adc 100644 --- a/tests/BaGet.Core.Tests/Services/SymbolIndexingServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/SymbolIndexingServiceTests.cs @@ -10,359 +10,358 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +/// +/// These drive with real .snupkg and .nupkg +/// archives built in memory, carrying assemblies and portable PDBs a compiler really +/// produced, so that every rejection reason is reached through the production code path. +/// +public class SymbolIndexingServiceTests { - /// - /// These drive with real .snupkg and .nupkg - /// archives built in memory, carrying assemblies and portable PDBs a compiler really - /// produced, so that every rejection reason is reached through the production code path. - /// - public class SymbolIndexingServiceTests + private const string PackageId = "Test.Package"; + private const string PackageVersion = "1.0.0"; + + // Two unrelated assemblies with their real portable PDBs. Entry names inside the test + // packages are deliberately not the assemblies' own names: nothing in the service may + // depend on a file name, only on the paths lining up and the signatures matching. + private static readonly byte[] LibraryDll = TestAssembly.ReadAssembly(typeof(SymbolIndexingService).Assembly); + private static readonly byte[] LibraryPdb = TestAssembly.ReadPdb(typeof(SymbolIndexingService).Assembly); + private static readonly Guid LibrarySignature = TestAssembly.DebugSignature(typeof(SymbolIndexingService).Assembly); + + private static readonly byte[] OtherDll = TestAssembly.ReadAssembly(typeof(SymbolIndexingServiceTests).Assembly); + private static readonly byte[] OtherPdb = TestAssembly.ReadPdb(typeof(SymbolIndexingServiceTests).Assembly); + private static readonly Guid OtherSignature = TestAssembly.DebugSignature(typeof(SymbolIndexingServiceTests).Assembly); + + private readonly Mock _packages; + private readonly Mock _packageStorage; + private readonly Mock _symbols; + private readonly RecordingLogger _logger; + private readonly List _saved; + private readonly SymbolIndexingService _target; + + public SymbolIndexingServiceTests() { - private const string PackageId = "Test.Package"; - private const string PackageVersion = "1.0.0"; - - // Two unrelated assemblies with their real portable PDBs. Entry names inside the test - // packages are deliberately not the assemblies' own names: nothing in the service may - // depend on a file name, only on the paths lining up and the signatures matching. - private static readonly byte[] LibraryDll = TestAssembly.ReadAssembly(typeof(SymbolIndexingService).Assembly); - private static readonly byte[] LibraryPdb = TestAssembly.ReadPdb(typeof(SymbolIndexingService).Assembly); - private static readonly Guid LibrarySignature = TestAssembly.DebugSignature(typeof(SymbolIndexingService).Assembly); - - private static readonly byte[] OtherDll = TestAssembly.ReadAssembly(typeof(SymbolIndexingServiceTests).Assembly); - private static readonly byte[] OtherPdb = TestAssembly.ReadPdb(typeof(SymbolIndexingServiceTests).Assembly); - private static readonly Guid OtherSignature = TestAssembly.DebugSignature(typeof(SymbolIndexingServiceTests).Assembly); - - private readonly Mock _packages; - private readonly Mock _packageStorage; - private readonly Mock _symbols; - private readonly RecordingLogger _logger; - private readonly List _saved; - private readonly SymbolIndexingService _target; - - public SymbolIndexingServiceTests() - { - _packages = new Mock(); - _packageStorage = new Mock(); - _symbols = new Mock(); - _logger = new RecordingLogger(); - _saved = new List(); - - _symbols - .Setup(s => s.SavePortablePdbContentAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback((string file, string key, Stream content, CancellationToken _) => - { - using var copy = new MemoryStream(); - content.CopyTo(copy); - - _saved.Add(new SavedPdb(file, key, copy.ToArray())); - }) - .Returns(Task.CompletedTask); - - _target = new SymbolIndexingService( - _packages.Object, - _packageStorage.Object, - _symbols.Object, - _logger); - } + _packages = new Mock(); + _packageStorage = new Mock(); + _symbols = new Mock(); + _logger = new RecordingLogger(); + _saved = new List(); + + _symbols + .Setup(s => s.SavePortablePdbContentAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Callback((string file, string key, Stream content, CancellationToken _) => + { + using var copy = new MemoryStream(); + content.CopyTo(copy); + + _saved.Add(new SavedPdb(file, key, copy.ToArray())); + }) + .Returns(Task.CompletedTask); + + _target = new SymbolIndexingService( + _packages.Object, + _packageStorage.Object, + _symbols.Object, + _logger); + } - [Fact] - public async Task IfSnupkgHasEntryThatExtractsOutsideOfExtractionPath_ReturnsInvalidSymbolPackage() - { - // An entry whose path climbs out of the extraction directory would overwrite files - // elsewhere on the server when extracted. - using var snupkg = TestPackage.CreateSymbols( - files: new Dictionary { { "../../evil.pdb", "not a pdb" } }); - - var result = await _target.IndexAsync(snupkg, default); - - Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); - Assert.Empty(_saved); - AssertRejectionWasExplained("not safe to extract"); - - // The package is rejected before it is even looked up. - _packages.Verify( - p => p.FindOrNullAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny()), - Times.Never); - } + [Fact] + public async Task IfSnupkgHasEntryThatExtractsOutsideOfExtractionPath_ReturnsInvalidSymbolPackage() + { + // An entry whose path climbs out of the extraction directory would overwrite files + // elsewhere on the server when extracted. + using var snupkg = TestPackage.CreateSymbols( + files: new Dictionary { { "../../evil.pdb", "not a pdb" } }); + + var result = await _target.IndexAsync(snupkg, default); + + Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); + Assert.Empty(_saved); + AssertRejectionWasExplained("not safe to extract"); + + // The package is rejected before it is even looked up. + _packages.Verify( + p => p.FindOrNullAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Never); + } - [Fact] - public async Task IfSnupkgContainsEntryWithInvalidExtension_ReturnsInvalidSymbolPackage() - { - // A symbol package may only carry symbols and packaging metadata. An assembly in - // there would let an upload replace the package's own content. - GivenPackageExists(TestPackage.CreateMinimal( - binaryFiles: new Dictionary { { "lib/net8.0/Library.dll", LibraryDll } })); - - using var snupkg = TestPackage.CreateSymbols( - binaryFiles: new Dictionary - { - { "lib/net8.0/Library.pdb", LibraryPdb }, - { "lib/net8.0/Library.dll", LibraryDll }, - }); - - var result = await _target.IndexAsync(snupkg, default); - - Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); - Assert.Empty(_saved); - AssertRejectionWasExplained("lib/net8.0/Library.dll"); - } + [Fact] + public async Task IfSnupkgContainsEntryWithInvalidExtension_ReturnsInvalidSymbolPackage() + { + // A symbol package may only carry symbols and packaging metadata. An assembly in + // there would let an upload replace the package's own content. + GivenPackageExists(TestPackage.CreateMinimal( + binaryFiles: new Dictionary { { "lib/net8.0/Library.dll", LibraryDll } })); - [Fact] - public async Task IfSnupkgDoesNotHaveCorrespondingNupkg_ReturnsPackageNotFound() - { - GivenPackageDoesNotExist(); + using var snupkg = TestPackage.CreateSymbols( + binaryFiles: new Dictionary + { + { "lib/net8.0/Library.pdb", LibraryPdb }, + { "lib/net8.0/Library.dll", LibraryDll }, + }); - using var snupkg = TestPackage.CreateSymbols( - binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", LibraryPdb } }); + var result = await _target.IndexAsync(snupkg, default); - var result = await _target.IndexAsync(snupkg, default); + Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); + Assert.Empty(_saved); + AssertRejectionWasExplained("lib/net8.0/Library.dll"); + } - Assert.Equal(SymbolIndexingResult.PackageNotFound, result); - Assert.Empty(_saved); - } + [Fact] + public async Task IfSnupkgDoesNotHaveCorrespondingNupkg_ReturnsPackageNotFound() + { + GivenPackageDoesNotExist(); - [Fact] - public async Task IfSnupkgContainsInvalidPortablePdb_ReturnsInvalidSymbolPackage() - { - // Have two pdb entries, the first of which is valid. Ensure nothing is persisted. - GivenPackageExists(TestPackage.CreateMinimal( - binaryFiles: new Dictionary - { - { "lib/net8.0/Library.dll", LibraryDll }, - { "lib/net8.0/Broken.dll", OtherDll }, - })); - - using var snupkg = TestPackage.CreateSymbols( - files: new Dictionary { { "lib/net8.0/Broken.pdb", "this is not a pdb at all" } }, - binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", LibraryPdb } }); - - var result = await _target.IndexAsync(snupkg, default); - - Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); - Assert.Empty(_saved); - AssertRejectionWasExplained("lib/net8.0/Broken.pdb", "not a portable PDB"); - AssertNothingWasLoggedAsAnException(); - } + using var snupkg = TestPackage.CreateSymbols( + binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", LibraryPdb } }); - [Fact] - public async Task IfSnupkgContainsWindowsPdb_ReturnsInvalidSymbolPackage() - { - // A Windows PDB is a different format entirely - the symbol server cannot key it - - // so it must be rejected rather than crash the metadata reader. - GivenPackageExists(TestPackage.CreateMinimal( - binaryFiles: new Dictionary { { "lib/net8.0/Library.dll", LibraryDll } })); + var result = await _target.IndexAsync(snupkg, default); - using var snupkg = TestPackage.CreateSymbols( - binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", WindowsPdbHeader() } }); + Assert.Equal(SymbolIndexingResult.PackageNotFound, result); + Assert.Empty(_saved); + } - var result = await _target.IndexAsync(snupkg, default); + [Fact] + public async Task IfSnupkgContainsInvalidPortablePdb_ReturnsInvalidSymbolPackage() + { + // Have two pdb entries, the first of which is valid. Ensure nothing is persisted. + GivenPackageExists(TestPackage.CreateMinimal( + binaryFiles: new Dictionary + { + { "lib/net8.0/Library.dll", LibraryDll }, + { "lib/net8.0/Broken.dll", OtherDll }, + })); - Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); - Assert.Empty(_saved); - AssertRejectionWasExplained("lib/net8.0/Library.pdb", "not a portable PDB"); - AssertNothingWasLoggedAsAnException(); - } + using var snupkg = TestPackage.CreateSymbols( + files: new Dictionary { { "lib/net8.0/Broken.pdb", "this is not a pdb at all" } }, + binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", LibraryPdb } }); - [Fact] - public async Task IfSnupkgContainsEmptyPdb_ReturnsInvalidSymbolPackage() - { - // Shorter than the portable PDB signature: the signature check must not read past - // the end of the entry. - GivenPackageExists(TestPackage.CreateMinimal( - binaryFiles: new Dictionary { { "lib/net8.0/Library.dll", LibraryDll } })); + var result = await _target.IndexAsync(snupkg, default); - using var snupkg = TestPackage.CreateSymbols( - binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", new byte[0] } }); + Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); + Assert.Empty(_saved); + AssertRejectionWasExplained("lib/net8.0/Broken.pdb", "not a portable PDB"); + AssertNothingWasLoggedAsAnException(); + } - var result = await _target.IndexAsync(snupkg, default); + [Fact] + public async Task IfSnupkgContainsWindowsPdb_ReturnsInvalidSymbolPackage() + { + // A Windows PDB is a different format entirely - the symbol server cannot key it - + // so it must be rejected rather than crash the metadata reader. + GivenPackageExists(TestPackage.CreateMinimal( + binaryFiles: new Dictionary { { "lib/net8.0/Library.dll", LibraryDll } })); - Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); - Assert.Empty(_saved); - AssertRejectionWasExplained("lib/net8.0/Library.pdb", "not a portable PDB"); - AssertNothingWasLoggedAsAnException(); - } + using var snupkg = TestPackage.CreateSymbols( + binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", WindowsPdbHeader() } }); - [Fact] - public async Task IfSnupkgPdbDoesNotHaveCorrespondingNupkgDll_ReturnsInvalidSymbolPackage() - { - // The package ships no assembly at the PDB's path, so the symbols describe code - // that is not in the package. - GivenPackageExists(TestPackage.CreateMinimal( - binaryFiles: new Dictionary { { "lib/net8.0/Elsewhere.dll", LibraryDll } })); + var result = await _target.IndexAsync(snupkg, default); - using var snupkg = TestPackage.CreateSymbols( - binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", LibraryPdb } }); + Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); + Assert.Empty(_saved); + AssertRejectionWasExplained("lib/net8.0/Library.pdb", "not a portable PDB"); + AssertNothingWasLoggedAsAnException(); + } - var result = await _target.IndexAsync(snupkg, default); + [Fact] + public async Task IfSnupkgContainsEmptyPdb_ReturnsInvalidSymbolPackage() + { + // Shorter than the portable PDB signature: the signature check must not read past + // the end of the entry. + GivenPackageExists(TestPackage.CreateMinimal( + binaryFiles: new Dictionary { { "lib/net8.0/Library.dll", LibraryDll } })); - Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); - Assert.Empty(_saved); - AssertRejectionWasExplained("lib/net8.0/Library.pdb", "no corresponding assembly"); - } + using var snupkg = TestPackage.CreateSymbols( + binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", new byte[0] } }); - [Fact] - public async Task IfSnupkgPdbDoesNotDescribeCorrespondingNupkgDll_ReturnsInvalidSymbolPackage() - { - // The names line up but the PDB belongs to a different assembly, so it would serve - // the wrong sources for the package's code. - GivenPackageExists(TestPackage.CreateMinimal( - binaryFiles: new Dictionary { { "lib/net8.0/Library.dll", OtherDll } })); + var result = await _target.IndexAsync(snupkg, default); - using var snupkg = TestPackage.CreateSymbols( - binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", LibraryPdb } }); + Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); + Assert.Empty(_saved); + AssertRejectionWasExplained("lib/net8.0/Library.pdb", "not a portable PDB"); + AssertNothingWasLoggedAsAnException(); + } - var result = await _target.IndexAsync(snupkg, default); + [Fact] + public async Task IfSnupkgPdbDoesNotHaveCorrespondingNupkgDll_ReturnsInvalidSymbolPackage() + { + // The package ships no assembly at the PDB's path, so the symbols describe code + // that is not in the package. + GivenPackageExists(TestPackage.CreateMinimal( + binaryFiles: new Dictionary { { "lib/net8.0/Elsewhere.dll", LibraryDll } })); - Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); - Assert.Empty(_saved); - AssertRejectionWasExplained("lib/net8.0/Library.pdb", "does not describe", "lib/net8.0/Library.dll"); - } + using var snupkg = TestPackage.CreateSymbols( + binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", LibraryPdb } }); - [Fact] - public async Task SavesPdbs() - { - GivenPackageExists(TestPackage.CreateMinimal( - binaryFiles: new Dictionary - { - { "lib/net8.0/Library.dll", LibraryDll }, - { "lib/net8.0/Other.dll", OtherDll }, - })); - - using var snupkg = TestPackage.CreateSymbols( - binaryFiles: new Dictionary - { - { "lib/net8.0/Library.pdb", LibraryPdb }, - { "lib/net8.0/Other.pdb", OtherPdb }, - }); - - var result = await _target.IndexAsync(snupkg, default); - - Assert.Equal(SymbolIndexingResult.Success, result); - Assert.Equal(2, _saved.Count); - - AssertSaved("library.pdb", LibrarySignature, LibraryPdb); - AssertSaved("other.pdb", OtherSignature, OtherPdb); - } + var result = await _target.IndexAsync(snupkg, default); - [Fact] - public async Task IfNupkgShipsTheAssemblyAsAnExecutable_SavesPdbs() - { - // A PDB next to a tool's .exe is just as valid as one next to a library's .dll. - GivenPackageExists(TestPackage.CreateMinimal( - binaryFiles: new Dictionary { { "tools/Library.exe", LibraryDll } })); + Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); + Assert.Empty(_saved); + AssertRejectionWasExplained("lib/net8.0/Library.pdb", "no corresponding assembly"); + } - using var snupkg = TestPackage.CreateSymbols( - binaryFiles: new Dictionary { { "tools/Library.pdb", LibraryPdb } }); + [Fact] + public async Task IfSnupkgPdbDoesNotDescribeCorrespondingNupkgDll_ReturnsInvalidSymbolPackage() + { + // The names line up but the PDB belongs to a different assembly, so it would serve + // the wrong sources for the package's code. + GivenPackageExists(TestPackage.CreateMinimal( + binaryFiles: new Dictionary { { "lib/net8.0/Library.dll", OtherDll } })); - var result = await _target.IndexAsync(snupkg, default); + using var snupkg = TestPackage.CreateSymbols( + binaryFiles: new Dictionary { { "lib/net8.0/Library.pdb", LibraryPdb } }); - Assert.Equal(SymbolIndexingResult.Success, result); + var result = await _target.IndexAsync(snupkg, default); - AssertSaved("library.pdb", LibrarySignature, LibraryPdb); - } + Assert.Equal(SymbolIndexingResult.InvalidSymbolPackage, result); + Assert.Empty(_saved); + AssertRejectionWasExplained("lib/net8.0/Library.pdb", "does not describe", "lib/net8.0/Library.dll"); + } - [Fact] - public async Task IfSnupkgHasNoPdbs_ReturnsSuccessWithoutSavingAnything() - { - GivenPackageExists(TestPackage.CreateMinimal()); + [Fact] + public async Task SavesPdbs() + { + GivenPackageExists(TestPackage.CreateMinimal( + binaryFiles: new Dictionary + { + { "lib/net8.0/Library.dll", LibraryDll }, + { "lib/net8.0/Other.dll", OtherDll }, + })); - using var snupkg = TestPackage.CreateSymbols(); + using var snupkg = TestPackage.CreateSymbols( + binaryFiles: new Dictionary + { + { "lib/net8.0/Library.pdb", LibraryPdb }, + { "lib/net8.0/Other.pdb", OtherPdb }, + }); - var result = await _target.IndexAsync(snupkg, default); + var result = await _target.IndexAsync(snupkg, default); - Assert.Equal(SymbolIndexingResult.Success, result); - Assert.Empty(_saved); - } + Assert.Equal(SymbolIndexingResult.Success, result); + Assert.Equal(2, _saved.Count); - /// - /// A rejected upload must be diagnosable: an error naming the reason has to reach the - /// log, otherwise all the operator sees is "invalid symbol package". - /// - private void AssertRejectionWasExplained(params string[] expected) - { - var errors = _logger.Errors.ToList(); + AssertSaved("library.pdb", LibrarySignature, LibraryPdb); + AssertSaved("other.pdb", OtherSignature, OtherPdb); + } - Assert.NotEmpty(errors); - Assert.Contains( - errors, - error => expected.All(text => error.Message.Contains(text, StringComparison.OrdinalIgnoreCase))); - } + [Fact] + public async Task IfNupkgShipsTheAssemblyAsAnExecutable_SavesPdbs() + { + // A PDB next to a tool's .exe is just as valid as one next to a library's .dll. + GivenPackageExists(TestPackage.CreateMinimal( + binaryFiles: new Dictionary { { "tools/Library.exe", LibraryDll } })); - /// - /// The reason must be stated rather than left for the reader to infer from a stack - /// trace thrown out of a parser. - /// - private void AssertNothingWasLoggedAsAnException() - { - Assert.DoesNotContain(_logger.Entries, entry => entry.Exception != null); - } + using var snupkg = TestPackage.CreateSymbols( + binaryFiles: new Dictionary { { "tools/Library.pdb", LibraryPdb } }); - private void AssertSaved(string fileName, Guid signature, byte[] expectedContent) - { - var saved = Assert.Single(_saved.Where(p => p.File == fileName)); + var result = await _target.IndexAsync(snupkg, default); - // The symbol server key is the signature GUID followed by the age, which is always - // "ffffffff" for a portable PDB. - // See: https://github.com/dotnet/symstore/blob/main/docs/specs/SSQP_Key_Conventions.md#portable-pdb-signature - Assert.Equal($"{signature.ToString("N").ToUpperInvariant()}ffffffff", saved.Key); + Assert.Equal(SymbolIndexingResult.Success, result); - // The PDB is stored byte for byte, so a debugger gets back what was uploaded. - Assert.Equal(expectedContent, saved.Content); - } + AssertSaved("library.pdb", LibrarySignature, LibraryPdb); + } - private void GivenPackageExists(MemoryStream nupkg) - { - var version = NuGetVersion.Parse(PackageVersion); + [Fact] + public async Task IfSnupkgHasNoPdbs_ReturnsSuccessWithoutSavingAnything() + { + GivenPackageExists(TestPackage.CreateMinimal()); - _packages - .Setup(p => p.FindOrNullAsync(PackageId, version, true, It.IsAny())) - .ReturnsAsync(new Package { Id = PackageId, Version = version }); + using var snupkg = TestPackage.CreateSymbols(); - _packageStorage - .Setup(s => s.GetPackageStreamAsync(PackageId, version, It.IsAny())) - .ReturnsAsync(nupkg); - } + var result = await _target.IndexAsync(snupkg, default); - private void GivenPackageDoesNotExist() - { - _packages - .Setup(p => p.FindOrNullAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .ReturnsAsync((Package)null); - } + Assert.Equal(SymbolIndexingResult.Success, result); + Assert.Empty(_saved); + } - /// - /// The header of a Windows PDB, which is what MSBuild emits for DebugType=full. - /// - private static byte[] WindowsPdbHeader() - { - return Encoding.ASCII.GetBytes("Microsoft C/C++ MSF 7.00\r\n\u001aDS\0\0\0"); - } + /// + /// A rejected upload must be diagnosable: an error naming the reason has to reach the + /// log, otherwise all the operator sees is "invalid symbol package". + /// + private void AssertRejectionWasExplained(params string[] expected) + { + var errors = _logger.Errors.ToList(); + + Assert.NotEmpty(errors); + Assert.Contains( + errors, + error => expected.All(text => error.Message.Contains(text, StringComparison.OrdinalIgnoreCase))); + } + + /// + /// The reason must be stated rather than left for the reader to infer from a stack + /// trace thrown out of a parser. + /// + private void AssertNothingWasLoggedAsAnException() + { + Assert.DoesNotContain(_logger.Entries, entry => entry.Exception != null); + } + + private void AssertSaved(string fileName, Guid signature, byte[] expectedContent) + { + var saved = Assert.Single(_saved.Where(p => p.File == fileName)); + + // The symbol server key is the signature GUID followed by the age, which is always + // "ffffffff" for a portable PDB. + // See: https://github.com/dotnet/symstore/blob/main/docs/specs/SSQP_Key_Conventions.md#portable-pdb-signature + Assert.Equal($"{signature.ToString("N").ToUpperInvariant()}ffffffff", saved.Key); + + // The PDB is stored byte for byte, so a debugger gets back what was uploaded. + Assert.Equal(expectedContent, saved.Content); + } + + private void GivenPackageExists(MemoryStream nupkg) + { + var version = NuGetVersion.Parse(PackageVersion); + + _packages + .Setup(p => p.FindOrNullAsync(PackageId, version, true, It.IsAny())) + .ReturnsAsync(new Package { Id = PackageId, Version = version }); + + _packageStorage + .Setup(s => s.GetPackageStreamAsync(PackageId, version, It.IsAny())) + .ReturnsAsync(nupkg); + } + + private void GivenPackageDoesNotExist() + { + _packages + .Setup(p => p.FindOrNullAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .ReturnsAsync((Package)null); + } + + /// + /// The header of a Windows PDB, which is what MSBuild emits for DebugType=full. + /// + private static byte[] WindowsPdbHeader() + { + return Encoding.ASCII.GetBytes("Microsoft C/C++ MSF 7.00\r\n\u001aDS\0\0\0"); + } - private sealed class SavedPdb + private sealed class SavedPdb + { + public SavedPdb(string file, string key, byte[] content) { - public SavedPdb(string file, string key, byte[] content) - { - File = file; - Key = key; - Content = content; - } - - public string File { get; } - public string Key { get; } - public byte[] Content { get; } + File = file; + Key = key; + Content = content; } + + public string File { get; } + public string Key { get; } + public byte[] Content { get; } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Services/SymbolStorageServiceTests.cs b/tests/BaGet.Core.Tests/Services/SymbolStorageServiceTests.cs index a45e1d988..d1eb0ac61 100644 --- a/tests/BaGet.Core.Tests/Services/SymbolStorageServiceTests.cs +++ b/tests/BaGet.Core.Tests/Services/SymbolStorageServiceTests.cs @@ -1,68 +1,67 @@ using System.Threading.Tasks; using Xunit; -namespace BaGet.Core.Tests.Services +namespace BaGet.Core.Tests.Services; + +public class SymbolStorageServiceTests { - public class SymbolStorageServiceTests + public class SavePortablePdbContentAsync { - public class SavePortablePdbContentAsync + [Fact] + public async Task ThrowsIfFileNameIsInvalid() { - [Fact] - public async Task ThrowsIfFileNameIsInvalid() - { - await Task.CompletedTask; - } + await Task.CompletedTask; + } - [Fact] - public async Task ThrowsIfKeyIsInvalid() - { - await Task.CompletedTask; - } + [Fact] + public async Task ThrowsIfKeyIsInvalid() + { + await Task.CompletedTask; + } - [Fact] - public async Task SavesPdb() - { - await Task.CompletedTask; - } + [Fact] + public async Task SavesPdb() + { + await Task.CompletedTask; + } - [Fact] - public async Task IfPdbAlreadyExistsButHasDifferentContent_Fails() - { - await Task.CompletedTask; - } + [Fact] + public async Task IfPdbAlreadyExistsButHasDifferentContent_Fails() + { + await Task.CompletedTask; + } - [Fact] - public async Task IfPdbAlreadyExistsButHasSameContent_Succeeds() - { - await Task.CompletedTask; - } + [Fact] + public async Task IfPdbAlreadyExistsButHasSameContent_Succeeds() + { + await Task.CompletedTask; } + } - public class GetPortablePdbContentStreamOrNullAsync + public class GetPortablePdbContentStreamOrNullAsync + { + [Fact] + public async Task ThrowsIfFileNameIsInvalid() { - [Fact] - public async Task ThrowsIfFileNameIsInvalid() - { - await Task.CompletedTask; - } + await Task.CompletedTask; + } - [Fact] - public async Task ThrowsIfKeyIsInvalid() - { - await Task.CompletedTask; - } + [Fact] + public async Task ThrowsIfKeyIsInvalid() + { + await Task.CompletedTask; + } - [Fact] - public async Task ReturnsNullIfPdbDoesNotExist() - { - await Task.CompletedTask; - } + [Fact] + public async Task ReturnsNullIfPdbDoesNotExist() + { + await Task.CompletedTask; + } - [Fact] - public async Task ReturnsPdb() - { - await Task.CompletedTask; - } + [Fact] + public async Task ReturnsPdb() + { + await Task.CompletedTask; } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Support/RecordingLogger.cs b/tests/BaGet.Core.Tests/Support/RecordingLogger.cs index b85397512..a64886a83 100644 --- a/tests/BaGet.Core.Tests/Support/RecordingLogger.cs +++ b/tests/BaGet.Core.Tests/Support/RecordingLogger.cs @@ -3,56 +3,55 @@ using System.Linq; using Microsoft.Extensions.Logging; -namespace BaGet.Core.Tests.Support +namespace BaGet.Core.Tests.Support; + +/// +/// An that keeps what was logged, so a test can assert that a +/// rejection said why it happened. A rejection whose only trace is a stack trace, or no +/// trace at all, cannot be diagnosed by whoever uploaded the package. +/// +public class RecordingLogger : ILogger { - /// - /// An that keeps what was logged, so a test can assert that a - /// rejection said why it happened. A rejection whose only trace is a stack trace, or no - /// trace at all, cannot be diagnosed by whoever uploaded the package. - /// - public class RecordingLogger : ILogger - { - private readonly List _entries = new List(); + private readonly List _entries = new List(); - public IReadOnlyList Entries => _entries; + public IReadOnlyList Entries => _entries; - public IEnumerable Errors => _entries.Where(e => e.Level == LogLevel.Error); + public IEnumerable Errors => _entries.Where(e => e.Level == LogLevel.Error); - public IDisposable BeginScope(TState state) => new NoopScope(); + public IDisposable BeginScope(TState state) => new NoopScope(); - public bool IsEnabled(LogLevel logLevel) => true; + public bool IsEnabled(LogLevel logLevel) => true; - public void Log( - LogLevel logLevel, - EventId eventId, - TState state, - Exception exception, - Func formatter) - { - _entries.Add(new LogEntry(logLevel, formatter(state, exception), exception)); - } + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception exception, + Func formatter) + { + _entries.Add(new LogEntry(logLevel, formatter(state, exception), exception)); + } - public class LogEntry + public class LogEntry + { + public LogEntry(LogLevel level, string message, Exception exception) { - public LogEntry(LogLevel level, string message, Exception exception) - { - Level = level; - Message = message; - Exception = exception; - } - - public LogLevel Level { get; } - public string Message { get; } - public Exception Exception { get; } - - public override string ToString() => $"{Level}: {Message}"; + Level = level; + Message = message; + Exception = exception; } - private class NoopScope : IDisposable + public LogLevel Level { get; } + public string Message { get; } + public Exception Exception { get; } + + public override string ToString() => $"{Level}: {Message}"; + } + + private class NoopScope : IDisposable + { + public void Dispose() { - public void Dispose() - { - } } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Support/TestAssembly.cs b/tests/BaGet.Core.Tests/Support/TestAssembly.cs index c1f362dc6..723c11d4e 100644 --- a/tests/BaGet.Core.Tests/Support/TestAssembly.cs +++ b/tests/BaGet.Core.Tests/Support/TestAssembly.cs @@ -4,66 +4,65 @@ using System.Reflection; using System.Reflection.PortableExecutable; -namespace BaGet.Core.Tests.Support +namespace BaGet.Core.Tests.Support; + +/// +/// The bytes of assemblies that were really compiled, together with their real portable +/// PDBs, so symbol handling can be exercised against files a compiler produced instead of +/// hand written stand ins. The test project itself and the libraries it references are +/// built with portable PDBs, which is exactly what a .snupkg carries. +/// +public static class TestAssembly { - /// - /// The bytes of assemblies that were really compiled, together with their real portable - /// PDBs, so symbol handling can be exercised against files a compiler produced instead of - /// hand written stand ins. The test project itself and the libraries it references are - /// built with portable PDBs, which is exactly what a .snupkg carries. - /// - public static class TestAssembly + /// The compiled assembly's own bytes. + public static byte[] ReadAssembly(Assembly assembly) { - /// The compiled assembly's own bytes. - public static byte[] ReadAssembly(Assembly assembly) - { - return File.ReadAllBytes(PathOf(assembly)); - } - - /// The portable PDB the assembly was compiled with. - public static byte[] ReadPdb(Assembly assembly) - { - var pdbPath = Path.ChangeExtension(PathOf(assembly), ".pdb"); + return File.ReadAllBytes(PathOf(assembly)); + } - if (!File.Exists(pdbPath)) - { - throw new InvalidOperationException( - $"{assembly.GetName().Name} was built without a portable PDB at '{pdbPath}'. " + - "These tests need one; build with the default DebugType."); - } + /// The portable PDB the assembly was compiled with. + public static byte[] ReadPdb(Assembly assembly) + { + var pdbPath = Path.ChangeExtension(PathOf(assembly), ".pdb"); - return File.ReadAllBytes(pdbPath); + if (!File.Exists(pdbPath)) + { + throw new InvalidOperationException( + $"{assembly.GetName().Name} was built without a portable PDB at '{pdbPath}'. " + + "These tests need one; build with the default DebugType."); } - /// - /// The debug signature GUID the assembly's CodeView debug directory entry points at, - /// which is the GUID its portable PDB carries. Read from the assembly rather than from - /// the PDB so that a test asserting a PDB's symbol server key has an independent source - /// for the expected value. - /// - public static Guid DebugSignature(Assembly assembly) - { - using var stream = File.OpenRead(PathOf(assembly)); - using var peReader = new PEReader(stream); + return File.ReadAllBytes(pdbPath); + } - var codeView = peReader - .ReadDebugDirectory() - .Single(entry => entry.Type == DebugDirectoryEntryType.CodeView); + /// + /// The debug signature GUID the assembly's CodeView debug directory entry points at, + /// which is the GUID its portable PDB carries. Read from the assembly rather than from + /// the PDB so that a test asserting a PDB's symbol server key has an independent source + /// for the expected value. + /// + public static Guid DebugSignature(Assembly assembly) + { + using var stream = File.OpenRead(PathOf(assembly)); + using var peReader = new PEReader(stream); - return peReader.ReadCodeViewDebugDirectoryData(codeView).Guid; - } + var codeView = peReader + .ReadDebugDirectory() + .Single(entry => entry.Type == DebugDirectoryEntryType.CodeView); - private static string PathOf(Assembly assembly) - { - var location = assembly.Location; + return peReader.ReadCodeViewDebugDirectoryData(codeView).Guid; + } - if (string.IsNullOrEmpty(location)) - { - throw new InvalidOperationException( - $"{assembly.GetName().Name} has no file on disk, so its bytes cannot be read."); - } + private static string PathOf(Assembly assembly) + { + var location = assembly.Location; - return location; + if (string.IsNullOrEmpty(location)) + { + throw new InvalidOperationException( + $"{assembly.GetName().Name} has no file on disk, so its bytes cannot be read."); } + + return location; } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Support/TestPackage.cs b/tests/BaGet.Core.Tests/Support/TestPackage.cs index 622733037..595cb9382 100644 --- a/tests/BaGet.Core.Tests/Support/TestPackage.cs +++ b/tests/BaGet.Core.Tests/Support/TestPackage.cs @@ -3,142 +3,141 @@ using System.IO.Compression; using System.Text; -namespace BaGet.Core.Tests.Support +namespace BaGet.Core.Tests.Support; + +/// +/// Builds a real .nupkg in memory so the package reading code can be exercised +/// without mocking it. +/// +public static class TestPackage { /// - /// Builds a real .nupkg in memory so the package reading code can be exercised - /// without mocking it. + /// The path of the nuspec within the archives this class builds. + /// + public const string NuspecPath = "Package.nuspec"; + + /// + /// Create a package whose nuspec holds as the inner XML + /// of its <metadata> element. /// - public static class TestPackage + public static MemoryStream Create( + string metadata, + IDictionary files = null, + IDictionary binaryFiles = null) { - /// - /// The path of the nuspec within the archives this class builds. - /// - public const string NuspecPath = "Package.nuspec"; - - /// - /// Create a package whose nuspec holds as the inner XML - /// of its <metadata> element. - /// - public static MemoryStream Create( - string metadata, - IDictionary files = null, - IDictionary binaryFiles = null) - { - var nuspec = $@" + var nuspec = $@" {metadata} "; - return Build(nuspec, files, binaryFiles); - } + return Build(nuspec, files, binaryFiles); + } - /// - /// Create a zip archive shaped like a package, but with no nuspec in it. - /// - public static MemoryStream CreateWithoutNuspec(IDictionary files = null) - { - return Build(nuspec: null, files: files); - } + /// + /// Create a zip archive shaped like a package, but with no nuspec in it. + /// + public static MemoryStream CreateWithoutNuspec(IDictionary files = null) + { + return Build(nuspec: null, files: files); + } - /// - /// A stream whose content is not a zip archive at all. - /// - public static MemoryStream NotAZipArchive() - { - return new MemoryStream(Encoding.UTF8.GetBytes("This is not a package, it is a text file.")); - } + /// + /// A stream whose content is not a zip archive at all. + /// + public static MemoryStream NotAZipArchive() + { + return new MemoryStream(Encoding.UTF8.GetBytes("This is not a package, it is a text file.")); + } + + private static MemoryStream Build( + string nuspec, + IDictionary files, + IDictionary binaryFiles = null) + { + var result = new MemoryStream(); - private static MemoryStream Build( - string nuspec, - IDictionary files, - IDictionary binaryFiles = null) + using (var archive = new ZipArchive(result, ZipArchiveMode.Create, leaveOpen: true)) { - var result = new MemoryStream(); + if (nuspec != null) + { + Write(archive, NuspecPath, nuspec); + } - using (var archive = new ZipArchive(result, ZipArchiveMode.Create, leaveOpen: true)) + foreach (var file in files ?? new Dictionary()) { - if (nuspec != null) - { - Write(archive, NuspecPath, nuspec); - } - - foreach (var file in files ?? new Dictionary()) - { - Write(archive, file.Key, file.Value); - } - - foreach (var file in binaryFiles ?? new Dictionary()) - { - Write(archive, file.Key, file.Value); - } + Write(archive, file.Key, file.Value); } - result.Position = 0; - return result; + foreach (var file in binaryFiles ?? new Dictionary()) + { + Write(archive, file.Key, file.Value); + } } - /// - /// Create a package with the minimum required metadata, plus whatever extra - /// elements are supplied. - /// - public static MemoryStream CreateMinimal( - string extraMetadata = "", - string id = "Test.Package", - string version = "1.0.0", - string authors = "Test Author", - IDictionary files = null, - IDictionary binaryFiles = null) - { - return Create( - $@" {id} + result.Position = 0; + return result; + } + + /// + /// Create a package with the minimum required metadata, plus whatever extra + /// elements are supplied. + /// + public static MemoryStream CreateMinimal( + string extraMetadata = "", + string id = "Test.Package", + string version = "1.0.0", + string authors = "Test Author", + IDictionary files = null, + IDictionary binaryFiles = null) + { + return Create( + $@" {id} {version} {authors} A test package. {extraMetadata}", - files, - binaryFiles); - } + files, + binaryFiles); + } - /// - /// Create a real symbol package (.snupkg) in memory: a package whose nuspec declares - /// the SymbolsPackage package type, as "dotnet pack --include-symbols" produces. - /// - public static MemoryStream CreateSymbols( - string id = "Test.Package", - string version = "1.0.0", - IDictionary files = null, - IDictionary binaryFiles = null) - { - return CreateMinimal( - extraMetadata: @" + /// + /// Create a real symbol package (.snupkg) in memory: a package whose nuspec declares + /// the SymbolsPackage package type, as "dotnet pack --include-symbols" produces. + /// + public static MemoryStream CreateSymbols( + string id = "Test.Package", + string version = "1.0.0", + IDictionary files = null, + IDictionary binaryFiles = null) + { + return CreateMinimal( + extraMetadata: @" ", - id: id, - version: version, - files: files, - binaryFiles: binaryFiles); - } + id: id, + version: version, + files: files, + binaryFiles: binaryFiles); + } - private static void Write(ZipArchive archive, string path, string content) - { - var entry = archive.CreateEntry(path); + private static void Write(ZipArchive archive, string path, string content) + { + var entry = archive.CreateEntry(path); - using var stream = entry.Open(); - using var writer = new StreamWriter(stream, new UTF8Encoding(false)); + using var stream = entry.Open(); + using var writer = new StreamWriter(stream, new UTF8Encoding(false)); - writer.Write(content); - } + writer.Write(content); + } - private static void Write(ZipArchive archive, string path, byte[] content) - { - var entry = archive.CreateEntry(path); + private static void Write(ZipArchive archive, string path, byte[] content) + { + var entry = archive.CreateEntry(path); - using var stream = entry.Open(); + using var stream = entry.Open(); - stream.Write(content, 0, content.Length); - } + stream.Write(content, 0, content.Length); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Upstream/PackageDownloadsJsonSourceTests.cs b/tests/BaGet.Core.Tests/Upstream/PackageDownloadsJsonSourceTests.cs index e49166e51..4113f7758 100644 --- a/tests/BaGet.Core.Tests/Upstream/PackageDownloadsJsonSourceTests.cs +++ b/tests/BaGet.Core.Tests/Upstream/PackageDownloadsJsonSourceTests.cs @@ -11,148 +11,147 @@ using Microsoft.Extensions.Logging.Abstractions; using Xunit; -namespace BaGet.Core.Tests.Upstream +namespace BaGet.Core.Tests.Upstream; + +/// +/// Parses the document nuget.org publishes at downloads.v1.json. Its shape is an array of +/// records, each one the package id followed by a pair per version: +/// +/// [ ["Package.Id", ["1.0.0", 42], ["2.0.0", 7]], ... ] +/// +public class PackageDownloadsJsonSourceTests { /// - /// Parses the document nuget.org publishes at downloads.v1.json. Its shape is an array of - /// records, each one the package id followed by a pair per version: - /// - /// [ ["Package.Id", ["1.0.0", 42], ["2.0.0", 7]], ... ] + /// Serves a fixed body, so the parser can be driven without a network. /// - public class PackageDownloadsJsonSourceTests + private class StubHandler : HttpMessageHandler { - /// - /// Serves a fixed body, so the parser can be driven without a network. - /// - private class StubHandler : HttpMessageHandler - { - private readonly string _body; + private readonly string _body; - public StubHandler(string body) => _body = body; + public StubHandler(string body) => _body = body; - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { - return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(Encoding.UTF8.GetBytes(_body)), - }); - } + Content = new ByteArrayContent(Encoding.UTF8.GetBytes(_body)), + }); } + } - private static Task>> ParseAsync(string document) - { - var client = new HttpClient(new StubHandler(document)); - var target = new PackageDownloadsJsonSource( - client, - NullLogger.Instance); + private static Task>> ParseAsync(string document) + { + var client = new HttpClient(new StubHandler(document)); + var target = new PackageDownloadsJsonSource( + client, + NullLogger.Instance); - return target.GetPackageDownloadsAsync(); - } + return target.GetPackageDownloadsAsync(); + } - [Fact] - public async Task ReadsAPackagesVersionsAndCounts() - { - var result = await ParseAsync(@"[[""Package.Id"",[""1.0.0"",42],[""2.0.0"",7]]]"); + [Fact] + public async Task ReadsAPackagesVersionsAndCounts() + { + var result = await ParseAsync(@"[[""Package.Id"",[""1.0.0"",42],[""2.0.0"",7]]]"); - var package = Assert.Single(result); - Assert.Equal("package.id", package.Key); - Assert.Equal(42, package.Value["1.0.0"]); - Assert.Equal(7, package.Value["2.0.0"]); - } + var package = Assert.Single(result); + Assert.Equal("package.id", package.Key); + Assert.Equal(42, package.Value["1.0.0"]); + Assert.Equal(7, package.Value["2.0.0"]); + } - [Fact] - public async Task LowercasesTheIdAndTheVersion() - { - // The importer looks packages up by their lowercased id. - var result = await ParseAsync(@"[[""Package.ID"",[""1.0.0-BETA"",1]]]"); + [Fact] + public async Task LowercasesTheIdAndTheVersion() + { + // The importer looks packages up by their lowercased id. + var result = await ParseAsync(@"[[""Package.ID"",[""1.0.0-BETA"",1]]]"); - Assert.Equal("package.id", Assert.Single(result).Key); - Assert.True(result["package.id"].ContainsKey("1.0.0-beta")); - } + Assert.Equal("package.id", Assert.Single(result).Key); + Assert.True(result["package.id"].ContainsKey("1.0.0-beta")); + } - [Fact] - public async Task NormalizesTheVersion() - { - var result = await ParseAsync(@"[[""Package.Id"",[""1.0.0.0"",5]]]"); + [Fact] + public async Task NormalizesTheVersion() + { + var result = await ParseAsync(@"[[""Package.Id"",[""1.0.0.0"",5]]]"); - Assert.True(result["package.id"].ContainsKey("1.0.0")); - } + Assert.True(result["package.id"].ContainsKey("1.0.0")); + } - [Fact] - public async Task ReadsEveryRecord() - { - var result = await ParseAsync( - @"[[""First"",[""1.0.0"",1]],[""Second"",[""1.0.0"",2]],[""Third"",[""1.0.0"",3]]]"); + [Fact] + public async Task ReadsEveryRecord() + { + var result = await ParseAsync( + @"[[""First"",[""1.0.0"",1]],[""Second"",[""1.0.0"",2]],[""Third"",[""1.0.0"",3]]]"); - Assert.Equal(new[] { "first", "second", "third" }, result.Keys.OrderBy(k => k)); - } + Assert.Equal(new[] { "first", "second", "third" }, result.Keys.OrderBy(k => k)); + } - [Fact] - public async Task ReadsADownloadCountBeyondTheRangeOfAnInt() - { - // The contract is a long. A package can plausibly pass two billion downloads, and - // the whole document is rejected if one entry overflows. - var count = (long)int.MaxValue + 1000; + [Fact] + public async Task ReadsADownloadCountBeyondTheRangeOfAnInt() + { + // The contract is a long. A package can plausibly pass two billion downloads, and + // the whole document is rejected if one entry overflows. + var count = (long)int.MaxValue + 1000; - var result = await ParseAsync( - @"[[""Package.Id"",[""1.0.0""," + count.ToString(CultureInfo.InvariantCulture) + "]]]"); + var result = await ParseAsync( + @"[[""Package.Id"",[""1.0.0""," + count.ToString(CultureInfo.InvariantCulture) + "]]]"); - Assert.Equal(count, result["package.id"]["1.0.0"]); - } + Assert.Equal(count, result["package.id"]["1.0.0"]); + } - [Fact] - public async Task AnEmptyDocumentYieldsNothing() - { - Assert.Empty(await ParseAsync("[]")); - } + [Fact] + public async Task AnEmptyDocumentYieldsNothing() + { + Assert.Empty(await ParseAsync("[]")); + } - [Fact] - public async Task ARecordWhoseSecondEntryIsNotAnArrayIsSkipped() - { - // Guards the existing check against malformed entries. - var result = await ParseAsync(@"[[""Package.Id"",""not-an-array""]]"); + [Fact] + public async Task ARecordWhoseSecondEntryIsNotAnArrayIsSkipped() + { + // Guards the existing check against malformed entries. + var result = await ParseAsync(@"[[""Package.Id"",""not-an-array""]]"); - Assert.DoesNotContain("package.id", result.Keys); - } + Assert.DoesNotContain("package.id", result.Keys); + } - [Fact] - public async Task AVersionlessRecordYieldsAnEmptyMap() - { - var result = await ParseAsync(@"[[""Package.Id""]]"); + [Fact] + public async Task AVersionlessRecordYieldsAnEmptyMap() + { + var result = await ParseAsync(@"[[""Package.Id""]]"); - Assert.Empty(result["package.id"]); - } + Assert.Empty(result["package.id"]); + } - [Fact] - public async Task LaterVersionsOfTheSameIdAreCombined() - { - var result = await ParseAsync( - @"[[""Package.Id"",[""1.0.0"",1]],[""Package.Id"",[""2.0.0"",2]]]"); + [Fact] + public async Task LaterVersionsOfTheSameIdAreCombined() + { + var result = await ParseAsync( + @"[[""Package.Id"",[""1.0.0"",1]],[""Package.Id"",[""2.0.0"",2]]]"); - var package = Assert.Single(result); - Assert.Equal(2, package.Value.Count); - } + var package = Assert.Single(result); + Assert.Equal(2, package.Value.Count); + } - [Fact] - public async Task DoesNotLeaveItsTemporaryFileBehind() + [Fact] + public async Task DoesNotLeaveItsTemporaryFileBehind() + { + // The document is spooled to disk rather than held in memory, so the file has to + // go when the stream is disposed. The spool file itself is checked: counting the + // temporary directory's files races with every other test that creates one. + var target = new PackageDownloadsJsonSource( + new HttpClient(new StubHandler(@"[[""Package.Id"",[""1.0.0"",1]]]")), + NullLogger.Instance); + + string path; + using (var stream = await target.GetDownloadsStreamAsync()) { - // The document is spooled to disk rather than held in memory, so the file has to - // go when the stream is disposed. The spool file itself is checked: counting the - // temporary directory's files races with every other test that creates one. - var target = new PackageDownloadsJsonSource( - new HttpClient(new StubHandler(@"[[""Package.Id"",[""1.0.0"",1]]]")), - NullLogger.Instance); - - string path; - using (var stream = await target.GetDownloadsStreamAsync()) - { - path = Assert.IsType(stream).Name; - Assert.True(File.Exists(path)); - } - - Assert.False(File.Exists(path), $"{path} was left behind"); + path = Assert.IsType(stream).Name; + Assert.True(File.Exists(path)); } + + Assert.False(File.Exists(path), $"{path} was left behind"); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Upstream/V3UpstreamClientTests.cs b/tests/BaGet.Core.Tests/Upstream/V3UpstreamClientTests.cs index 26306b38a..ef48dbec4 100644 --- a/tests/BaGet.Core.Tests/Upstream/V3UpstreamClientTests.cs +++ b/tests/BaGet.Core.Tests/Upstream/V3UpstreamClientTests.cs @@ -10,232 +10,231 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Core.Tests +namespace BaGet.Core.Tests; + +// The entity BaGet.Core.PackageDeprecation is reached through the enclosing namespace, +// which takes precedence over a file scoped using directive, so the alias has to live +// inside the namespace to name the protocol model instead. +using PackageDeprecation = BaGet.Protocol.Models.PackageDeprecation; + +public class V3UpstreamClientTests { - // The entity BaGet.Core.PackageDeprecation is reached through the enclosing namespace, - // which takes precedence over a file scoped using directive, so the alias has to live - // inside the namespace to name the protocol model instead. - using PackageDeprecation = BaGet.Protocol.Models.PackageDeprecation; + public class ListPackageVersionsAsync : FactsBase + { + [Fact] + public async Task ReturnsEmpty() + { + _client + .Setup(c => c.ListPackageVersionsAsync( + _id, + /*includeUnlisted: */ true, + _cancellation)) + .ReturnsAsync(new List()); + + var result = await _target.ListPackageVersionsAsync(_id, _cancellation); + + Assert.Empty(result); + } + + [Fact] + public async Task IgnoresExceptions() + { + _client + .Setup(c => c.ListPackageVersionsAsync( + _id, + /*includeUnlisted: */ true, + _cancellation)) + .ThrowsAsync(new InvalidDataException("Hello")); + + var result = await _target.ListPackageVersionsAsync(_id, _cancellation); + + Assert.Empty(result); + } - public class V3UpstreamClientTests + [Fact] + public async Task ReturnsPackages() + { + _client + .Setup(c => c.ListPackageVersionsAsync( + _id, + /*includeUnlisted: */ true, + _cancellation)) + .ReturnsAsync(new List { _version }); + + var result = await _target.ListPackageVersionsAsync(_id, _cancellation); + + var version = Assert.Single(result); + Assert.Equal(_version, version); + } + } + + public class ListPackagesAsync : FactsBase { - public class ListPackageVersionsAsync : FactsBase + [Fact] + public async Task ReturnsEmpty() + { + _client + .Setup(c => c.GetPackageMetadataAsync(_id, _cancellation)) + .ReturnsAsync(new List()); + + var result = await _target.ListPackagesAsync(_id, _cancellation); + + Assert.Empty(result); + } + + [Fact] + public async Task IgnoresExceptions() { - [Fact] - public async Task ReturnsEmpty() - { - _client - .Setup(c => c.ListPackageVersionsAsync( - _id, - /*includeUnlisted: */ true, - _cancellation)) - .ReturnsAsync(new List()); - - var result = await _target.ListPackageVersionsAsync(_id, _cancellation); - - Assert.Empty(result); - } - - [Fact] - public async Task IgnoresExceptions() - { - _client - .Setup(c => c.ListPackageVersionsAsync( - _id, - /*includeUnlisted: */ true, - _cancellation)) - .ThrowsAsync(new InvalidDataException("Hello")); - - var result = await _target.ListPackageVersionsAsync(_id, _cancellation); - - Assert.Empty(result); - } - - [Fact] - public async Task ReturnsPackages() - { - _client - .Setup(c => c.ListPackageVersionsAsync( - _id, - /*includeUnlisted: */ true, - _cancellation)) - .ReturnsAsync(new List { _version }); - - var result = await _target.ListPackageVersionsAsync(_id, _cancellation); - - var version = Assert.Single(result); - Assert.Equal(_version, version); - } + _client + .Setup(c => c.GetPackageMetadataAsync(_id, _cancellation)) + .ThrowsAsync(new InvalidDataException("Hello world")); + + var result = await _target.ListPackagesAsync(_id, _cancellation); + + Assert.Empty(result); } - public class ListPackagesAsync : FactsBase + [Fact] + public async Task ReturnsPackages() { - [Fact] - public async Task ReturnsEmpty() - { - _client - .Setup(c => c.GetPackageMetadataAsync(_id, _cancellation)) - .ReturnsAsync(new List()); - - var result = await _target.ListPackagesAsync(_id, _cancellation); - - Assert.Empty(result); - } - - [Fact] - public async Task IgnoresExceptions() - { - _client - .Setup(c => c.GetPackageMetadataAsync(_id, _cancellation)) - .ThrowsAsync(new InvalidDataException("Hello world")); - - var result = await _target.ListPackagesAsync(_id, _cancellation); - - Assert.Empty(result); - } - - [Fact] - public async Task ReturnsPackages() - { - var published = DateTimeOffset.Now; - - _client - .Setup(c => c.GetPackageMetadataAsync(_id, _cancellation)) - .ReturnsAsync(new List + var published = DateTimeOffset.Now; + + _client + .Setup(c => c.GetPackageMetadataAsync(_id, _cancellation)) + .ReturnsAsync(new List + { + new PackageMetadata { - new PackageMetadata + PackageId = "Foo", + Version = "1.2.3-prerelease+semver2", + Authors = "Author1, Author2", + Description = "Description", + IconUrl = "https://icon.test/", + Language = "Language", + LicenseUrl = "https://license.test/", + Listed = true, + MinClientVersion = "1.0.0", + PackageContentUrl = "https://content.test/", + Published = published, + RequireLicenseAcceptance = true, + Summary = "Summary", + Title = "Title", + + Tags = new List { "Tag1", "Tag2" }, + + Deprecation = new PackageDeprecation { - PackageId = "Foo", - Version = "1.2.3-prerelease+semver2", - Authors = "Author1, Author2", - Description = "Description", - IconUrl = "https://icon.test/", - Language = "Language", - LicenseUrl = "https://license.test/", - Listed = true, - MinClientVersion = "1.0.0", - PackageContentUrl = "https://content.test/", - Published = published, - RequireLicenseAcceptance = true, - Summary = "Summary", - Title = "Title", - - Tags = new List { "Tag1", "Tag2" }, - - Deprecation = new PackageDeprecation + Reasons = new List { "Reason1", "Reason2" }, + Message = "Message", + AlternatePackage = new AlternatePackage { - Reasons = new List { "Reason1", "Reason2" }, - Message = "Message", - AlternatePackage = new AlternatePackage - { - Id = "Alternate", - Range = "*", - }, + Id = "Alternate", + Range = "*", }, - DependencyGroups = new List + }, + DependencyGroups = new List + { + new DependencyGroupItem { - new DependencyGroupItem + TargetFramework = "Target Framework", + Dependencies = new List { - TargetFramework = "Target Framework", - Dependencies = new List + new DependencyItem { - new DependencyItem - { - Id = "Dependency", - Range = "1.0.0", - } + Id = "Dependency", + Range = "1.0.0", } } } } - }); - - var result = await _target.ListPackagesAsync(_id, _cancellation); - - var package = Assert.Single(result); - - Assert.Equal("Foo", package.Id); - Assert.Equal(new[] { "Author1", "Author2"}, package.Authors); - Assert.Equal("Description", package.Description); - Assert.False(package.HasReadme); - Assert.False(package.HasEmbeddedIcon); - Assert.True(package.IsPrerelease); - Assert.Null(package.ReleaseNotes); - Assert.Equal("Language", package.Language); - Assert.True(package.Listed); - Assert.Equal("1.0.0", package.MinClientVersion); - Assert.Equal(published.UtcDateTime, package.Published); - Assert.True(package.RequireLicenseAcceptance); - Assert.Equal(SemVerLevel.SemVer2, package.SemVerLevel); - Assert.Equal("Summary", package.Summary); - Assert.Equal("Title", package.Title); - Assert.Equal("https://icon.test/", package.IconUrlString); - Assert.Equal("https://license.test/", package.LicenseUrlString); - Assert.Equal("", package.ProjectUrlString); - Assert.Equal("", package.RepositoryUrlString); - Assert.Null(package.RepositoryType); - Assert.Equal(new[] { "Tag1", "Tag2" }, package.Tags); - Assert.Equal("1.2.3-prerelease", package.NormalizedVersionString); - Assert.Equal("1.2.3-prerelease+semver2", package.OriginalVersionString); - } + } + }); + + var result = await _target.ListPackagesAsync(_id, _cancellation); + + var package = Assert.Single(result); + + Assert.Equal("Foo", package.Id); + Assert.Equal(new[] { "Author1", "Author2"}, package.Authors); + Assert.Equal("Description", package.Description); + Assert.False(package.HasReadme); + Assert.False(package.HasEmbeddedIcon); + Assert.True(package.IsPrerelease); + Assert.Null(package.ReleaseNotes); + Assert.Equal("Language", package.Language); + Assert.True(package.Listed); + Assert.Equal("1.0.0", package.MinClientVersion); + Assert.Equal(published.UtcDateTime, package.Published); + Assert.True(package.RequireLicenseAcceptance); + Assert.Equal(SemVerLevel.SemVer2, package.SemVerLevel); + Assert.Equal("Summary", package.Summary); + Assert.Equal("Title", package.Title); + Assert.Equal("https://icon.test/", package.IconUrlString); + Assert.Equal("https://license.test/", package.LicenseUrlString); + Assert.Equal("", package.ProjectUrlString); + Assert.Equal("", package.RepositoryUrlString); + Assert.Null(package.RepositoryType); + Assert.Equal(new[] { "Tag1", "Tag2" }, package.Tags); + Assert.Equal("1.2.3-prerelease", package.NormalizedVersionString); + Assert.Equal("1.2.3-prerelease+semver2", package.OriginalVersionString); } + } - public class DownloadPackageOrNullAsync : FactsBase + public class DownloadPackageOrNullAsync : FactsBase + { + [Fact] + public async Task ReturnsNull() { - [Fact] - public async Task ReturnsNull() - { - _client - .Setup(c => c.DownloadPackageAsync(_id, _version, _cancellation)) - .ThrowsAsync(new PackageNotFoundException(_id, _version)); - - var result = await _target.DownloadPackageOrNullAsync(_id, _version, _cancellation); - - Assert.Null(result); - } - - [Fact] - public async Task IgnoresExceptions() - { - _client - .Setup(c => c.DownloadPackageAsync(_id, _version, _cancellation)) - .ThrowsAsync(new InvalidDataException("Hello world")); - - var result = await _target.DownloadPackageOrNullAsync(_id, _version, _cancellation); - - Assert.Null(result); - } - - [Fact] - public async Task ReturnsPackage() - { - _client - .Setup(c => c.DownloadPackageAsync(_id, _version, _cancellation)) - .ReturnsAsync(new MemoryStream()); - - var result = await _target.DownloadPackageOrNullAsync(_id, _version, _cancellation); - - Assert.NotNull(result); - Assert.True(result.CanSeek); - } + _client + .Setup(c => c.DownloadPackageAsync(_id, _version, _cancellation)) + .ThrowsAsync(new PackageNotFoundException(_id, _version)); + + var result = await _target.DownloadPackageOrNullAsync(_id, _version, _cancellation); + + Assert.Null(result); } - public class FactsBase + [Fact] + public async Task IgnoresExceptions() + { + _client + .Setup(c => c.DownloadPackageAsync(_id, _version, _cancellation)) + .ThrowsAsync(new InvalidDataException("Hello world")); + + var result = await _target.DownloadPackageOrNullAsync(_id, _version, _cancellation); + + Assert.Null(result); + } + + [Fact] + public async Task ReturnsPackage() + { + _client + .Setup(c => c.DownloadPackageAsync(_id, _version, _cancellation)) + .ReturnsAsync(new MemoryStream()); + + var result = await _target.DownloadPackageOrNullAsync(_id, _version, _cancellation); + + Assert.NotNull(result); + Assert.True(result.CanSeek); + } + } + + public class FactsBase + { + protected readonly Mock _client; + protected readonly V3UpstreamClient _target; + + protected readonly string _id = "Foo"; + protected readonly NuGetVersion _version = new NuGetVersion("1.2.3-prerelease+semver2"); + protected readonly CancellationToken _cancellation = CancellationToken.None; + + protected FactsBase() { - protected readonly Mock _client; - protected readonly V3UpstreamClient _target; - - protected readonly string _id = "Foo"; - protected readonly NuGetVersion _version = new NuGetVersion("1.2.3-prerelease+semver2"); - protected readonly CancellationToken _cancellation = CancellationToken.None; - - protected FactsBase() - { - _client = new Mock(); - _target = new V3UpstreamClient( - _client.Object, - Mock.Of>()); - } + _client = new Mock(); + _target = new V3UpstreamClient( + _client.Object, + Mock.Of>()); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Validation/RequiredIfAttributeTests.cs b/tests/BaGet.Core.Tests/Validation/RequiredIfAttributeTests.cs index 0dc8988c0..32b8b0bd3 100644 --- a/tests/BaGet.Core.Tests/Validation/RequiredIfAttributeTests.cs +++ b/tests/BaGet.Core.Tests/Validation/RequiredIfAttributeTests.cs @@ -1,140 +1,139 @@ using System.ComponentModel.DataAnnotations; using Xunit; -namespace BaGet.Core.Tests.Validation +namespace BaGet.Core.Tests.Validation; + +public class RequiredIfAttributeTests { - public class RequiredIfAttributeTests + private class Model { - private class Model - { - public string Mode { get; set; } + public string Mode { get; set; } - public string Value { get; set; } - } + public string Value { get; set; } + } - private static ValidationResult Validate( - RequiredIfAttribute attribute, - string mode, - string value, - string displayName = "Value") - { - var model = new Model { Mode = mode, Value = value }; - var context = new ValidationContext(model) { DisplayName = displayName }; + private static ValidationResult Validate( + RequiredIfAttribute attribute, + string mode, + string value, + string displayName = "Value") + { + var model = new Model { Mode = mode, Value = value }; + var context = new ValidationContext(model) { DisplayName = displayName }; - return attribute.GetValidationResult(value, context); - } + return attribute.GetValidationResult(value, context); + } - [Fact] - public void RequiresTheValueWhenTheOtherPropertyMatches() - { - var result = Validate(new RequiredIfAttribute("Mode", "needed"), "needed", null); + [Fact] + public void RequiresTheValueWhenTheOtherPropertyMatches() + { + var result = Validate(new RequiredIfAttribute("Mode", "needed"), "needed", null); - Assert.NotNull(result); - Assert.NotEqual(ValidationResult.Success, result); - } + Assert.NotNull(result); + Assert.NotEqual(ValidationResult.Success, result); + } - [Fact] - public void AcceptsAValueWhenTheOtherPropertyMatches() - { - var result = Validate(new RequiredIfAttribute("Mode", "needed"), "needed", "provided"); + [Fact] + public void AcceptsAValueWhenTheOtherPropertyMatches() + { + var result = Validate(new RequiredIfAttribute("Mode", "needed"), "needed", "provided"); - Assert.Equal(ValidationResult.Success, result); - } + Assert.Equal(ValidationResult.Success, result); + } - [Fact] - public void IgnoresAMissingValueWhenTheOtherPropertyDoesNotMatch() - { - var result = Validate(new RequiredIfAttribute("Mode", "needed"), "other", null); + [Fact] + public void IgnoresAMissingValueWhenTheOtherPropertyDoesNotMatch() + { + var result = Validate(new RequiredIfAttribute("Mode", "needed"), "other", null); - Assert.Equal(ValidationResult.Success, result); - } + Assert.Equal(ValidationResult.Success, result); + } - [Theory] - [InlineData("")] - [InlineData(" ")] - [InlineData("\t")] - public void TreatsAWhitespaceOnlyStringAsMissing(string value) - { - var result = Validate(new RequiredIfAttribute("Mode", "needed"), "needed", value); + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("\t")] + public void TreatsAWhitespaceOnlyStringAsMissing(string value) + { + var result = Validate(new RequiredIfAttribute("Mode", "needed"), "needed", value); - Assert.NotEqual(ValidationResult.Success, result); - } + Assert.NotEqual(ValidationResult.Success, result); + } - [Fact] - public void InvertedRequiresTheValueWhenTheOtherPropertyDiffers() - { - var attribute = new RequiredIfAttribute("Mode", "ignored") { IsInverted = true }; + [Fact] + public void InvertedRequiresTheValueWhenTheOtherPropertyDiffers() + { + var attribute = new RequiredIfAttribute("Mode", "ignored") { IsInverted = true }; - var result = Validate(attribute, "something else", null); + var result = Validate(attribute, "something else", null); - Assert.NotEqual(ValidationResult.Success, result); - } + Assert.NotEqual(ValidationResult.Success, result); + } - [Fact] - public void InvertedIgnoresAMissingValueWhenTheOtherPropertyMatches() - { - var attribute = new RequiredIfAttribute("Mode", "ignored") { IsInverted = true }; + [Fact] + public void InvertedIgnoresAMissingValueWhenTheOtherPropertyMatches() + { + var attribute = new RequiredIfAttribute("Mode", "ignored") { IsInverted = true }; - var result = Validate(attribute, "ignored", null); + var result = Validate(attribute, "ignored", null); - Assert.Equal(ValidationResult.Success, result); - } + Assert.Equal(ValidationResult.Success, result); + } - [Fact] - public void MatchesANullOtherPropertyValue() - { - var result = Validate(new RequiredIfAttribute("Mode", null), null, null); + [Fact] + public void MatchesANullOtherPropertyValue() + { + var result = Validate(new RequiredIfAttribute("Mode", null), null, null); - Assert.NotEqual(ValidationResult.Success, result); - } + Assert.NotEqual(ValidationResult.Success, result); + } - [Fact] - public void ReportsAnUnknownOtherProperty() - { - var result = Validate(new RequiredIfAttribute("NoSuchProperty", "x"), "x", null); + [Fact] + public void ReportsAnUnknownOtherProperty() + { + var result = Validate(new RequiredIfAttribute("NoSuchProperty", "x"), "x", null); - Assert.NotEqual(ValidationResult.Success, result); - Assert.Contains("NoSuchProperty", result.ErrorMessage); - } + Assert.NotEqual(ValidationResult.Success, result); + Assert.Contains("NoSuchProperty", result.ErrorMessage); + } - [Fact] - public void TheMessageNamesThePropertyAndTheCondition() - { - var result = Validate(new RequiredIfAttribute("Mode", "needed"), "needed", null); + [Fact] + public void TheMessageNamesThePropertyAndTheCondition() + { + var result = Validate(new RequiredIfAttribute("Mode", "needed"), "needed", null); - Assert.Contains("Value", result.ErrorMessage); - Assert.Contains("Mode", result.ErrorMessage); - Assert.Contains("needed", result.ErrorMessage); - Assert.Contains("of ", result.ErrorMessage); - } + Assert.Contains("Value", result.ErrorMessage); + Assert.Contains("Mode", result.ErrorMessage); + Assert.Contains("needed", result.ErrorMessage); + Assert.Contains("of ", result.ErrorMessage); + } - [Fact] - public void TheInvertedMessageSaysOtherThan() - { - var attribute = new RequiredIfAttribute("Mode", "ignored") { IsInverted = true }; + [Fact] + public void TheInvertedMessageSaysOtherThan() + { + var attribute = new RequiredIfAttribute("Mode", "ignored") { IsInverted = true }; - var result = Validate(attribute, "something else", null); + var result = Validate(attribute, "something else", null); - Assert.Contains("other than ", result.ErrorMessage); - } + Assert.Contains("other than ", result.ErrorMessage); + } - [Fact] - public void TheMessageUsesTheOtherPropertyDisplayNameWhenSet() + [Fact] + public void TheMessageUsesTheOtherPropertyDisplayNameWhenSet() + { + var attribute = new RequiredIfAttribute("Mode", "needed") { - var attribute = new RequiredIfAttribute("Mode", "needed") - { - OtherPropertyDisplayName = "Operating mode", - }; + OtherPropertyDisplayName = "Operating mode", + }; - var result = Validate(attribute, "needed", null); + var result = Validate(attribute, "needed", null); - Assert.Contains("Operating mode", result.ErrorMessage); - } + Assert.Contains("Operating mode", result.ErrorMessage); + } - [Fact] - public void RequiresAValidationContext() - { - Assert.True(new RequiredIfAttribute("Mode", "needed").RequiresValidationContext); - } + [Fact] + public void RequiresAValidationContext() + { + Assert.True(new RequiredIfAttribute("Mode", "needed").RequiresValidationContext); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Core.Tests/Validation/ValidateBaGetOptionsTests.cs b/tests/BaGet.Core.Tests/Validation/ValidateBaGetOptionsTests.cs index e28e4973d..a88a4c86e 100644 --- a/tests/BaGet.Core.Tests/Validation/ValidateBaGetOptionsTests.cs +++ b/tests/BaGet.Core.Tests/Validation/ValidateBaGetOptionsTests.cs @@ -2,89 +2,88 @@ using System.Linq; using Xunit; -namespace BaGet.Core.Tests.Validation +namespace BaGet.Core.Tests.Validation; + +public class ValidateBaGetOptionsTests { - public class ValidateBaGetOptionsTests + private class Options { - private class Options - { - [Required] - public string Name { get; set; } + [Required] + public string Name { get; set; } - [Range(1, 10)] - public int Count { get; set; } = 1; - } + [Range(1, 10)] + public int Count { get; set; } = 1; + } - [Fact] - public void AcceptsValidOptions() - { - var target = new ValidateBaGetOptions("Section"); + [Fact] + public void AcceptsValidOptions() + { + var target = new ValidateBaGetOptions("Section"); - var result = target.Validate(null, new Options { Name = "ok", Count = 5 }); + var result = target.Validate(null, new Options { Name = "ok", Count = 5 }); - Assert.True(result.Succeeded); - } + Assert.True(result.Succeeded); + } - [Fact] - public void RejectsAMissingRequiredValue() - { - var target = new ValidateBaGetOptions("Section"); + [Fact] + public void RejectsAMissingRequiredValue() + { + var target = new ValidateBaGetOptions("Section"); - var result = target.Validate(null, new Options { Name = null }); + var result = target.Validate(null, new Options { Name = null }); - Assert.True(result.Failed); - } + Assert.True(result.Failed); + } - [Fact] - public void RejectsAnOutOfRangeValue() - { - var target = new ValidateBaGetOptions("Section"); + [Fact] + public void RejectsAnOutOfRangeValue() + { + var target = new ValidateBaGetOptions("Section"); - var result = target.Validate(null, new Options { Name = "ok", Count = 99 }); + var result = target.Validate(null, new Options { Name = "ok", Count = 99 }); - Assert.True(result.Failed); - } + Assert.True(result.Failed); + } - [Fact] - public void ValidatesEveryPropertyNotJustTheFirst() - { - var target = new ValidateBaGetOptions("Section"); + [Fact] + public void ValidatesEveryPropertyNotJustTheFirst() + { + var target = new ValidateBaGetOptions("Section"); - var result = target.Validate(null, new Options { Name = null, Count = 99 }); + var result = target.Validate(null, new Options { Name = null, Count = 99 }); - Assert.True(result.Failed); - Assert.Equal(2, result.Failures.Count()); - } + Assert.True(result.Failed); + Assert.Equal(2, result.Failures.Count()); + } - [Fact] - public void TheMessageNamesTheConfigurationSection() - { - var target = new ValidateBaGetOptions("Storage"); + [Fact] + public void TheMessageNamesTheConfigurationSection() + { + var target = new ValidateBaGetOptions("Storage"); - var result = target.Validate(null, new Options { Name = null }); + var result = target.Validate(null, new Options { Name = null }); - Assert.Contains("Invalid 'Storage' configs", result.FailureMessage); - } + Assert.Contains("Invalid 'Storage' configs", result.FailureMessage); + } - [Fact] - public void TheMessageOmitsTheSectionForRootOptions() - { - var target = new ValidateBaGetOptions(null); + [Fact] + public void TheMessageOmitsTheSectionForRootOptions() + { + var target = new ValidateBaGetOptions(null); - var result = target.Validate(null, new Options { Name = null }); + var result = target.Validate(null, new Options { Name = null }); - Assert.Contains("Invalid configs", result.FailureMessage); - Assert.DoesNotContain("''", result.FailureMessage); - } + Assert.Contains("Invalid configs", result.FailureMessage); + Assert.DoesNotContain("''", result.FailureMessage); + } - [Fact] - public void TheMessageIncludesTheValidationError() - { - var target = new ValidateBaGetOptions("Section"); + [Fact] + public void TheMessageIncludesTheValidationError() + { + var target = new ValidateBaGetOptions("Section"); - var result = target.Validate(null, new Options { Name = null }); + var result = target.Validate(null, new Options { Name = null }); - Assert.Contains("Name", result.FailureMessage); - } + Assert.Contains("Name", result.FailureMessage); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Converters/PackageDependencyRangeJsonConverterTests.cs b/tests/BaGet.Protocol.Tests/Converters/PackageDependencyRangeJsonConverterTests.cs index 5229bd798..3691e7890 100644 --- a/tests/BaGet.Protocol.Tests/Converters/PackageDependencyRangeJsonConverterTests.cs +++ b/tests/BaGet.Protocol.Tests/Converters/PackageDependencyRangeJsonConverterTests.cs @@ -2,86 +2,85 @@ using BaGet.Protocol.Internal; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class PackageDependencyRangeJsonConverterTests { - public class PackageDependencyRangeJsonConverterTests + [Fact] + public void DeserializesNull() { - [Fact] - public void DeserializesNull() - { - var json = @"null"; + var json = @"null"; - var options = new JsonSerializerOptions(); - options.Converters.Add(new PackageDependencyRangeJsonConverter()); + var options = new JsonSerializerOptions(); + options.Converters.Add(new PackageDependencyRangeJsonConverter()); - var result = JsonSerializer.Deserialize(json, options); + var result = JsonSerializer.Deserialize(json, options); - Assert.Null(result); - } + Assert.Null(result); + } - [Fact] - public void DeserializesString() - { - var json = @"""Hello"""; + [Fact] + public void DeserializesString() + { + var json = @"""Hello"""; - var options = new JsonSerializerOptions(); - options.Converters.Add(new PackageDependencyRangeJsonConverter()); + var options = new JsonSerializerOptions(); + options.Converters.Add(new PackageDependencyRangeJsonConverter()); - var result = JsonSerializer.Deserialize(json, options); + var result = JsonSerializer.Deserialize(json, options); - Assert.Equal("Hello", result); - } + Assert.Equal("Hello", result); + } - [Fact] - public void DeserializesStringArray() - { - var json = @"[""first"", ""second"", ""third""]"; + [Fact] + public void DeserializesStringArray() + { + var json = @"[""first"", ""second"", ""third""]"; - var options = new JsonSerializerOptions(); - options.Converters.Add(new PackageDependencyRangeJsonConverter()); + var options = new JsonSerializerOptions(); + options.Converters.Add(new PackageDependencyRangeJsonConverter()); - var result = JsonSerializer.Deserialize(json, options); + var result = JsonSerializer.Deserialize(json, options); - Assert.Equal("first", result); - } + Assert.Equal("first", result); + } - [Theory] - [InlineData(@"false")] - [InlineData(@"0")] - [InlineData(@"{")] - [InlineData(@"[")] - [InlineData(@"[""hello""")] - [InlineData(@"[""hello""}")] - [InlineData(@"[""hello"", 1")] - public void ThrowsOnInvalidJson(string json) - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new PackageDependencyRangeJsonConverter()); + [Theory] + [InlineData(@"false")] + [InlineData(@"0")] + [InlineData(@"{")] + [InlineData(@"[")] + [InlineData(@"[""hello""")] + [InlineData(@"[""hello""}")] + [InlineData(@"[""hello"", 1")] + public void ThrowsOnInvalidJson(string json) + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new PackageDependencyRangeJsonConverter()); - Assert.Throws( - () => JsonSerializer.Deserialize(json, options)); - } + Assert.Throws( + () => JsonSerializer.Deserialize(json, options)); + } - [Fact] - public void SerializesNull() - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + [Fact] + public void SerializesNull() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - var json = JsonSerializer.Serialize(null, options); + var json = JsonSerializer.Serialize(null, options); - Assert.Equal("null", json); - } + Assert.Equal("null", json); + } - [Fact] - public void SerializesString() - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + [Fact] + public void SerializesString() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - var json = JsonSerializer.Serialize("foo", options); + var json = JsonSerializer.Serialize("foo", options); - Assert.Equal(@"""foo""", json); - } + Assert.Equal(@"""foo""", json); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Converters/StringOrStringArrayJsonConverterTests.cs b/tests/BaGet.Protocol.Tests/Converters/StringOrStringArrayJsonConverterTests.cs index 9f4b77df2..c05d5749e 100644 --- a/tests/BaGet.Protocol.Tests/Converters/StringOrStringArrayJsonConverterTests.cs +++ b/tests/BaGet.Protocol.Tests/Converters/StringOrStringArrayJsonConverterTests.cs @@ -3,121 +3,120 @@ using BaGet.Protocol.Internal; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class StringOrStringArrayJsonConverterTests { - public class StringOrStringArrayJsonConverterTests + [Fact] + public void DeserializesEmptyString() { - [Fact] - public void DeserializesEmptyString() - { - var json = @""""""; + var json = @""""""; - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - var result = JsonSerializer.Deserialize>(json, options); + var result = JsonSerializer.Deserialize>(json, options); - var first = Assert.Single(result); - Assert.NotNull(first); - Assert.True(string.IsNullOrEmpty(first)); - } + var first = Assert.Single(result); + Assert.NotNull(first); + Assert.True(string.IsNullOrEmpty(first)); + } - [Fact] - public void DeserializesString() - { - var json = @"""Foo bar"""; + [Fact] + public void DeserializesString() + { + var json = @"""Foo bar"""; - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - var result = JsonSerializer.Deserialize>(json, options); + var result = JsonSerializer.Deserialize>(json, options); - var first = Assert.Single(result); - Assert.Equal("Foo bar", first); - } + var first = Assert.Single(result); + Assert.Equal("Foo bar", first); + } - [Fact] - public void DeserializesEmptyArray() - { - var json = "[]"; + [Fact] + public void DeserializesEmptyArray() + { + var json = "[]"; - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - var result = JsonSerializer.Deserialize>(json, options); + var result = JsonSerializer.Deserialize>(json, options); - Assert.Empty(result); - } + Assert.Empty(result); + } - [Fact] - public void DeserializesArray() - { - var json = @"[""Foo"", ""bar""]"; + [Fact] + public void DeserializesArray() + { + var json = @"[""Foo"", ""bar""]"; - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - var result = JsonSerializer.Deserialize>(json, options); + var result = JsonSerializer.Deserialize>(json, options); - Assert.Equal(2, result.Count); - Assert.Equal("Foo", result[0]); - Assert.Equal("bar", result[1]); - } + Assert.Equal(2, result.Count); + Assert.Equal("Foo", result[0]); + Assert.Equal("bar", result[1]); + } - [Theory] - [InlineData(@"false")] - [InlineData(@"0")] - [InlineData(@"{")] - [InlineData(@"[")] - [InlineData(@"[""hello""")] - [InlineData(@"[""hello""}")] - [InlineData(@"[""hello"", 1")] - public void ThrowsOnInvalidJson(string json) - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + [Theory] + [InlineData(@"false")] + [InlineData(@"0")] + [InlineData(@"{")] + [InlineData(@"[")] + [InlineData(@"[""hello""")] + [InlineData(@"[""hello""}")] + [InlineData(@"[""hello"", 1")] + public void ThrowsOnInvalidJson(string json) + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - Assert.Throws( - () => JsonSerializer.Deserialize>(json, options)); - } + Assert.Throws( + () => JsonSerializer.Deserialize>(json, options)); + } - [Fact] - public void SerializesNull() - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + [Fact] + public void SerializesNull() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - IReadOnlyList list = null; + IReadOnlyList list = null; - var json = JsonSerializer.Serialize(list, options); + var json = JsonSerializer.Serialize(list, options); - Assert.Equal("null", json); - } + Assert.Equal("null", json); + } - [Fact] - public void SerializesEmptyString() - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + [Fact] + public void SerializesEmptyString() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - IReadOnlyList list = new List { "" }; + IReadOnlyList list = new List { "" }; - var json = JsonSerializer.Serialize(list, options); + var json = JsonSerializer.Serialize(list, options); - Assert.Equal(@"[""""]", json); - } + Assert.Equal(@"[""""]", json); + } - [Fact] - public void SerializesList() - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new StringOrStringArrayJsonConverter()); + [Fact] + public void SerializesList() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new StringOrStringArrayJsonConverter()); - IReadOnlyList list = new List { "Hello", "World", null }; + IReadOnlyList list = new List { "Hello", "World", null }; - var json = JsonSerializer.Serialize(list, options); + var json = JsonSerializer.Serialize(list, options); - Assert.Equal(@"[""Hello"",""World"",null]", json); - } + Assert.Equal(@"[""Hello"",""World"",null]", json); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/NuGetClientFactoryTests.cs b/tests/BaGet.Protocol.Tests/NuGetClientFactoryTests.cs index cb171e564..5f4a2ce40 100644 --- a/tests/BaGet.Protocol.Tests/NuGetClientFactoryTests.cs +++ b/tests/BaGet.Protocol.Tests/NuGetClientFactoryTests.cs @@ -6,222 +6,221 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class NuGetClientFactoryTests : IClassFixture { - public class NuGetClientFactoryTests : IClassFixture + private readonly NuGetClientFactory _target; + + public NuGetClientFactoryTests(ProtocolFixture fixture) { - private readonly NuGetClientFactory _target; + _target = fixture.NuGetClientFactory; + } - public NuGetClientFactoryTests(ProtocolFixture fixture) - { - _target = fixture.NuGetClientFactory; - } + [Fact] + public async Task DownloadsPackage() + { + var client = _target.CreatePackageContentClient(); - [Fact] - public async Task DownloadsPackage() + using (var stream = await client.DownloadPackageOrNullAsync( + "Test.Package", + NuGetVersion.Parse("1.0.0"))) { - var client = _target.CreatePackageContentClient(); + Assert.NotNull(stream); - using (var stream = await client.DownloadPackageOrNullAsync( - "Test.Package", - NuGetVersion.Parse("1.0.0"))) + using (var reader = new StreamReader(stream)) { - Assert.NotNull(stream); - - using (var reader = new StreamReader(stream)) - { - Assert.Equal(TestData.PackageContentNupkg, await reader.ReadToEndAsync()); - } + Assert.Equal(TestData.PackageContentNupkg, await reader.ReadToEndAsync()); } } + } - [Fact] - public async Task DownloadsPackageManifest() + [Fact] + public async Task DownloadsPackageManifest() + { + var client = _target.CreatePackageContentClient(); + + using (var stream = await client.DownloadPackageManifestOrNullAsync( + "Test.Package", + NuGetVersion.Parse("1.0.0"))) { - var client = _target.CreatePackageContentClient(); + Assert.NotNull(stream); - using (var stream = await client.DownloadPackageManifestOrNullAsync( - "Test.Package", - NuGetVersion.Parse("1.0.0"))) + using (var reader = new StreamReader(stream)) { - Assert.NotNull(stream); - - using (var reader = new StreamReader(stream)) - { - Assert.Equal(TestData.PackageContentNuspec, await reader.ReadToEndAsync()); - } + Assert.Equal(TestData.PackageContentNuspec, await reader.ReadToEndAsync()); } } + } - [Fact] - public async Task ListsPackageVersions() - { - var client = _target.CreatePackageContentClient(); + [Fact] + public async Task ListsPackageVersions() + { + var client = _target.CreatePackageContentClient(); - var response = await client.GetPackageVersionsOrNullAsync("Test.Package"); + var response = await client.GetPackageVersionsOrNullAsync("Test.Package"); - Assert.NotNull(response); - Assert.Equal(new[] { "1.0.0", "2.0.0" }, response.Versions.ToArray()); - } + Assert.NotNull(response); + Assert.Equal(new[] { "1.0.0", "2.0.0" }, response.Versions.ToArray()); + } - [Fact] - public async Task ListsPackageVersionsOfPagedPackage() - { - var client = _target.CreatePackageContentClient(); + [Fact] + public async Task ListsPackageVersionsOfPagedPackage() + { + var client = _target.CreatePackageContentClient(); - var response = await client.GetPackageVersionsOrNullAsync("Paged.Package"); + var response = await client.GetPackageVersionsOrNullAsync("Paged.Package"); - Assert.NotNull(response); - Assert.Equal(new[] { "1.0.0", "2.0.0", "3.0.0" }, response.Versions.ToArray()); - } + Assert.NotNull(response); + Assert.Equal(new[] { "1.0.0", "2.0.0", "3.0.0" }, response.Versions.ToArray()); + } - [Fact] - public async Task ListsAllPackageVersions() - { - var client = _target.CreateAutocompleteClient(); + [Fact] + public async Task ListsAllPackageVersions() + { + var client = _target.CreateAutocompleteClient(); - var response = await client.ListPackageVersionsAsync("Test.Package"); + var response = await client.ListPackageVersionsAsync("Test.Package"); - Assert.NotNull(response); - Assert.Equal(3, response.TotalHits); - Assert.Equal(new[] { "1.0.0", "2.0.0", "3.0.0" }, response.Data.ToArray()); - } + Assert.NotNull(response); + Assert.Equal(3, response.TotalHits); + Assert.Equal(new[] { "1.0.0", "2.0.0", "3.0.0" }, response.Data.ToArray()); + } - [Fact] - public async Task GetsPackageMetadataInlined() - { - var client = _target.CreatePackageMetadataClient(); - - var response = await client.GetRegistrationIndexOrNullAsync("Test.Package"); - - Assert.NotNull(response); - Assert.Equal(2, response.Pages.Count); - Assert.All(response.Pages, page => Assert.NotNull(page.ItemsOrNull)); - Assert.Equal( - new[] { "1.0.0", "2.0.0+build", "3.0.0" }, - response.Pages - .SelectMany(p => p.ItemsOrNull) - .Select(i => i.PackageMetadata.Version) - .ToArray()); - } + [Fact] + public async Task GetsPackageMetadataInlined() + { + var client = _target.CreatePackageMetadataClient(); + + var response = await client.GetRegistrationIndexOrNullAsync("Test.Package"); + + Assert.NotNull(response); + Assert.Equal(2, response.Pages.Count); + Assert.All(response.Pages, page => Assert.NotNull(page.ItemsOrNull)); + Assert.Equal( + new[] { "1.0.0", "2.0.0+build", "3.0.0" }, + response.Pages + .SelectMany(p => p.ItemsOrNull) + .Select(i => i.PackageMetadata.Version) + .ToArray()); + } - [Fact] - public async Task GetsPackageMetadataPaged() - { - var client = _target.CreatePackageMetadataClient(); + [Fact] + public async Task GetsPackageMetadataPaged() + { + var client = _target.CreatePackageMetadataClient(); - var response = await client.GetRegistrationIndexOrNullAsync("Paged.Package"); + var response = await client.GetRegistrationIndexOrNullAsync("Paged.Package"); - Assert.NotNull(response); - Assert.Equal(2, response.Pages.Count); - Assert.All(response.Pages, page => Assert.Null(page.ItemsOrNull)); - Assert.Equal( - new[] { TestData.RegistrationPageFirstUrl, TestData.RegistrationPageUrl }, - response.Pages.Select(p => p.RegistrationPageUrl).ToArray()); - } + Assert.NotNull(response); + Assert.Equal(2, response.Pages.Count); + Assert.All(response.Pages, page => Assert.Null(page.ItemsOrNull)); + Assert.Equal( + new[] { TestData.RegistrationPageFirstUrl, TestData.RegistrationPageUrl }, + response.Pages.Select(p => p.RegistrationPageUrl).ToArray()); + } - [Fact] - public async Task GetsSinglePackageMetadataInlined() - { - var client = _target.CreatePackageMetadataClient(); + [Fact] + public async Task GetsSinglePackageMetadataInlined() + { + var client = _target.CreatePackageMetadataClient(); - var response = await client.GetRegistrationLeafAsync(TestData.RegistrationLeafListedUrl); + var response = await client.GetRegistrationLeafAsync(TestData.RegistrationLeafListedUrl); - Assert.NotNull(response); - Assert.True(response.Listed); - Assert.Equal( - "https://test.example/v3/content/test.package/1.0.0/test.package.1.0.0.nupkg", - response.PackageContentUrl); - } + Assert.NotNull(response); + Assert.True(response.Listed); + Assert.Equal( + "https://test.example/v3/content/test.package/1.0.0/test.package.1.0.0.nupkg", + response.PackageContentUrl); + } - [Fact] - public async Task GetsSinglePackageMetadataPaged() - { - var client = _target.CreatePackageMetadataClient(); + [Fact] + public async Task GetsSinglePackageMetadataPaged() + { + var client = _target.CreatePackageMetadataClient(); - var response = await client.GetRegistrationPageAsync(TestData.RegistrationPageUrl); + var response = await client.GetRegistrationPageAsync(TestData.RegistrationPageUrl); - Assert.NotNull(response); - Assert.NotNull(response.ItemsOrNull); + Assert.NotNull(response); + Assert.NotNull(response.ItemsOrNull); - var metadata = response.ItemsOrNull[1].PackageMetadata; + var metadata = response.ItemsOrNull[1].PackageMetadata; - Assert.Equal("Paged.Package", metadata.PackageId); - Assert.Equal("3.0.0", metadata.Version); - } + Assert.Equal("Paged.Package", metadata.PackageId); + Assert.Equal("3.0.0", metadata.Version); + } - [Fact] - public async Task Searches() - { - var client = _target.CreateSearchClient(); + [Fact] + public async Task Searches() + { + var client = _target.CreateSearchClient(); - var response = await client.SearchAsync(); + var response = await client.SearchAsync(); - Assert.NotNull(response); - Assert.Equal(1, response.TotalHits); - Assert.Equal("Test.Package", Assert.Single(response.Data).PackageId); - } + Assert.NotNull(response); + Assert.Equal(1, response.TotalHits); + Assert.Equal("Test.Package", Assert.Single(response.Data).PackageId); + } - [Fact] - public async Task Autocompletes() - { - var client = _target.CreateAutocompleteClient(); + [Fact] + public async Task Autocompletes() + { + var client = _target.CreateAutocompleteClient(); - var response = await client.AutocompleteAsync(); + var response = await client.AutocompleteAsync(); - Assert.NotNull(response); - Assert.Equal(1, response.TotalHits); - Assert.Equal("Test.Package", Assert.Single(response.Data)); - } + Assert.NotNull(response); + Assert.Equal(1, response.TotalHits); + Assert.Equal("Test.Package", Assert.Single(response.Data)); + } - [Fact] - public async Task ResolvesResourcesFromTheServiceIndex() - { - var client = _target.CreateServiceIndexClient(); + [Fact] + public async Task ResolvesResourcesFromTheServiceIndex() + { + var client = _target.CreateServiceIndexClient(); - var serviceIndex = await client.GetAsync(); + var serviceIndex = await client.GetAsync(); - Assert.Equal("https://test.example/v3/content", serviceIndex.GetPackageContentResourceUrl()); - Assert.Equal("https://test.example/v3/metadata", serviceIndex.GetPackageMetadataResourceUrl()); - Assert.Equal(TestData.SearchUrl, serviceIndex.GetSearchQueryResourceUrl()); - Assert.Equal(TestData.AutocompleteUrl, serviceIndex.GetSearchAutocompleteResourceUrl()); - Assert.Equal(TestData.CatalogIndexUrl, serviceIndex.GetCatalogResourceUrl()); - } + Assert.Equal("https://test.example/v3/content", serviceIndex.GetPackageContentResourceUrl()); + Assert.Equal("https://test.example/v3/metadata", serviceIndex.GetPackageMetadataResourceUrl()); + Assert.Equal(TestData.SearchUrl, serviceIndex.GetSearchQueryResourceUrl()); + Assert.Equal(TestData.AutocompleteUrl, serviceIndex.GetSearchAutocompleteResourceUrl()); + Assert.Equal(TestData.CatalogIndexUrl, serviceIndex.GetCatalogResourceUrl()); + } - [Fact] - public async Task FetchesTheServiceIndexOnce() - { - var handler = new CountingHttpMessageHandler(new TestDataHttpMessageHandler()); - var target = new NuGetClientFactory(new HttpClient(handler), TestData.ServiceIndexUrl); + [Fact] + public async Task FetchesTheServiceIndexOnce() + { + var handler = new CountingHttpMessageHandler(new TestDataHttpMessageHandler()); + var target = new NuGetClientFactory(new HttpClient(handler), TestData.ServiceIndexUrl); - await target.CreatePackageContentClient().GetPackageVersionsOrNullAsync("Test.Package"); - await target.CreateSearchClient().SearchAsync(); - await target.CreateAutocompleteClient().AutocompleteAsync(); + await target.CreatePackageContentClient().GetPackageVersionsOrNullAsync("Test.Package"); + await target.CreateSearchClient().SearchAsync(); + await target.CreateAutocompleteClient().AutocompleteAsync(); - Assert.Equal(1, handler.RequestCount(TestData.ServiceIndexUrl)); - Assert.Equal(1, handler.RequestCount(TestData.PackageContentVersionListUrl)); - Assert.Equal(1, handler.RequestCount(TestData.DefaultSearchUrl)); - Assert.Equal(1, handler.RequestCount(TestData.DefaultAutocompleteUrl)); - } + Assert.Equal(1, handler.RequestCount(TestData.ServiceIndexUrl)); + Assert.Equal(1, handler.RequestCount(TestData.PackageContentVersionListUrl)); + Assert.Equal(1, handler.RequestCount(TestData.DefaultSearchUrl)); + Assert.Equal(1, handler.RequestCount(TestData.DefaultAutocompleteUrl)); + } - [Fact] - public async Task ReturnsNullWhenPackageDoesNotExist() - { - var contentClient = _target.CreatePackageContentClient(); - var metadataClient = _target.CreatePackageMetadataClient(); - var packageId = Guid.NewGuid().ToString(); + [Fact] + public async Task ReturnsNullWhenPackageDoesNotExist() + { + var contentClient = _target.CreatePackageContentClient(); + var metadataClient = _target.CreatePackageMetadataClient(); + var packageId = Guid.NewGuid().ToString(); - Assert.Null(await contentClient.GetPackageVersionsOrNullAsync(packageId)); - Assert.Null(await metadataClient.GetRegistrationIndexOrNullAsync(packageId)); - } + Assert.Null(await contentClient.GetPackageVersionsOrNullAsync(packageId)); + Assert.Null(await metadataClient.GetRegistrationIndexOrNullAsync(packageId)); + } - [Fact] - public void ThrowsWhenConstructedWithoutHttpClient() - { - Assert.Throws( - () => new NuGetClientFactory(null, TestData.ServiceIndexUrl)); - Assert.Throws( - () => new NuGetClientFactory(new HttpClient(), null)); - } + [Fact] + public void ThrowsWhenConstructedWithoutHttpClient() + { + Assert.Throws( + () => new NuGetClientFactory(null, TestData.ServiceIndexUrl)); + Assert.Throws( + () => new NuGetClientFactory(new HttpClient(), null)); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/NuGetClientTests.cs b/tests/BaGet.Protocol.Tests/NuGetClientTests.cs index 4ba3cb79e..1c5df3abb 100644 --- a/tests/BaGet.Protocol.Tests/NuGetClientTests.cs +++ b/tests/BaGet.Protocol.Tests/NuGetClientTests.cs @@ -6,213 +6,212 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class NuGetClientTests : IClassFixture { - public class NuGetClientTests : IClassFixture - { - private readonly NuGetClient _target; + private readonly NuGetClient _target; - public NuGetClientTests(ProtocolFixture fixture) - { - _target = fixture.NuGetClient; - } + public NuGetClientTests(ProtocolFixture fixture) + { + _target = fixture.NuGetClient; + } - [Fact] - public async Task DownloadsPackage() + [Fact] + public async Task DownloadsPackage() + { + using (var stream = await _target.DownloadPackageAsync("Test.Package", NuGetVersion.Parse("1.0.0"))) + using (var reader = new StreamReader(stream)) { - using (var stream = await _target.DownloadPackageAsync("Test.Package", NuGetVersion.Parse("1.0.0"))) - using (var reader = new StreamReader(stream)) - { - Assert.Equal(TestData.PackageContentNupkg, await reader.ReadToEndAsync()); - } + Assert.Equal(TestData.PackageContentNupkg, await reader.ReadToEndAsync()); } + } - [Fact] - public async Task ThrowsIfPackageToDownloadDoesNotExist() - { - var exception = await Assert.ThrowsAsync( - () => _target.DownloadPackageAsync("Test.Package", NuGetVersion.Parse("9.9.9"))); + [Fact] + public async Task ThrowsIfPackageToDownloadDoesNotExist() + { + var exception = await Assert.ThrowsAsync( + () => _target.DownloadPackageAsync("Test.Package", NuGetVersion.Parse("9.9.9"))); - Assert.Equal("Test.Package", exception.PackageId); - Assert.Equal(NuGetVersion.Parse("9.9.9"), exception.PackageVersion); - } + Assert.Equal("Test.Package", exception.PackageId); + Assert.Equal(NuGetVersion.Parse("9.9.9"), exception.PackageVersion); + } - [Fact] - public async Task DownloadsPackageManifest() + [Fact] + public async Task DownloadsPackageManifest() + { + using (var stream = await _target.DownloadPackageManifestAsync("Test.Package", NuGetVersion.Parse("1.0.0"))) + using (var reader = new StreamReader(stream)) { - using (var stream = await _target.DownloadPackageManifestAsync("Test.Package", NuGetVersion.Parse("1.0.0"))) - using (var reader = new StreamReader(stream)) - { - Assert.Equal(TestData.PackageContentNuspec, await reader.ReadToEndAsync()); - } + Assert.Equal(TestData.PackageContentNuspec, await reader.ReadToEndAsync()); } + } - [Fact] - public async Task ThrowsIfPackageManifestToDownloadDoesNotExist() - { - var exception = await Assert.ThrowsAsync( - () => _target.DownloadPackageManifestAsync("Test.Package", NuGetVersion.Parse("9.9.9"))); + [Fact] + public async Task ThrowsIfPackageManifestToDownloadDoesNotExist() + { + var exception = await Assert.ThrowsAsync( + () => _target.DownloadPackageManifestAsync("Test.Package", NuGetVersion.Parse("9.9.9"))); - Assert.Equal("Test.Package", exception.PackageId); - Assert.Equal(NuGetVersion.Parse("9.9.9"), exception.PackageVersion); - } + Assert.Equal("Test.Package", exception.PackageId); + Assert.Equal(NuGetVersion.Parse("9.9.9"), exception.PackageVersion); + } - [Fact] - public async Task ListsPackageVersions() - { - // The listed versions come from the package's registration index, which, - // for this package, has its items inlined. - var versions = await _target.ListPackageVersionsAsync("Test.Package"); + [Fact] + public async Task ListsPackageVersions() + { + // The listed versions come from the package's registration index, which, + // for this package, has its items inlined. + var versions = await _target.ListPackageVersionsAsync("Test.Package"); - Assert.Equal( - new[] { "1.0.0", "2.0.0+build", "3.0.0" }, - versions.Select(v => v.ToFullString()).ToArray()); - } + Assert.Equal( + new[] { "1.0.0", "2.0.0+build", "3.0.0" }, + versions.Select(v => v.ToFullString()).ToArray()); + } - [Fact] - public async Task ListsPackageVersionsSkippingUnlistedVersions() - { - // "Paged.Package" has three versions, 2.0.0+build is unlisted. - var versions = await _target.ListPackageVersionsAsync("Paged.Package"); + [Fact] + public async Task ListsPackageVersionsSkippingUnlistedVersions() + { + // "Paged.Package" has three versions, 2.0.0+build is unlisted. + var versions = await _target.ListPackageVersionsAsync("Paged.Package"); - Assert.Equal( - new[] { "1.0.0", "3.0.0" }, - versions.Select(v => v.ToFullString()).ToArray()); - } + Assert.Equal( + new[] { "1.0.0", "3.0.0" }, + versions.Select(v => v.ToFullString()).ToArray()); + } - [Fact] - public async Task ListsPackageVersionsOfPackageThatDoesNotExist() - { - var versions = await _target.ListPackageVersionsAsync(Guid.NewGuid().ToString()); + [Fact] + public async Task ListsPackageVersionsOfPackageThatDoesNotExist() + { + var versions = await _target.ListPackageVersionsAsync(Guid.NewGuid().ToString()); - Assert.Empty(versions); - } + Assert.Empty(versions); + } - [Fact] - public async Task ListsAllPackageVersions() - { - // Unlisted versions are only served by the package content resource, - // which lists 2.0.0 even though the registration marks it unlisted. - var versions = await _target.ListPackageVersionsAsync("Paged.Package", includeUnlisted: true); + [Fact] + public async Task ListsAllPackageVersions() + { + // Unlisted versions are only served by the package content resource, + // which lists 2.0.0 even though the registration marks it unlisted. + var versions = await _target.ListPackageVersionsAsync("Paged.Package", includeUnlisted: true); - Assert.Equal( - new[] { "1.0.0", "2.0.0", "3.0.0" }, - versions.Select(v => v.ToFullString()).ToArray()); - } + Assert.Equal( + new[] { "1.0.0", "2.0.0", "3.0.0" }, + versions.Select(v => v.ToFullString()).ToArray()); + } - [Fact] - public async Task ListsAllPackageVersionsOfPackageThatDoesNotExist() - { - var versions = await _target.ListPackageVersionsAsync( - Guid.NewGuid().ToString(), - includeUnlisted: true); + [Fact] + public async Task ListsAllPackageVersionsOfPackageThatDoesNotExist() + { + var versions = await _target.ListPackageVersionsAsync( + Guid.NewGuid().ToString(), + includeUnlisted: true); - Assert.Empty(versions); - } + Assert.Empty(versions); + } - [Fact] - public async Task GetsPackageMetadataInlined() - { - var metadata = await _target.GetPackageMetadataAsync("Test.Package"); + [Fact] + public async Task GetsPackageMetadataInlined() + { + var metadata = await _target.GetPackageMetadataAsync("Test.Package"); - Assert.Equal(3, metadata.Count); - Assert.All(metadata, m => Assert.Equal("Test.Package", m.PackageId)); - Assert.Equal( - new[] { "1.0.0", "2.0.0+build", "3.0.0" }, - metadata.Select(m => m.Version).ToArray()); - } + Assert.Equal(3, metadata.Count); + Assert.All(metadata, m => Assert.Equal("Test.Package", m.PackageId)); + Assert.Equal( + new[] { "1.0.0", "2.0.0+build", "3.0.0" }, + metadata.Select(m => m.Version).ToArray()); + } - [Fact] - public async Task GetsPackageMetadataPaged() - { - // "Paged.Package"'s registration index does not inline its items, so - // each registration page has to be fetched separately. - var metadata = await _target.GetPackageMetadataAsync("Paged.Package"); - - Assert.Equal(3, metadata.Count); - Assert.All(metadata, m => Assert.Equal("Paged.Package", m.PackageId)); - Assert.Equal( - new[] { "1.0.0", "2.0.0+build", "3.0.0" }, - metadata.Select(m => m.Version).ToArray()); - Assert.Equal( - new bool?[] { true, false, true }, - metadata.Select(m => m.Listed).ToArray()); - } + [Fact] + public async Task GetsPackageMetadataPaged() + { + // "Paged.Package"'s registration index does not inline its items, so + // each registration page has to be fetched separately. + var metadata = await _target.GetPackageMetadataAsync("Paged.Package"); + + Assert.Equal(3, metadata.Count); + Assert.All(metadata, m => Assert.Equal("Paged.Package", m.PackageId)); + Assert.Equal( + new[] { "1.0.0", "2.0.0+build", "3.0.0" }, + metadata.Select(m => m.Version).ToArray()); + Assert.Equal( + new bool?[] { true, false, true }, + metadata.Select(m => m.Listed).ToArray()); + } - [Fact] - public async Task GetsPackageMetadataOfPackageThatDoesNotExist() - { - var metadata = await _target.GetPackageMetadataAsync(Guid.NewGuid().ToString()); + [Fact] + public async Task GetsPackageMetadataOfPackageThatDoesNotExist() + { + var metadata = await _target.GetPackageMetadataAsync(Guid.NewGuid().ToString()); - Assert.Empty(metadata); - } + Assert.Empty(metadata); + } - [Fact] - public async Task GetsSinglePackageMetadataInlined() - { - var metadata = await _target.GetPackageMetadataAsync("Test.Package", NuGetVersion.Parse("2.0.0")); + [Fact] + public async Task GetsSinglePackageMetadataInlined() + { + var metadata = await _target.GetPackageMetadataAsync("Test.Package", NuGetVersion.Parse("2.0.0")); - Assert.Equal("Test.Package", metadata.PackageId); - Assert.Equal("2.0.0+build", metadata.Version); - Assert.Equal("Test Author", metadata.Authors); - } + Assert.Equal("Test.Package", metadata.PackageId); + Assert.Equal("2.0.0+build", metadata.Version); + Assert.Equal("Test Author", metadata.Authors); + } - [Fact] - public async Task GetsSinglePackageMetadataPaged() - { - var metadata = await _target.GetPackageMetadataAsync("Paged.Package", NuGetVersion.Parse("3.0.0")); + [Fact] + public async Task GetsSinglePackageMetadataPaged() + { + var metadata = await _target.GetPackageMetadataAsync("Paged.Package", NuGetVersion.Parse("3.0.0")); - Assert.Equal("Paged.Package", metadata.PackageId); - Assert.Equal("3.0.0", metadata.Version); - Assert.True(metadata.Listed); - } + Assert.Equal("Paged.Package", metadata.PackageId); + Assert.Equal("3.0.0", metadata.Version); + Assert.True(metadata.Listed); + } - [Fact] - public async Task ThrowsIfSinglePackageMetadataVersionDoesNotExist() - { - await Assert.ThrowsAsync( - () => _target.GetPackageMetadataAsync("Test.Package", NuGetVersion.Parse("9.9.9"))); - } + [Fact] + public async Task ThrowsIfSinglePackageMetadataVersionDoesNotExist() + { + await Assert.ThrowsAsync( + () => _target.GetPackageMetadataAsync("Test.Package", NuGetVersion.Parse("9.9.9"))); + } - [Fact] - public async Task ThrowsIfSinglePackageMetadataPackageDoesNotExist() - { - await Assert.ThrowsAsync( - () => _target.GetPackageMetadataAsync(Guid.NewGuid().ToString(), NuGetVersion.Parse("1.0.0"))); - } + [Fact] + public async Task ThrowsIfSinglePackageMetadataPackageDoesNotExist() + { + await Assert.ThrowsAsync( + () => _target.GetPackageMetadataAsync(Guid.NewGuid().ToString(), NuGetVersion.Parse("1.0.0"))); + } - [Fact] - public async Task Searches() - { - var results = await _target.SearchAsync(); + [Fact] + public async Task Searches() + { + var results = await _target.SearchAsync(); - var result = Assert.Single(results); + var result = Assert.Single(results); - Assert.Equal("Test.Package", result.PackageId); - Assert.Equal("3.0.0", result.Version); - Assert.Equal("Package Authors", Assert.Single(result.Authors)); - } + Assert.Equal("Test.Package", result.PackageId); + Assert.Equal("3.0.0", result.Version); + Assert.Equal("Package Authors", Assert.Single(result.Authors)); + } - [Fact] - public async Task Autocompletes() - { - var results = await _target.AutocompleteAsync(); + [Fact] + public async Task Autocompletes() + { + var results = await _target.AutocompleteAsync(); - Assert.Equal("Test.Package", Assert.Single(results)); - } + Assert.Equal("Test.Package", Assert.Single(results)); + } - [Fact] - public async Task PackageExists() - { - Assert.True(await _target.ExistsAsync("Test.Package")); - Assert.True(await _target.ExistsAsync("Test.Package", NuGetVersion.Parse("1.0.0"))); - } + [Fact] + public async Task PackageExists() + { + Assert.True(await _target.ExistsAsync("Test.Package")); + Assert.True(await _target.ExistsAsync("Test.Package", NuGetVersion.Parse("1.0.0"))); + } - [Fact] - public async Task PackageDoesNotExist() - { - Assert.False(await _target.ExistsAsync(Guid.NewGuid().ToString())); - Assert.False(await _target.ExistsAsync("Test.Package", NuGetVersion.Parse("9.9.9"))); - } + [Fact] + public async Task PackageDoesNotExist() + { + Assert.False(await _target.ExistsAsync(Guid.NewGuid().ToString())); + Assert.False(await _target.ExistsAsync("Test.Package", NuGetVersion.Parse("9.9.9"))); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/RawAutocompleteClientTests.cs b/tests/BaGet.Protocol.Tests/RawAutocompleteClientTests.cs index c0914b3ad..5a04806af 100644 --- a/tests/BaGet.Protocol.Tests/RawAutocompleteClientTests.cs +++ b/tests/BaGet.Protocol.Tests/RawAutocompleteClientTests.cs @@ -4,120 +4,119 @@ using BaGet.Protocol.Internal; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class RawAutocompleteClientTests : IClassFixture { - public class RawAutocompleteClientTests : IClassFixture + private readonly RawAutocompleteClient _target; + + public RawAutocompleteClientTests(ProtocolFixture fixture) + { + _target = fixture.AutocompleteClient; + } + + [Fact] + public async Task GetDefaultAutocompleteResults() + { + var response = await _target.AutocompleteAsync(); + + Assert.NotNull(response); + Assert.Equal(1, response.TotalHits); + Assert.Equal("Test.Package", Assert.Single(response.Data)); + } + + [Fact] + public async Task AddsDefaultAutocompleteParameters() + { + var handler = new RecordingHttpMessageHandler(TestData.DefaultAutocomplete); + var target = new RawAutocompleteClient(new HttpClient(handler), TestData.AutocompleteUrl); + + await target.AutocompleteAsync(); + + var url = Assert.Single(handler.Requests); + var query = TestQueryString.Parse(url); + + Assert.Equal("test.example", url.Host); + Assert.Equal("/v3/autocomplete", url.AbsolutePath); + Assert.Equal( + new[] { "prerelease", "semVerLevel", "take" }, + query.Keys.OrderBy(k => k).ToArray()); + Assert.Equal("20", query["take"]); + Assert.Equal("True", query["prerelease"]); + Assert.Equal("2.0.0", query["semVerLevel"]); + } + + [Fact] + public async Task AddsAutocompleteParameters() + { + var handler = new RecordingHttpMessageHandler(TestData.DefaultAutocomplete); + var target = new RawAutocompleteClient(new HttpClient(handler), TestData.AutocompleteUrl); + + await target.AutocompleteAsync( + "query", + skip: 2, + take: 5, + includePrerelease: false, + includeSemVer2: false); + + var url = Assert.Single(handler.Requests); + var query = TestQueryString.Parse(url); + + Assert.Equal("/v3/autocomplete", url.AbsolutePath); + Assert.Equal( + new[] { "q", "skip", "take" }, + query.Keys.OrderBy(k => k).ToArray()); + Assert.Equal("2", query["skip"]); + Assert.Equal("5", query["take"]); + Assert.Equal("query", query["q"]); + } + + [Fact] + public async Task ListsPackageVersions() + { + var response = await _target.ListPackageVersionsAsync("Test.Package"); + + Assert.NotNull(response); + Assert.Equal(3, response.TotalHits); + Assert.Equal(new[] { "1.0.0", "2.0.0", "3.0.0" }, response.Data.ToArray()); + } + + [Fact] + public async Task AddsDefaultListPackageVersionsParameters() + { + var handler = new RecordingHttpMessageHandler(TestData.AutocompleteVersions); + var target = new RawAutocompleteClient(new HttpClient(handler), TestData.AutocompleteUrl); + + await target.ListPackageVersionsAsync("Test.Package"); + + var url = Assert.Single(handler.Requests); + var query = TestQueryString.Parse(url); + + Assert.Equal("/v3/autocomplete", url.AbsolutePath); + Assert.Equal( + new[] { "id", "prerelease", "semVerLevel" }, + query.Keys.OrderBy(k => k).ToArray()); + Assert.Equal("Test.Package", query["id"]); + Assert.Equal("True", query["prerelease"]); + Assert.Equal("2.0.0", query["semVerLevel"]); + } + + [Fact] + public async Task AddsListPackageVersionsParameters() { - private readonly RawAutocompleteClient _target; - - public RawAutocompleteClientTests(ProtocolFixture fixture) - { - _target = fixture.AutocompleteClient; - } - - [Fact] - public async Task GetDefaultAutocompleteResults() - { - var response = await _target.AutocompleteAsync(); - - Assert.NotNull(response); - Assert.Equal(1, response.TotalHits); - Assert.Equal("Test.Package", Assert.Single(response.Data)); - } - - [Fact] - public async Task AddsDefaultAutocompleteParameters() - { - var handler = new RecordingHttpMessageHandler(TestData.DefaultAutocomplete); - var target = new RawAutocompleteClient(new HttpClient(handler), TestData.AutocompleteUrl); - - await target.AutocompleteAsync(); - - var url = Assert.Single(handler.Requests); - var query = TestQueryString.Parse(url); - - Assert.Equal("test.example", url.Host); - Assert.Equal("/v3/autocomplete", url.AbsolutePath); - Assert.Equal( - new[] { "prerelease", "semVerLevel", "take" }, - query.Keys.OrderBy(k => k).ToArray()); - Assert.Equal("20", query["take"]); - Assert.Equal("True", query["prerelease"]); - Assert.Equal("2.0.0", query["semVerLevel"]); - } - - [Fact] - public async Task AddsAutocompleteParameters() - { - var handler = new RecordingHttpMessageHandler(TestData.DefaultAutocomplete); - var target = new RawAutocompleteClient(new HttpClient(handler), TestData.AutocompleteUrl); - - await target.AutocompleteAsync( - "query", - skip: 2, - take: 5, - includePrerelease: false, - includeSemVer2: false); - - var url = Assert.Single(handler.Requests); - var query = TestQueryString.Parse(url); - - Assert.Equal("/v3/autocomplete", url.AbsolutePath); - Assert.Equal( - new[] { "q", "skip", "take" }, - query.Keys.OrderBy(k => k).ToArray()); - Assert.Equal("2", query["skip"]); - Assert.Equal("5", query["take"]); - Assert.Equal("query", query["q"]); - } - - [Fact] - public async Task ListsPackageVersions() - { - var response = await _target.ListPackageVersionsAsync("Test.Package"); - - Assert.NotNull(response); - Assert.Equal(3, response.TotalHits); - Assert.Equal(new[] { "1.0.0", "2.0.0", "3.0.0" }, response.Data.ToArray()); - } - - [Fact] - public async Task AddsDefaultListPackageVersionsParameters() - { - var handler = new RecordingHttpMessageHandler(TestData.AutocompleteVersions); - var target = new RawAutocompleteClient(new HttpClient(handler), TestData.AutocompleteUrl); - - await target.ListPackageVersionsAsync("Test.Package"); - - var url = Assert.Single(handler.Requests); - var query = TestQueryString.Parse(url); - - Assert.Equal("/v3/autocomplete", url.AbsolutePath); - Assert.Equal( - new[] { "id", "prerelease", "semVerLevel" }, - query.Keys.OrderBy(k => k).ToArray()); - Assert.Equal("Test.Package", query["id"]); - Assert.Equal("True", query["prerelease"]); - Assert.Equal("2.0.0", query["semVerLevel"]); - } - - [Fact] - public async Task AddsListPackageVersionsParameters() - { - var handler = new RecordingHttpMessageHandler(TestData.AutocompleteVersions); - var target = new RawAutocompleteClient(new HttpClient(handler), TestData.AutocompleteUrl); - - await target.ListPackageVersionsAsync( - "query", - includePrerelease: false, - includeSemVer2: false); - - var url = Assert.Single(handler.Requests); - var query = TestQueryString.Parse(url); - - Assert.Equal("/v3/autocomplete", url.AbsolutePath); - Assert.Equal(new[] { "id" }, query.Keys.ToArray()); - Assert.Equal("query", query["id"]); - } + var handler = new RecordingHttpMessageHandler(TestData.AutocompleteVersions); + var target = new RawAutocompleteClient(new HttpClient(handler), TestData.AutocompleteUrl); + + await target.ListPackageVersionsAsync( + "query", + includePrerelease: false, + includeSemVer2: false); + + var url = Assert.Single(handler.Requests); + var query = TestQueryString.Parse(url); + + Assert.Equal("/v3/autocomplete", url.AbsolutePath); + Assert.Equal(new[] { "id" }, query.Keys.ToArray()); + Assert.Equal("query", query["id"]); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/RawCatalogClientTests.cs b/tests/BaGet.Protocol.Tests/RawCatalogClientTests.cs index 55ecc029a..30e2eda30 100644 --- a/tests/BaGet.Protocol.Tests/RawCatalogClientTests.cs +++ b/tests/BaGet.Protocol.Tests/RawCatalogClientTests.cs @@ -5,71 +5,70 @@ using BaGet.Protocol.Models; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class RawCatalogClientTests : IClassFixture { - public class RawCatalogClientTests : IClassFixture - { - private readonly RawCatalogClient _target; + private readonly RawCatalogClient _target; - public RawCatalogClientTests(ProtocolFixture fixture) - { - _target = fixture.CatalogClient; - } + public RawCatalogClientTests(ProtocolFixture fixture) + { + _target = fixture.CatalogClient; + } - [Fact] - public async Task GetCatalogIndex() - { - var result = await _target.GetIndexAsync(); + [Fact] + public async Task GetCatalogIndex() + { + var result = await _target.GetIndexAsync(); - Assert.NotNull(result); - Assert.Equal(2, result.Count); - Assert.Equal(2, result.Items.Count); - Assert.Equal(TestData.CatalogPageUrl, result.Items.Select(i => i.CatalogPageUrl).First()); - } + Assert.NotNull(result); + Assert.Equal(2, result.Count); + Assert.Equal(2, result.Items.Count); + Assert.Equal(TestData.CatalogPageUrl, result.Items.Select(i => i.CatalogPageUrl).First()); + } - [Fact] - public async Task GetCatalogPage() - { - var page = await _target.GetPageAsync(TestData.CatalogPageUrl); + [Fact] + public async Task GetCatalogPage() + { + var page = await _target.GetPageAsync(TestData.CatalogPageUrl); - Assert.Equal(2, page.Count); - Assert.Equal(2, page.Items.Count); - Assert.Equal(TestData.CatalogIndexUrl, page.CatalogIndexUrl); - Assert.Equal(TestData.PackageDetailsCatalogLeafUrl, page.Items[0].CatalogLeafUrl); - Assert.Equal(TestData.PackageDeleteCatalogLeafUrl, page.Items[1].CatalogLeafUrl); - } + Assert.Equal(2, page.Count); + Assert.Equal(2, page.Items.Count); + Assert.Equal(TestData.CatalogIndexUrl, page.CatalogIndexUrl); + Assert.Equal(TestData.PackageDetailsCatalogLeafUrl, page.Items[0].CatalogLeafUrl); + Assert.Equal(TestData.PackageDeleteCatalogLeafUrl, page.Items[1].CatalogLeafUrl); + } - [Fact] - public async Task GetPackageDetailsLeaf() - { - var leaf = await _target.GetPackageDetailsLeafAsync(TestData.PackageDetailsCatalogLeafUrl); + [Fact] + public async Task GetPackageDetailsLeaf() + { + var leaf = await _target.GetPackageDetailsLeafAsync(TestData.PackageDetailsCatalogLeafUrl); - Assert.Equal(TestData.PackageDetailsCatalogLeafUrl, leaf.CatalogLeafUrl); - Assert.Equal("PackageDetails", leaf.Type[0]); - Assert.Equal("catalog:Permalink", leaf.Type[1]); + Assert.Equal(TestData.PackageDetailsCatalogLeafUrl, leaf.CatalogLeafUrl); + Assert.Equal("PackageDetails", leaf.Type[0]); + Assert.Equal("catalog:Permalink", leaf.Type[1]); - Assert.Equal("Test.Package", leaf.PackageId); - Assert.Equal("1.0.0", leaf.PackageVersion); - } + Assert.Equal("Test.Package", leaf.PackageId); + Assert.Equal("1.0.0", leaf.PackageVersion); + } - [Fact] - public async Task GetPackageDeleteLeaf() - { - var leaf = await _target.GetPackageDeleteLeafAsync(TestData.PackageDeleteCatalogLeafUrl); + [Fact] + public async Task GetPackageDeleteLeaf() + { + var leaf = await _target.GetPackageDeleteLeafAsync(TestData.PackageDeleteCatalogLeafUrl); - Assert.Equal(TestData.PackageDeleteCatalogLeafUrl, leaf.CatalogLeafUrl); - Assert.Equal("PackageDelete", leaf.Type[0]); - Assert.Equal("catalog:Permalink", leaf.Type[1]); + Assert.Equal(TestData.PackageDeleteCatalogLeafUrl, leaf.CatalogLeafUrl); + Assert.Equal("PackageDelete", leaf.Type[0]); + Assert.Equal("catalog:Permalink", leaf.Type[1]); - Assert.Equal("Deleted.Package", leaf.PackageId); - Assert.Equal("1.0.0", leaf.PackageVersion); - } + Assert.Equal("Deleted.Package", leaf.PackageId); + Assert.Equal("1.0.0", leaf.PackageVersion); + } - [Fact] - public async Task ThrowsOnTypeMismatch() - { - await Assert.ThrowsAsync(() => _target.GetPackageDetailsLeafAsync(TestData.PackageDeleteCatalogLeafUrl)); - await Assert.ThrowsAsync(() => _target.GetPackageDeleteLeafAsync(TestData.PackageDetailsCatalogLeafUrl)); - } + [Fact] + public async Task ThrowsOnTypeMismatch() + { + await Assert.ThrowsAsync(() => _target.GetPackageDetailsLeafAsync(TestData.PackageDeleteCatalogLeafUrl)); + await Assert.ThrowsAsync(() => _target.GetPackageDeleteLeafAsync(TestData.PackageDetailsCatalogLeafUrl)); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/RawPackageContentClientTests.cs b/tests/BaGet.Protocol.Tests/RawPackageContentClientTests.cs index f8194c4fc..fdb906112 100644 --- a/tests/BaGet.Protocol.Tests/RawPackageContentClientTests.cs +++ b/tests/BaGet.Protocol.Tests/RawPackageContentClientTests.cs @@ -6,124 +6,123 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Protocol.Tests -{ - public class RawPackageContentTests : IClassFixture - { - private readonly RawPackageContentClient _target; - - public RawPackageContentTests(ProtocolFixture fixture) - { - _target = fixture.ContentClient; - } +namespace BaGet.Protocol.Tests; - [Fact] - public async Task GetsPackageVersions() - { - var result = await _target.GetPackageVersionsOrNullAsync("Test.Package"); +public class RawPackageContentTests : IClassFixture +{ + private readonly RawPackageContentClient _target; - Assert.NotNull(result); - Assert.Equal(2, result.Versions.Count); - Assert.Equal("1.0.0", result.Versions[0]); - Assert.Equal("2.0.0", result.Versions[1]); - } + public RawPackageContentTests(ProtocolFixture fixture) + { + _target = fixture.ContentClient; + } - [Fact] - public async Task ReturnsNullIfPackageDoesNotExist() - { - var result = await _target.GetPackageVersionsOrNullAsync(Guid.NewGuid().ToString()); + [Fact] + public async Task GetsPackageVersions() + { + var result = await _target.GetPackageVersionsOrNullAsync("Test.Package"); - Assert.Null(result); - } + Assert.NotNull(result); + Assert.Equal(2, result.Versions.Count); + Assert.Equal("1.0.0", result.Versions[0]); + Assert.Equal("2.0.0", result.Versions[1]); + } - [Fact] - public async Task DownloadsPackage() - { - using (var stream = await _target.DownloadPackageOrNullAsync( - "Test.Package", - NuGetVersion.Parse("1.0.0"))) - { - Assert.NotNull(stream); + [Fact] + public async Task ReturnsNullIfPackageDoesNotExist() + { + var result = await _target.GetPackageVersionsOrNullAsync(Guid.NewGuid().ToString()); - using (var reader = new StreamReader(stream)) - { - Assert.Equal(TestData.PackageContentNupkg, await reader.ReadToEndAsync()); - } - } - } + Assert.Null(result); + } - [Fact] - public async Task DownloadsPackageUsingNormalizedLowercasedUrl() + [Fact] + public async Task DownloadsPackage() + { + using (var stream = await _target.DownloadPackageOrNullAsync( + "Test.Package", + NuGetVersion.Parse("1.0.0"))) { - var handler = new RecordingHttpMessageHandler(); - var target = new RawPackageContentClient(new HttpClient(handler), TestData.PackageContentUrl); + Assert.NotNull(stream); - using (await target.DownloadPackageOrNullAsync( - "Test.Package", - NuGetVersion.Parse("1.0.0.0+Build"))) + using (var reader = new StreamReader(stream)) { + Assert.Equal(TestData.PackageContentNupkg, await reader.ReadToEndAsync()); } + } + } - var url = Assert.Single(handler.Requests); + [Fact] + public async Task DownloadsPackageUsingNormalizedLowercasedUrl() + { + var handler = new RecordingHttpMessageHandler(); + var target = new RawPackageContentClient(new HttpClient(handler), TestData.PackageContentUrl); - Assert.Equal( - "/v3/content/test.package/1.0.0/test.package.1.0.0.nupkg", - url.AbsolutePath); + using (await target.DownloadPackageOrNullAsync( + "Test.Package", + NuGetVersion.Parse("1.0.0.0+Build"))) + { } - [Fact] - public async Task ReturnsNullIfPackageToDownloadDoesNotExist() - { - var stream = await _target.DownloadPackageOrNullAsync( - Guid.NewGuid().ToString(), - NuGetVersion.Parse("1.0.0")); + var url = Assert.Single(handler.Requests); - Assert.Null(stream); - } + Assert.Equal( + "/v3/content/test.package/1.0.0/test.package.1.0.0.nupkg", + url.AbsolutePath); + } - [Fact] - public async Task DownloadsPackageManifest() - { - using (var stream = await _target.DownloadPackageManifestOrNullAsync( - "Test.Package", - NuGetVersion.Parse("1.0.0"))) - { - Assert.NotNull(stream); + [Fact] + public async Task ReturnsNullIfPackageToDownloadDoesNotExist() + { + var stream = await _target.DownloadPackageOrNullAsync( + Guid.NewGuid().ToString(), + NuGetVersion.Parse("1.0.0")); - using (var reader = new StreamReader(stream)) - { - Assert.Equal(TestData.PackageContentNuspec, await reader.ReadToEndAsync()); - } - } - } + Assert.Null(stream); + } - [Fact] - public async Task DownloadsPackageManifestUsingNormalizedLowercasedUrl() + [Fact] + public async Task DownloadsPackageManifest() + { + using (var stream = await _target.DownloadPackageManifestOrNullAsync( + "Test.Package", + NuGetVersion.Parse("1.0.0"))) { - var handler = new RecordingHttpMessageHandler(); - var target = new RawPackageContentClient(new HttpClient(handler), TestData.PackageContentUrl); + Assert.NotNull(stream); - using (await target.DownloadPackageManifestOrNullAsync( - "Test.Package", - NuGetVersion.Parse("1.0.0.0+Build"))) + using (var reader = new StreamReader(stream)) { + Assert.Equal(TestData.PackageContentNuspec, await reader.ReadToEndAsync()); } + } + } - var url = Assert.Single(handler.Requests); + [Fact] + public async Task DownloadsPackageManifestUsingNormalizedLowercasedUrl() + { + var handler = new RecordingHttpMessageHandler(); + var target = new RawPackageContentClient(new HttpClient(handler), TestData.PackageContentUrl); - Assert.Equal( - "/v3/content/test.package/1.0.0/test.package.nuspec", - url.AbsolutePath); + using (await target.DownloadPackageManifestOrNullAsync( + "Test.Package", + NuGetVersion.Parse("1.0.0.0+Build"))) + { } - [Fact] - public async Task ReturnsNullIfPackageManifestDoesNotExist() - { - var stream = await _target.DownloadPackageManifestOrNullAsync( - Guid.NewGuid().ToString(), - NuGetVersion.Parse("1.0.0")); + var url = Assert.Single(handler.Requests); - Assert.Null(stream); - } + Assert.Equal( + "/v3/content/test.package/1.0.0/test.package.nuspec", + url.AbsolutePath); + } + + [Fact] + public async Task ReturnsNullIfPackageManifestDoesNotExist() + { + var stream = await _target.DownloadPackageManifestOrNullAsync( + Guid.NewGuid().ToString(), + NuGetVersion.Parse("1.0.0")); + + Assert.Null(stream); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/RawPackageMetadataClientTests.cs b/tests/BaGet.Protocol.Tests/RawPackageMetadataClientTests.cs index e281bb446..05d3ba4d6 100644 --- a/tests/BaGet.Protocol.Tests/RawPackageMetadataClientTests.cs +++ b/tests/BaGet.Protocol.Tests/RawPackageMetadataClientTests.cs @@ -5,164 +5,163 @@ using BaGet.Protocol.Internal; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class RawPackageMetadataClientTests : IClassFixture { - public class RawPackageMetadataClientTests : IClassFixture + private readonly RawPackageMetadataClient _target; + + public RawPackageMetadataClientTests(ProtocolFixture fixture) + { + _target = fixture.MetadataClient; + } + + [Fact] + public async Task GetRegistrationIndexInlinedItems() + { + var result = await _target.GetRegistrationIndexOrNullAsync("Test.Package"); + + Assert.NotNull(result); + Assert.Equal(2, result.Pages.Count); + + Assert.True(result.Pages[0].Count == 1); + Assert.True(result.Pages[0].ItemsOrNull.Count == 1); + Assert.Equal("1.0.0", result.Pages[0].Lower); + Assert.Equal("1.0.0", result.Pages[0].Upper); + Assert.StartsWith(TestData.RegistrationIndexInlinedItemsUrl, result.Pages[0].RegistrationPageUrl); + + Assert.True(result.Pages[1].Count == 2); + Assert.True(result.Pages[1].ItemsOrNull.Count == 2); + Assert.Equal("2.0.0", result.Pages[1].Lower); + Assert.Equal("3.0.0", result.Pages[1].Upper); + Assert.StartsWith(TestData.RegistrationIndexInlinedItemsUrl, result.Pages[1].RegistrationPageUrl); + } + + [Fact] + public async Task GetRegistrationIndexPagedItems() + { + var result = await _target.GetRegistrationIndexOrNullAsync("Paged.Package"); + + Assert.NotNull(result); + Assert.Equal(2, result.Pages.Count); + + Assert.True(result.Pages[0].Count == 1); + Assert.Null(result.Pages[0].ItemsOrNull); + Assert.Equal("1.0.0", result.Pages[0].Lower); + Assert.Equal("1.0.0", result.Pages[0].Upper); + + Assert.True(result.Pages[1].Count == 2); + Assert.Null(result.Pages[1].ItemsOrNull); + Assert.Equal("2.0.0", result.Pages[1].Lower); + Assert.Equal("3.0.0", result.Pages[1].Upper); + } + + [Fact] + public async Task GetRegistrationPage() + { + var result = await _target.GetRegistrationPageAsync(TestData.RegistrationPageUrl); + + Assert.NotNull(result); + Assert.Equal(2, result.Count); + Assert.NotNull(result.ItemsOrNull); + Assert.Equal(2, result.ItemsOrNull.Count); + Assert.Equal("2.0.0", result.Lower); + Assert.Equal("3.0.0", result.Upper); + + var firstMetadata = result.ItemsOrNull[0].PackageMetadata; + + Assert.Equal("Paged.Package", firstMetadata.PackageId); + Assert.Equal("2.0.0+build", firstMetadata.Version); + } + + [Fact] + public async Task GetRegistrationPageDeprecated() + { + var result = await _target.GetRegistrationPageAsync(TestData.RegistrationPageDeprecatedUrl); + + Assert.NotNull(result); + Assert.NotNull(result.ItemsOrNull); + + var metadata = Assert.Single(result.ItemsOrNull).PackageMetadata; + + Assert.Equal("Deprecated.Package", metadata.PackageId); + Assert.Equal("1.0.0", metadata.Version); + + var deprecation = metadata.Deprecation; + + Assert.NotNull(deprecation); + Assert.Equal(new[] { "Legacy", "CriticalBugs" }, deprecation.Reasons.ToArray()); + Assert.Equal( + "This package is deprecated, use the alternate package instead.", + deprecation.Message); + + Assert.NotNull(deprecation.AlternatePackage); + Assert.Equal("Test.Package", deprecation.AlternatePackage.Id); + Assert.Equal("[2.0.0, )", deprecation.AlternatePackage.Range); + } + + [Fact] + public async Task GetRegistrationPageWithoutDeprecation() + { + var result = await _target.GetRegistrationPageAsync(TestData.RegistrationPageUrl); + + Assert.NotNull(result); + Assert.All(result.ItemsOrNull, item => Assert.Null(item.PackageMetadata.Deprecation)); + } + + [Fact] + public async Task ReturnsNullIfRegistrationIndexDoesNotExist() + { + var result = await _target.GetRegistrationIndexOrNullAsync(Guid.NewGuid().ToString()); + + Assert.Null(result); + } + + [Fact] + public async Task ThrowsIfRegistrationPageDoesNotExist() + { + await Assert.ThrowsAsync( + () => _target.GetRegistrationPageAsync( + $"https://test.example/v3/metadata/{Guid.NewGuid()}/page/1.0.0/1.0.0.json")); + } + + [Fact] + public async Task GetsRegistrationLeaf() + { + var result = await _target.GetRegistrationLeafAsync(TestData.RegistrationLeafListedUrl); + + Assert.NotNull(result); + Assert.True(result.Listed); + Assert.Equal(2010, result.Published.Year); + + Assert.Equal( + "https://test.example/v3/content/test.package/1.0.0/test.package.1.0.0.nupkg", + result.PackageContentUrl); + Assert.Equal( + "https://test.example/v3/metadata/test.package/index.json", + result.RegistrationIndexUrl); + Assert.Equal( + "https://test.example/v3/metadata/test.package/1.0.0.json", + result.RegistrationLeafUrl); + } + + [Fact] + public async Task GetsRegistrationLeafUnlisted() { - private readonly RawPackageMetadataClient _target; - - public RawPackageMetadataClientTests(ProtocolFixture fixture) - { - _target = fixture.MetadataClient; - } - - [Fact] - public async Task GetRegistrationIndexInlinedItems() - { - var result = await _target.GetRegistrationIndexOrNullAsync("Test.Package"); - - Assert.NotNull(result); - Assert.Equal(2, result.Pages.Count); - - Assert.True(result.Pages[0].Count == 1); - Assert.True(result.Pages[0].ItemsOrNull.Count == 1); - Assert.Equal("1.0.0", result.Pages[0].Lower); - Assert.Equal("1.0.0", result.Pages[0].Upper); - Assert.StartsWith(TestData.RegistrationIndexInlinedItemsUrl, result.Pages[0].RegistrationPageUrl); - - Assert.True(result.Pages[1].Count == 2); - Assert.True(result.Pages[1].ItemsOrNull.Count == 2); - Assert.Equal("2.0.0", result.Pages[1].Lower); - Assert.Equal("3.0.0", result.Pages[1].Upper); - Assert.StartsWith(TestData.RegistrationIndexInlinedItemsUrl, result.Pages[1].RegistrationPageUrl); - } - - [Fact] - public async Task GetRegistrationIndexPagedItems() - { - var result = await _target.GetRegistrationIndexOrNullAsync("Paged.Package"); - - Assert.NotNull(result); - Assert.Equal(2, result.Pages.Count); - - Assert.True(result.Pages[0].Count == 1); - Assert.Null(result.Pages[0].ItemsOrNull); - Assert.Equal("1.0.0", result.Pages[0].Lower); - Assert.Equal("1.0.0", result.Pages[0].Upper); - - Assert.True(result.Pages[1].Count == 2); - Assert.Null(result.Pages[1].ItemsOrNull); - Assert.Equal("2.0.0", result.Pages[1].Lower); - Assert.Equal("3.0.0", result.Pages[1].Upper); - } - - [Fact] - public async Task GetRegistrationPage() - { - var result = await _target.GetRegistrationPageAsync(TestData.RegistrationPageUrl); - - Assert.NotNull(result); - Assert.Equal(2, result.Count); - Assert.NotNull(result.ItemsOrNull); - Assert.Equal(2, result.ItemsOrNull.Count); - Assert.Equal("2.0.0", result.Lower); - Assert.Equal("3.0.0", result.Upper); - - var firstMetadata = result.ItemsOrNull[0].PackageMetadata; - - Assert.Equal("Paged.Package", firstMetadata.PackageId); - Assert.Equal("2.0.0+build", firstMetadata.Version); - } - - [Fact] - public async Task GetRegistrationPageDeprecated() - { - var result = await _target.GetRegistrationPageAsync(TestData.RegistrationPageDeprecatedUrl); - - Assert.NotNull(result); - Assert.NotNull(result.ItemsOrNull); - - var metadata = Assert.Single(result.ItemsOrNull).PackageMetadata; - - Assert.Equal("Deprecated.Package", metadata.PackageId); - Assert.Equal("1.0.0", metadata.Version); - - var deprecation = metadata.Deprecation; - - Assert.NotNull(deprecation); - Assert.Equal(new[] { "Legacy", "CriticalBugs" }, deprecation.Reasons.ToArray()); - Assert.Equal( - "This package is deprecated, use the alternate package instead.", - deprecation.Message); - - Assert.NotNull(deprecation.AlternatePackage); - Assert.Equal("Test.Package", deprecation.AlternatePackage.Id); - Assert.Equal("[2.0.0, )", deprecation.AlternatePackage.Range); - } - - [Fact] - public async Task GetRegistrationPageWithoutDeprecation() - { - var result = await _target.GetRegistrationPageAsync(TestData.RegistrationPageUrl); - - Assert.NotNull(result); - Assert.All(result.ItemsOrNull, item => Assert.Null(item.PackageMetadata.Deprecation)); - } - - [Fact] - public async Task ReturnsNullIfRegistrationIndexDoesNotExist() - { - var result = await _target.GetRegistrationIndexOrNullAsync(Guid.NewGuid().ToString()); - - Assert.Null(result); - } - - [Fact] - public async Task ThrowsIfRegistrationPageDoesNotExist() - { - await Assert.ThrowsAsync( - () => _target.GetRegistrationPageAsync( - $"https://test.example/v3/metadata/{Guid.NewGuid()}/page/1.0.0/1.0.0.json")); - } - - [Fact] - public async Task GetsRegistrationLeaf() - { - var result = await _target.GetRegistrationLeafAsync(TestData.RegistrationLeafListedUrl); - - Assert.NotNull(result); - Assert.True(result.Listed); - Assert.Equal(2010, result.Published.Year); - - Assert.Equal( - "https://test.example/v3/content/test.package/1.0.0/test.package.1.0.0.nupkg", - result.PackageContentUrl); - Assert.Equal( - "https://test.example/v3/metadata/test.package/index.json", - result.RegistrationIndexUrl); - Assert.Equal( - "https://test.example/v3/metadata/test.package/1.0.0.json", - result.RegistrationLeafUrl); - } - - [Fact] - public async Task GetsRegistrationLeafUnlisted() - { - var result = await _target.GetRegistrationLeafAsync(TestData.RegistrationLeafUnlistedUrl); - - Assert.NotNull(result); - Assert.False(result.Listed); - Assert.Equal(2010, result.Published.Year); - - Assert.Equal( - "https://test.example/v3/content/paged.package/2.0.0/paged.package.2.0.0.nupkg", - result.PackageContentUrl); - Assert.Equal( - "https://test.example/v3/metadata/paged.package/index.json", - result.RegistrationIndexUrl); - Assert.Equal( - "https://test.example/v3/metadata/paged.package/2.0.0.json", - result.RegistrationLeafUrl); - } + var result = await _target.GetRegistrationLeafAsync(TestData.RegistrationLeafUnlistedUrl); + + Assert.NotNull(result); + Assert.False(result.Listed); + Assert.Equal(2010, result.Published.Year); + + Assert.Equal( + "https://test.example/v3/content/paged.package/2.0.0/paged.package.2.0.0.nupkg", + result.PackageContentUrl); + Assert.Equal( + "https://test.example/v3/metadata/paged.package/index.json", + result.RegistrationIndexUrl); + Assert.Equal( + "https://test.example/v3/metadata/paged.package/2.0.0.json", + result.RegistrationLeafUrl); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/RawSearchClientTests.cs b/tests/BaGet.Protocol.Tests/RawSearchClientTests.cs index 6b8afb162..10ab175a6 100644 --- a/tests/BaGet.Protocol.Tests/RawSearchClientTests.cs +++ b/tests/BaGet.Protocol.Tests/RawSearchClientTests.cs @@ -4,108 +4,107 @@ using BaGet.Protocol.Internal; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class RawSearchClientTests : IClassFixture { - public class RawSearchClientTests : IClassFixture + private readonly RawSearchClient _target; + + public RawSearchClientTests(ProtocolFixture fixture) + { + _target = fixture.SearchClient; + } + + [Fact] + public async Task GetDefaultSearchResults() + { + var response = await _target.SearchAsync(); + + Assert.NotNull(response); + Assert.Equal(1, response.TotalHits); + + var result = Assert.Single(response.Data); + Assert.Equal("Test.Package", result.PackageId); + Assert.Equal("Package Authors", Assert.Single(result.Authors)); + Assert.Equal(TestData.RegistrationIndexInlinedItemsUrl, result.RegistrationIndexUrl); + + var packageType = Assert.Single(result.PackageTypes); + Assert.Equal("Dependency", packageType.Name); + } + + [Fact] + public async Task AddsDefaultParameters() + { + var handler = new RecordingHttpMessageHandler(TestData.DefaultSearch); + var target = new RawSearchClient(new HttpClient(handler), TestData.SearchUrl); + + await target.SearchAsync(); + + var url = Assert.Single(handler.Requests); + var query = TestQueryString.Parse(url); + + Assert.Equal("test.example", url.Host); + Assert.Equal("/v3/search", url.AbsolutePath); + Assert.Equal( + new[] { "prerelease", "semVerLevel", "take" }, + query.Keys.OrderBy(k => k).ToArray()); + Assert.Equal("20", query["take"]); + Assert.Equal("True", query["prerelease"]); + Assert.Equal("2.0.0", query["semVerLevel"]); + } + + [Fact] + public async Task AddsParameters() + { + var handler = new RecordingHttpMessageHandler(TestData.DefaultSearch); + var target = new RawSearchClient(new HttpClient(handler), TestData.SearchUrl); + + await target.SearchAsync( + "query", + skip: 2, + take: 5, + includePrerelease: false, + includeSemVer2: false); + + var url = Assert.Single(handler.Requests); + var query = TestQueryString.Parse(url); + + Assert.Equal("/v3/search", url.AbsolutePath); + Assert.Equal( + new[] { "q", "skip", "take" }, + query.Keys.OrderBy(k => k).ToArray()); + Assert.Equal("2", query["skip"]); + Assert.Equal("5", query["take"]); + Assert.Equal("query", query["q"]); + } + + [Fact] + public async Task EscapesTheQuery() { - private readonly RawSearchClient _target; - - public RawSearchClientTests(ProtocolFixture fixture) - { - _target = fixture.SearchClient; - } - - [Fact] - public async Task GetDefaultSearchResults() - { - var response = await _target.SearchAsync(); - - Assert.NotNull(response); - Assert.Equal(1, response.TotalHits); - - var result = Assert.Single(response.Data); - Assert.Equal("Test.Package", result.PackageId); - Assert.Equal("Package Authors", Assert.Single(result.Authors)); - Assert.Equal(TestData.RegistrationIndexInlinedItemsUrl, result.RegistrationIndexUrl); - - var packageType = Assert.Single(result.PackageTypes); - Assert.Equal("Dependency", packageType.Name); - } - - [Fact] - public async Task AddsDefaultParameters() - { - var handler = new RecordingHttpMessageHandler(TestData.DefaultSearch); - var target = new RawSearchClient(new HttpClient(handler), TestData.SearchUrl); - - await target.SearchAsync(); - - var url = Assert.Single(handler.Requests); - var query = TestQueryString.Parse(url); - - Assert.Equal("test.example", url.Host); - Assert.Equal("/v3/search", url.AbsolutePath); - Assert.Equal( - new[] { "prerelease", "semVerLevel", "take" }, - query.Keys.OrderBy(k => k).ToArray()); - Assert.Equal("20", query["take"]); - Assert.Equal("True", query["prerelease"]); - Assert.Equal("2.0.0", query["semVerLevel"]); - } - - [Fact] - public async Task AddsParameters() - { - var handler = new RecordingHttpMessageHandler(TestData.DefaultSearch); - var target = new RawSearchClient(new HttpClient(handler), TestData.SearchUrl); - - await target.SearchAsync( - "query", - skip: 2, - take: 5, - includePrerelease: false, - includeSemVer2: false); - - var url = Assert.Single(handler.Requests); - var query = TestQueryString.Parse(url); - - Assert.Equal("/v3/search", url.AbsolutePath); - Assert.Equal( - new[] { "q", "skip", "take" }, - query.Keys.OrderBy(k => k).ToArray()); - Assert.Equal("2", query["skip"]); - Assert.Equal("5", query["take"]); - Assert.Equal("query", query["q"]); - } - - [Fact] - public async Task EscapesTheQuery() - { - var handler = new RecordingHttpMessageHandler(TestData.DefaultSearch); - var target = new RawSearchClient(new HttpClient(handler), TestData.SearchUrl); - - await target.SearchAsync("packageid:Test.Package Foo&Bar"); - - var url = Assert.Single(handler.Requests); - var query = TestQueryString.Parse(url); - - Assert.DoesNotContain("Foo&Bar", url.AbsoluteUri); - Assert.Equal("packageid:Test.Package Foo&Bar", query["q"]); - } - - [Fact] - public async Task SkipIsOmittedWhenZero() - { - var handler = new RecordingHttpMessageHandler(TestData.DefaultSearch); - var target = new RawSearchClient(new HttpClient(handler), TestData.SearchUrl); - - await target.SearchAsync("query", skip: 0, take: 5); - - var url = Assert.Single(handler.Requests); - var query = TestQueryString.Parse(url); - - Assert.DoesNotContain("skip", query.Keys); - Assert.Equal("5", query["take"]); - } + var handler = new RecordingHttpMessageHandler(TestData.DefaultSearch); + var target = new RawSearchClient(new HttpClient(handler), TestData.SearchUrl); + + await target.SearchAsync("packageid:Test.Package Foo&Bar"); + + var url = Assert.Single(handler.Requests); + var query = TestQueryString.Parse(url); + + Assert.DoesNotContain("Foo&Bar", url.AbsoluteUri); + Assert.Equal("packageid:Test.Package Foo&Bar", query["q"]); + } + + [Fact] + public async Task SkipIsOmittedWhenZero() + { + var handler = new RecordingHttpMessageHandler(TestData.DefaultSearch); + var target = new RawSearchClient(new HttpClient(handler), TestData.SearchUrl); + + await target.SearchAsync("query", skip: 0, take: 5); + + var url = Assert.Single(handler.Requests); + var query = TestQueryString.Parse(url); + + Assert.DoesNotContain("skip", query.Keys); + Assert.Equal("5", query["take"]); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/RawServiceIndexClientTests.cs b/tests/BaGet.Protocol.Tests/RawServiceIndexClientTests.cs index 2af1670d2..9c5c695f8 100644 --- a/tests/BaGet.Protocol.Tests/RawServiceIndexClientTests.cs +++ b/tests/BaGet.Protocol.Tests/RawServiceIndexClientTests.cs @@ -2,30 +2,29 @@ using BaGet.Protocol.Internal; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class RawServiceIndexClientTests : IClassFixture { - public class RawServiceIndexClientTests : IClassFixture - { - private readonly RawServiceIndexClient _target; + private readonly RawServiceIndexClient _target; - public RawServiceIndexClientTests(ProtocolFixture fixture) - { - _target = fixture.ServiceIndexClient; - } + public RawServiceIndexClientTests(ProtocolFixture fixture) + { + _target = fixture.ServiceIndexClient; + } - [Fact] - public async Task GetsServiceIndex() - { - var result = await _target.GetAsync(); + [Fact] + public async Task GetsServiceIndex() + { + var result = await _target.GetAsync(); - Assert.Equal("3.0.0", result.Version); - Assert.Equal(5, result.Resources.Count); + Assert.Equal("3.0.0", result.Version); + Assert.Equal(5, result.Resources.Count); - Assert.Equal(TestData.CatalogIndexUrl, result.GetCatalogResourceUrl()); - Assert.Equal(TestData.PackageMetadataUrl, result.GetPackageMetadataResourceUrl()); - Assert.Equal(TestData.PackageContentUrl, result.GetPackageContentResourceUrl()); - Assert.Equal(TestData.SearchUrl, result.GetSearchQueryResourceUrl()); - Assert.Equal(TestData.AutocompleteUrl, result.GetSearchAutocompleteResourceUrl()); - } + Assert.Equal(TestData.CatalogIndexUrl, result.GetCatalogResourceUrl()); + Assert.Equal(TestData.PackageMetadataUrl, result.GetPackageMetadataResourceUrl()); + Assert.Equal(TestData.PackageContentUrl, result.GetPackageContentResourceUrl()); + Assert.Equal(TestData.SearchUrl, result.GetSearchQueryResourceUrl()); + Assert.Equal(TestData.AutocompleteUrl, result.GetSearchAutocompleteResourceUrl()); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/SearchFailoverTests.cs b/tests/BaGet.Protocol.Tests/SearchFailoverTests.cs index a7285b702..2ba40948c 100644 --- a/tests/BaGet.Protocol.Tests/SearchFailoverTests.cs +++ b/tests/BaGet.Protocol.Tests/SearchFailoverTests.cs @@ -6,287 +6,286 @@ using System.Threading.Tasks; using Xunit; -namespace BaGet.Protocol.Tests -{ - /// - /// The service index may advertise several endpoints for the search and autocomplete - /// resources. These tests cover which failures move on to the next endpoint and which do not. - /// - public class SearchFailoverTests - { - private const string FirstSearchUrl = "https://test.example/v3/search-one"; - private const string SecondSearchUrl = "https://test.example/v3/search-two"; +namespace BaGet.Protocol.Tests; - private const string FirstAutocompleteUrl = "https://test.example/v3/autocomplete-one"; - private const string SecondAutocompleteUrl = "https://test.example/v3/autocomplete-two"; +/// +/// The service index may advertise several endpoints for the search and autocomplete +/// resources. These tests cover which failures move on to the next endpoint and which do not. +/// +public class SearchFailoverTests +{ + private const string FirstSearchUrl = "https://test.example/v3/search-one"; + private const string SecondSearchUrl = "https://test.example/v3/search-two"; - private readonly FakeHttpMessageHandler _handler = new FakeHttpMessageHandler(); + private const string FirstAutocompleteUrl = "https://test.example/v3/autocomplete-one"; + private const string SecondAutocompleteUrl = "https://test.example/v3/autocomplete-two"; - public SearchFailoverTests() - { - _handler.Json( - TestData.ServiceIndexUrl, - FakeServiceIndex.Json( - searchUrls: new[] { FirstSearchUrl, SecondSearchUrl }, - autocompleteUrls: new[] { FirstAutocompleteUrl, SecondAutocompleteUrl })); - } + private readonly FakeHttpMessageHandler _handler = new FakeHttpMessageHandler(); - private NuGetClientFactory CreateFactory() - { - return new NuGetClientFactory(new HttpClient(_handler), TestData.ServiceIndexUrl); - } + public SearchFailoverTests() + { + _handler.Json( + TestData.ServiceIndexUrl, + FakeServiceIndex.Json( + searchUrls: new[] { FirstSearchUrl, SecondSearchUrl }, + autocompleteUrls: new[] { FirstAutocompleteUrl, SecondAutocompleteUrl })); + } - [Fact] - public async Task SearchAsync_FirstEndpointDropsTheResponse_UsesTheNextEndpoint() - { - // A connection dropped while the response body is being read surfaces as an - // IOException, not an HttpRequestException. The endpoint still failed. - _handler.Throws(FirstSearchUrl, () => new IOException("The response ended prematurely.")); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + private NuGetClientFactory CreateFactory() + { + return new NuGetClientFactory(new HttpClient(_handler), TestData.ServiceIndexUrl); + } - var response = await CreateFactory().CreateSearchClient().SearchAsync(); + [Fact] + public async Task SearchAsync_FirstEndpointDropsTheResponse_UsesTheNextEndpoint() + { + // A connection dropped while the response body is being read surfaces as an + // IOException, not an HttpRequestException. The endpoint still failed. + _handler.Throws(FirstSearchUrl, () => new IOException("The response ended prematurely.")); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - Assert.Equal(1, response.TotalHits); - Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); - Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); - } + var response = await CreateFactory().CreateSearchClient().SearchAsync(); - [Fact] - public async Task AutocompleteAsync_FirstEndpointDropsTheResponse_UsesTheNextEndpoint() - { - _handler.Throws(FirstAutocompleteUrl, () => new IOException("The response ended prematurely.")); - _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); + Assert.Equal(1, response.TotalHits); + Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); + Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); + } - var response = await CreateFactory().CreateAutocompleteClient().AutocompleteAsync(); + [Fact] + public async Task AutocompleteAsync_FirstEndpointDropsTheResponse_UsesTheNextEndpoint() + { + _handler.Throws(FirstAutocompleteUrl, () => new IOException("The response ended prematurely.")); + _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); - Assert.Equal(1, response.TotalHits); - Assert.Equal(1, _handler.RequestCount(FirstAutocompleteUrl)); - Assert.Equal(1, _handler.RequestCount(SecondAutocompleteUrl)); - } + var response = await CreateFactory().CreateAutocompleteClient().AutocompleteAsync(); - [Fact] - public async Task SearchAsync_FirstEndpointUnreachable_UsesTheNextEndpoint() - { - _handler.Unreachable(FirstSearchUrl); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + Assert.Equal(1, response.TotalHits); + Assert.Equal(1, _handler.RequestCount(FirstAutocompleteUrl)); + Assert.Equal(1, _handler.RequestCount(SecondAutocompleteUrl)); + } - var response = await CreateFactory().CreateSearchClient().SearchAsync(); + [Fact] + public async Task SearchAsync_FirstEndpointUnreachable_UsesTheNextEndpoint() + { + _handler.Unreachable(FirstSearchUrl); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - Assert.Equal(1, response.TotalHits); - Assert.Equal("Test.Package", Assert.Single(response.Data).PackageId); - Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); - Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); - } + var response = await CreateFactory().CreateSearchClient().SearchAsync(); - [Fact] - public async Task SearchAsync_FirstEndpointHasServerError_UsesTheNextEndpoint() - { - _handler.Status(FirstSearchUrl, HttpStatusCode.ServiceUnavailable); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + Assert.Equal(1, response.TotalHits); + Assert.Equal("Test.Package", Assert.Single(response.Data).PackageId); + Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); + Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); + } - var response = await CreateFactory().CreateSearchClient().SearchAsync(); + [Fact] + public async Task SearchAsync_FirstEndpointHasServerError_UsesTheNextEndpoint() + { + _handler.Status(FirstSearchUrl, HttpStatusCode.ServiceUnavailable); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - Assert.Equal(1, response.TotalHits); - Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); - } + var response = await CreateFactory().CreateSearchClient().SearchAsync(); - [Fact] - public async Task SearchAsync_FirstEndpointTimesOut_UsesTheNextEndpoint() - { - _handler.TimesOut(FirstSearchUrl); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + Assert.Equal(1, response.TotalHits); + Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); + } - var response = await CreateFactory().CreateSearchClient().SearchAsync(); + [Fact] + public async Task SearchAsync_FirstEndpointTimesOut_UsesTheNextEndpoint() + { + _handler.TimesOut(FirstSearchUrl); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - Assert.Equal(1, response.TotalHits); - Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); - } + var response = await CreateFactory().CreateSearchClient().SearchAsync(); - [Fact] - public async Task SearchAsync_EveryEndpointFails_ThrowsEachFailure() - { - _handler.Unreachable(FirstSearchUrl); - _handler.Unreachable(SecondSearchUrl); - - var exception = await Assert.ThrowsAsync( - () => CreateFactory().CreateSearchClient().SearchAsync()); - - Assert.Equal(2, exception.InnerExceptions.Count); - Assert.All(exception.InnerExceptions, inner => Assert.IsType(inner)); - Assert.Contains(FirstSearchUrl, exception.InnerExceptions[0].Message); - Assert.Contains(SecondSearchUrl, exception.InnerExceptions[1].Message); - Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); - Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); - } + Assert.Equal(1, response.TotalHits); + Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); + } - [Fact] - public async Task SearchAsync_OnlyEndpointFails_ThrowsThatFailureUnwrapped() - { - _handler.Json( - TestData.ServiceIndexUrl, - FakeServiceIndex.Json(searchUrls: new[] { FirstSearchUrl })); - _handler.Unreachable(FirstSearchUrl); + [Fact] + public async Task SearchAsync_EveryEndpointFails_ThrowsEachFailure() + { + _handler.Unreachable(FirstSearchUrl); + _handler.Unreachable(SecondSearchUrl); + + var exception = await Assert.ThrowsAsync( + () => CreateFactory().CreateSearchClient().SearchAsync()); + + Assert.Equal(2, exception.InnerExceptions.Count); + Assert.All(exception.InnerExceptions, inner => Assert.IsType(inner)); + Assert.Contains(FirstSearchUrl, exception.InnerExceptions[0].Message); + Assert.Contains(SecondSearchUrl, exception.InnerExceptions[1].Message); + Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); + Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); + } - var exception = await Assert.ThrowsAsync( - () => CreateFactory().CreateSearchClient().SearchAsync()); + [Fact] + public async Task SearchAsync_OnlyEndpointFails_ThrowsThatFailureUnwrapped() + { + _handler.Json( + TestData.ServiceIndexUrl, + FakeServiceIndex.Json(searchUrls: new[] { FirstSearchUrl })); + _handler.Unreachable(FirstSearchUrl); - Assert.Contains(FirstSearchUrl, exception.Message); - } + var exception = await Assert.ThrowsAsync( + () => CreateFactory().CreateSearchClient().SearchAsync()); - [Fact] - public async Task SearchAsync_EndpointAnswersNotFound_DoesNotFailOver() - { - _handler.Status(FirstSearchUrl, HttpStatusCode.NotFound); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + Assert.Contains(FirstSearchUrl, exception.Message); + } - var exception = await Assert.ThrowsAsync( - () => CreateFactory().CreateSearchClient().SearchAsync()); + [Fact] + public async Task SearchAsync_EndpointAnswersNotFound_DoesNotFailOver() + { + _handler.Status(FirstSearchUrl, HttpStatusCode.NotFound); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode); - Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); - Assert.Equal(0, _handler.RequestCount(SecondSearchUrl)); - } + var exception = await Assert.ThrowsAsync( + () => CreateFactory().CreateSearchClient().SearchAsync()); - [Fact] - public async Task SearchAsync_EndpointAnswersBadRequest_DoesNotFailOver() - { - _handler.Status(FirstSearchUrl, HttpStatusCode.BadRequest); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode); + Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); + Assert.Equal(0, _handler.RequestCount(SecondSearchUrl)); + } - var exception = await Assert.ThrowsAsync( - () => CreateFactory().CreateSearchClient().SearchAsync()); + [Fact] + public async Task SearchAsync_EndpointAnswersBadRequest_DoesNotFailOver() + { + _handler.Status(FirstSearchUrl, HttpStatusCode.BadRequest); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - Assert.Equal(HttpStatusCode.BadRequest, exception.StatusCode); - Assert.Equal(0, _handler.RequestCount(SecondSearchUrl)); - } + var exception = await Assert.ThrowsAsync( + () => CreateFactory().CreateSearchClient().SearchAsync()); - [Fact] - public async Task SearchAsync_CallerCancels_DoesNotFailOver() - { - _handler.Json(FirstSearchUrl, TestData.DefaultSearch); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + Assert.Equal(HttpStatusCode.BadRequest, exception.StatusCode); + Assert.Equal(0, _handler.RequestCount(SecondSearchUrl)); + } - var factory = CreateFactory(); + [Fact] + public async Task SearchAsync_CallerCancels_DoesNotFailOver() + { + _handler.Json(FirstSearchUrl, TestData.DefaultSearch); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - // Load the service index before cancelling, so that the cancellation applies to the - // search request and not to the service index request. - await factory.CreateSearchClient().SearchAsync(); + var factory = CreateFactory(); - using (var cancellation = new CancellationTokenSource()) - { - cancellation.Cancel(); + // Load the service index before cancelling, so that the cancellation applies to the + // search request and not to the service index request. + await factory.CreateSearchClient().SearchAsync(); - await Assert.ThrowsAnyAsync( - () => factory.CreateSearchClient().SearchAsync(cancellationToken: cancellation.Token)); - } + using (var cancellation = new CancellationTokenSource()) + { + cancellation.Cancel(); - Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); - Assert.Equal(0, _handler.RequestCount(SecondSearchUrl)); + await Assert.ThrowsAnyAsync( + () => factory.CreateSearchClient().SearchAsync(cancellationToken: cancellation.Token)); } - [Fact] - public async Task AutocompleteAsync_FirstEndpointUnreachable_UsesTheNextEndpoint() - { - _handler.Unreachable(FirstAutocompleteUrl); - _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); + Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); + Assert.Equal(0, _handler.RequestCount(SecondSearchUrl)); + } - var response = await CreateFactory().CreateAutocompleteClient().AutocompleteAsync(); + [Fact] + public async Task AutocompleteAsync_FirstEndpointUnreachable_UsesTheNextEndpoint() + { + _handler.Unreachable(FirstAutocompleteUrl); + _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); - Assert.Equal(1, response.TotalHits); - Assert.Equal("Test.Package", Assert.Single(response.Data)); - Assert.Equal(1, _handler.RequestCount(FirstAutocompleteUrl)); - Assert.Equal(1, _handler.RequestCount(SecondAutocompleteUrl)); - } + var response = await CreateFactory().CreateAutocompleteClient().AutocompleteAsync(); - [Fact] - public async Task AutocompleteAsync_EndpointAnswersNotFound_DoesNotFailOver() - { - _handler.Status(FirstAutocompleteUrl, HttpStatusCode.NotFound); - _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); + Assert.Equal(1, response.TotalHits); + Assert.Equal("Test.Package", Assert.Single(response.Data)); + Assert.Equal(1, _handler.RequestCount(FirstAutocompleteUrl)); + Assert.Equal(1, _handler.RequestCount(SecondAutocompleteUrl)); + } - var exception = await Assert.ThrowsAsync( - () => CreateFactory().CreateAutocompleteClient().AutocompleteAsync()); + [Fact] + public async Task AutocompleteAsync_EndpointAnswersNotFound_DoesNotFailOver() + { + _handler.Status(FirstAutocompleteUrl, HttpStatusCode.NotFound); + _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); - Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode); - Assert.Equal(0, _handler.RequestCount(SecondAutocompleteUrl)); - } + var exception = await Assert.ThrowsAsync( + () => CreateFactory().CreateAutocompleteClient().AutocompleteAsync()); - [Fact] - public async Task AutocompleteAsync_EveryEndpointFails_ThrowsEachFailure() - { - _handler.Unreachable(FirstAutocompleteUrl); - _handler.Unreachable(SecondAutocompleteUrl); + Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode); + Assert.Equal(0, _handler.RequestCount(SecondAutocompleteUrl)); + } - var exception = await Assert.ThrowsAsync( - () => CreateFactory().CreateAutocompleteClient().AutocompleteAsync()); + [Fact] + public async Task AutocompleteAsync_EveryEndpointFails_ThrowsEachFailure() + { + _handler.Unreachable(FirstAutocompleteUrl); + _handler.Unreachable(SecondAutocompleteUrl); - Assert.Equal(2, exception.InnerExceptions.Count); - } + var exception = await Assert.ThrowsAsync( + () => CreateFactory().CreateAutocompleteClient().AutocompleteAsync()); - [Fact] - public async Task ListPackageVersionsAsync_FirstEndpointUnreachable_UsesTheNextEndpoint() - { - _handler.Unreachable(FirstAutocompleteUrl); - _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); + Assert.Equal(2, exception.InnerExceptions.Count); + } - var response = await CreateFactory() - .CreateAutocompleteClient() - .ListPackageVersionsAsync("Test.Package"); + [Fact] + public async Task ListPackageVersionsAsync_FirstEndpointUnreachable_UsesTheNextEndpoint() + { + _handler.Unreachable(FirstAutocompleteUrl); + _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); - Assert.Equal(1, response.TotalHits); - Assert.Equal(1, _handler.RequestCount(FirstAutocompleteUrl)); - Assert.Equal(1, _handler.RequestCount(SecondAutocompleteUrl)); - } + var response = await CreateFactory() + .CreateAutocompleteClient() + .ListPackageVersionsAsync("Test.Package"); - [Fact] - public async Task ListPackageVersionsAsync_EndpointAnswersNotFound_DoesNotFailOver() - { - _handler.Status(FirstAutocompleteUrl, HttpStatusCode.NotFound); - _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); + Assert.Equal(1, response.TotalHits); + Assert.Equal(1, _handler.RequestCount(FirstAutocompleteUrl)); + Assert.Equal(1, _handler.RequestCount(SecondAutocompleteUrl)); + } - await Assert.ThrowsAsync( - () => CreateFactory().CreateAutocompleteClient().ListPackageVersionsAsync("Test.Package")); + [Fact] + public async Task ListPackageVersionsAsync_EndpointAnswersNotFound_DoesNotFailOver() + { + _handler.Status(FirstAutocompleteUrl, HttpStatusCode.NotFound); + _handler.Json(SecondAutocompleteUrl, TestData.DefaultAutocomplete); - Assert.Equal(0, _handler.RequestCount(SecondAutocompleteUrl)); - } + await Assert.ThrowsAsync( + () => CreateFactory().CreateAutocompleteClient().ListPackageVersionsAsync("Test.Package")); - [Fact] - public async Task AutocompleteAsync_ServiceIndexHasNoAutocompleteResource_ReturnsNoResults() - { - _handler.Json( - TestData.ServiceIndexUrl, - FakeServiceIndex.Json( - searchUrls: new[] { FirstSearchUrl }, - autocompleteUrls: Array.Empty())); + Assert.Equal(0, _handler.RequestCount(SecondAutocompleteUrl)); + } - var response = await CreateFactory().CreateAutocompleteClient().AutocompleteAsync(); + [Fact] + public async Task AutocompleteAsync_ServiceIndexHasNoAutocompleteResource_ReturnsNoResults() + { + _handler.Json( + TestData.ServiceIndexUrl, + FakeServiceIndex.Json( + searchUrls: new[] { FirstSearchUrl }, + autocompleteUrls: Array.Empty())); - Assert.Equal(0, response.TotalHits); - Assert.Empty(response.Data); - } + var response = await CreateFactory().CreateAutocompleteClient().AutocompleteAsync(); - [Fact] - public async Task SearchAsync_DuplicateEndpoints_TriesEachEndpointOnce() - { - // nuget.org advertises the same URL under several resource type versions. A failover - // must not retry a URL that already failed. - _handler.Json( - TestData.ServiceIndexUrl, - "{\"version\":\"3.0.0\",\"resources\":[" - + "{\"@id\":\"" + TestData.PackageContentUrl + "\",\"@type\":\"PackageBaseAddress/3.0.0\"}," - + "{\"@id\":\"" + TestData.PackageMetadataUrl + "\",\"@type\":\"RegistrationsBaseUrl/3.6.0\"}," - + "{\"@id\":\"" + FirstSearchUrl + "\",\"@type\":\"SearchQueryService/3.4.0\"}," - + "{\"@id\":\"" + FirstSearchUrl + "\",\"@type\":\"SearchQueryService/3.0.0-beta\"}," - + "{\"@id\":\"" + SecondSearchUrl + "\",\"@type\":\"SearchQueryService\"}]}"); - - _handler.Unreachable(FirstSearchUrl); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - - var response = await CreateFactory().CreateSearchClient().SearchAsync(); - - Assert.Equal(1, response.TotalHits); - Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); - Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); - } + Assert.Equal(0, response.TotalHits); + Assert.Empty(response.Data); + } + + [Fact] + public async Task SearchAsync_DuplicateEndpoints_TriesEachEndpointOnce() + { + // nuget.org advertises the same URL under several resource type versions. A failover + // must not retry a URL that already failed. + _handler.Json( + TestData.ServiceIndexUrl, + "{\"version\":\"3.0.0\",\"resources\":[" + + "{\"@id\":\"" + TestData.PackageContentUrl + "\",\"@type\":\"PackageBaseAddress/3.0.0\"}," + + "{\"@id\":\"" + TestData.PackageMetadataUrl + "\",\"@type\":\"RegistrationsBaseUrl/3.6.0\"}," + + "{\"@id\":\"" + FirstSearchUrl + "\",\"@type\":\"SearchQueryService/3.4.0\"}," + + "{\"@id\":\"" + FirstSearchUrl + "\",\"@type\":\"SearchQueryService/3.0.0-beta\"}," + + "{\"@id\":\"" + SecondSearchUrl + "\",\"@type\":\"SearchQueryService\"}]}"); + + _handler.Unreachable(FirstSearchUrl); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + + var response = await CreateFactory().CreateSearchClient().SearchAsync(); + + Assert.Equal(1, response.TotalHits); + Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); + Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/ServiceIndexRefreshTests.cs b/tests/BaGet.Protocol.Tests/ServiceIndexRefreshTests.cs index d91ef61e7..e6d928e72 100644 --- a/tests/BaGet.Protocol.Tests/ServiceIndexRefreshTests.cs +++ b/tests/BaGet.Protocol.Tests/ServiceIndexRefreshTests.cs @@ -4,120 +4,119 @@ using System.Threading.Tasks; using Xunit; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +/// +/// The factory caches the service index response. These tests cover that the cache expires, +/// so a long-lived client picks up changes to the server's resources, and that it is not +/// re-fetched before it expires. +/// +public class ServiceIndexRefreshTests { - /// - /// The factory caches the service index response. These tests cover that the cache expires, - /// so a long-lived client picks up changes to the server's resources, and that it is not - /// re-fetched before it expires. - /// - public class ServiceIndexRefreshTests + private const string FirstSearchUrl = "https://test.example/v3/search-one"; + private const string SecondSearchUrl = "https://test.example/v3/search-two"; + + private readonly FakeHttpMessageHandler _handler = new FakeHttpMessageHandler(); + private readonly TimeSpan _cacheDuration = TimeSpan.FromMinutes(40); + + private DateTimeOffset _now = new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero); + private string _searchUrl = FirstSearchUrl; + + public ServiceIndexRefreshTests() + { + _handler.Json( + TestData.ServiceIndexUrl, + () => FakeServiceIndex.Json(searchUrls: new[] { _searchUrl })); + + _handler.Json(FirstSearchUrl, TestData.DefaultSearch); + _handler.Json(SecondSearchUrl, TestData.DefaultSearch); + } + + private NuGetClientFactory CreateFactory() + { + return new NuGetClientFactory( + new HttpClient(_handler), + TestData.ServiceIndexUrl, + _cacheDuration, + () => _now); + } + + [Fact] + public async Task ServiceIndex_BeforeTheCacheExpires_IsNotFetchedAgain() + { + var factory = CreateFactory(); + + await factory.CreateSearchClient().SearchAsync(); + _now += _cacheDuration - TimeSpan.FromSeconds(1); + _searchUrl = SecondSearchUrl; + await factory.CreateSearchClient().SearchAsync(); + + Assert.Equal(1, _handler.RequestCount(TestData.ServiceIndexUrl)); + Assert.Equal(2, _handler.RequestCount(FirstSearchUrl)); + Assert.Equal(0, _handler.RequestCount(SecondSearchUrl)); + } + + [Fact] + public async Task ServiceIndex_OnceTheCacheExpires_IsFetchedAgain() + { + var factory = CreateFactory(); + + await factory.CreateSearchClient().SearchAsync(); + _now += _cacheDuration; + _searchUrl = SecondSearchUrl; + await factory.CreateSearchClient().SearchAsync(); + + // The refreshed index moved the search resource, and the client followed it. + Assert.Equal(2, _handler.RequestCount(TestData.ServiceIndexUrl)); + Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); + Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); + } + + [Fact] + public async Task ServiceIndex_AfterRefreshing_IsCachedAgain() + { + var factory = CreateFactory(); + + await factory.CreateSearchClient().SearchAsync(); + _now += _cacheDuration; + await factory.CreateSearchClient().SearchAsync(); + await factory.CreateSearchClient().SearchAsync(); + + Assert.Equal(2, _handler.RequestCount(TestData.ServiceIndexUrl)); + } + + [Fact] + public async Task ServiceIndex_WhenTheRefreshFails_SurfacesTheFailure() + { + var factory = CreateFactory(); + + await factory.CreateSearchClient().SearchAsync(); + _now += _cacheDuration; + _handler.Unreachable(TestData.ServiceIndexUrl); + + // A stale service index is not served in place of a failed refresh: an index that + // cannot be read is reported, as its resources may have moved. + await Assert.ThrowsAsync( + () => factory.CreateSearchClient().SearchAsync()); + } + + [Fact] + public async Task ServiceIndex_WithConcurrentCallers_IsFetchedOnce() + { + var factory = CreateFactory(); + + await Task.WhenAll(Enumerable + .Range(0, 8) + .Select(_ => Task.Run(() => factory.CreateSearchClient().SearchAsync()))); + + Assert.Equal(1, _handler.RequestCount(TestData.ServiceIndexUrl)); + Assert.Equal(8, _handler.RequestCount(FirstSearchUrl)); + } + + [Fact] + public void ServiceIndexCacheDuration_IsBoundedByDefault() { - private const string FirstSearchUrl = "https://test.example/v3/search-one"; - private const string SecondSearchUrl = "https://test.example/v3/search-two"; - - private readonly FakeHttpMessageHandler _handler = new FakeHttpMessageHandler(); - private readonly TimeSpan _cacheDuration = TimeSpan.FromMinutes(40); - - private DateTimeOffset _now = new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero); - private string _searchUrl = FirstSearchUrl; - - public ServiceIndexRefreshTests() - { - _handler.Json( - TestData.ServiceIndexUrl, - () => FakeServiceIndex.Json(searchUrls: new[] { _searchUrl })); - - _handler.Json(FirstSearchUrl, TestData.DefaultSearch); - _handler.Json(SecondSearchUrl, TestData.DefaultSearch); - } - - private NuGetClientFactory CreateFactory() - { - return new NuGetClientFactory( - new HttpClient(_handler), - TestData.ServiceIndexUrl, - _cacheDuration, - () => _now); - } - - [Fact] - public async Task ServiceIndex_BeforeTheCacheExpires_IsNotFetchedAgain() - { - var factory = CreateFactory(); - - await factory.CreateSearchClient().SearchAsync(); - _now += _cacheDuration - TimeSpan.FromSeconds(1); - _searchUrl = SecondSearchUrl; - await factory.CreateSearchClient().SearchAsync(); - - Assert.Equal(1, _handler.RequestCount(TestData.ServiceIndexUrl)); - Assert.Equal(2, _handler.RequestCount(FirstSearchUrl)); - Assert.Equal(0, _handler.RequestCount(SecondSearchUrl)); - } - - [Fact] - public async Task ServiceIndex_OnceTheCacheExpires_IsFetchedAgain() - { - var factory = CreateFactory(); - - await factory.CreateSearchClient().SearchAsync(); - _now += _cacheDuration; - _searchUrl = SecondSearchUrl; - await factory.CreateSearchClient().SearchAsync(); - - // The refreshed index moved the search resource, and the client followed it. - Assert.Equal(2, _handler.RequestCount(TestData.ServiceIndexUrl)); - Assert.Equal(1, _handler.RequestCount(FirstSearchUrl)); - Assert.Equal(1, _handler.RequestCount(SecondSearchUrl)); - } - - [Fact] - public async Task ServiceIndex_AfterRefreshing_IsCachedAgain() - { - var factory = CreateFactory(); - - await factory.CreateSearchClient().SearchAsync(); - _now += _cacheDuration; - await factory.CreateSearchClient().SearchAsync(); - await factory.CreateSearchClient().SearchAsync(); - - Assert.Equal(2, _handler.RequestCount(TestData.ServiceIndexUrl)); - } - - [Fact] - public async Task ServiceIndex_WhenTheRefreshFails_SurfacesTheFailure() - { - var factory = CreateFactory(); - - await factory.CreateSearchClient().SearchAsync(); - _now += _cacheDuration; - _handler.Unreachable(TestData.ServiceIndexUrl); - - // A stale service index is not served in place of a failed refresh: an index that - // cannot be read is reported, as its resources may have moved. - await Assert.ThrowsAsync( - () => factory.CreateSearchClient().SearchAsync()); - } - - [Fact] - public async Task ServiceIndex_WithConcurrentCallers_IsFetchedOnce() - { - var factory = CreateFactory(); - - await Task.WhenAll(Enumerable - .Range(0, 8) - .Select(_ => Task.Run(() => factory.CreateSearchClient().SearchAsync()))); - - Assert.Equal(1, _handler.RequestCount(TestData.ServiceIndexUrl)); - Assert.Equal(8, _handler.RequestCount(FirstSearchUrl)); - } - - [Fact] - public void ServiceIndexCacheDuration_IsBoundedByDefault() - { - Assert.True(NuGetClientFactory.DefaultServiceIndexCacheDuration > TimeSpan.Zero); - Assert.True(NuGetClientFactory.DefaultServiceIndexCacheDuration <= TimeSpan.FromHours(1)); - } + Assert.True(NuGetClientFactory.DefaultServiceIndexCacheDuration > TimeSpan.Zero); + Assert.True(NuGetClientFactory.DefaultServiceIndexCacheDuration <= TimeSpan.FromHours(1)); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Support/CountingHttpMessageHandler.cs b/tests/BaGet.Protocol.Tests/Support/CountingHttpMessageHandler.cs index 9fd1993a7..20cc38490 100644 --- a/tests/BaGet.Protocol.Tests/Support/CountingHttpMessageHandler.cs +++ b/tests/BaGet.Protocol.Tests/Support/CountingHttpMessageHandler.cs @@ -5,47 +5,46 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +/// +/// Records the requests that pass through to an inner handler, so tests can +/// assert how many times a resource was fetched. +/// +public class CountingHttpMessageHandler : DelegatingHandler { - /// - /// Records the requests that pass through to an inner handler, so tests can - /// assert how many times a resource was fetched. - /// - public class CountingHttpMessageHandler : DelegatingHandler - { - private readonly List _requests = new List(); + private readonly List _requests = new List(); - public CountingHttpMessageHandler(HttpMessageHandler innerHandler) - : base(innerHandler) - { - } + public CountingHttpMessageHandler(HttpMessageHandler innerHandler) + : base(innerHandler) + { + } - public IReadOnlyList Requests + public IReadOnlyList Requests + { + get { - get + lock (_requests) { - lock (_requests) - { - return _requests.ToArray(); - } + return _requests.ToArray(); } } + } - public int RequestCount(string url) - { - return Requests.Count(u => u.AbsoluteUri == url); - } + public int RequestCount(string url) + { + return Requests.Count(u => u.AbsoluteUri == url); + } - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + lock (_requests) { - lock (_requests) - { - _requests.Add(request.RequestUri); - } - - return base.SendAsync(request, cancellationToken); + _requests.Add(request.RequestUri); } + + return base.SendAsync(request, cancellationToken); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Support/FakeHttpMessageHandler.cs b/tests/BaGet.Protocol.Tests/Support/FakeHttpMessageHandler.cs index 4a32000af..8b335a78c 100644 --- a/tests/BaGet.Protocol.Tests/Support/FakeHttpMessageHandler.cs +++ b/tests/BaGet.Protocol.Tests/Support/FakeHttpMessageHandler.cs @@ -6,130 +6,129 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +/// +/// An that serves responses configured per URL and records +/// the requests it received. serves fixed test data; +/// this one lets a test make an endpoint fail, change its answer, or assert that an endpoint +/// was never requested. +/// +/// Query strings are ignored when matching, as the clients add their own. +/// +public class FakeHttpMessageHandler : HttpMessageHandler { + private readonly Dictionary> _responses + = new Dictionary>(StringComparer.Ordinal); + + private readonly List _requests = new List(); + private readonly object _lock = new object(); + /// - /// An that serves responses configured per URL and records - /// the requests it received. serves fixed test data; - /// this one lets a test make an endpoint fail, change its answer, or assert that an endpoint - /// was never requested. - /// - /// Query strings are ignored when matching, as the clients add their own. + /// The URLs that were requested, without their query strings, in order. /// - public class FakeHttpMessageHandler : HttpMessageHandler + public IReadOnlyList Requests { - private readonly Dictionary> _responses - = new Dictionary>(StringComparer.Ordinal); + get { lock (_lock) { return _requests.ToList(); } } + } - private readonly List _requests = new List(); - private readonly object _lock = new object(); + /// + /// How many times a URL was requested. + /// + public int RequestCount(string url) => Requests.Count(request => request == Key(url)); - /// - /// The URLs that were requested, without their query strings, in order. - /// - public IReadOnlyList Requests - { - get { lock (_lock) { return _requests.ToList(); } } - } + /// + /// Serve JSON content for a URL. + /// + public FakeHttpMessageHandler Json(string url, string content) => Json(url, () => content); - /// - /// How many times a URL was requested. - /// - public int RequestCount(string url) => Requests.Count(request => request == Key(url)); - - /// - /// Serve JSON content for a URL. - /// - public FakeHttpMessageHandler Json(string url, string content) => Json(url, () => content); - - /// - /// Serve JSON content for a URL. The content is resolved on each request, so a test can - /// change what an endpoint answers. - /// - public FakeHttpMessageHandler Json(string url, Func content) + /// + /// Serve JSON content for a URL. The content is resolved on each request, so a test can + /// change what an endpoint answers. + /// + public FakeHttpMessageHandler Json(string url, Func content) + { + return Respond(url, request => new HttpResponseMessage { - return Respond(url, request => new HttpResponseMessage - { - RequestMessage = request, - StatusCode = HttpStatusCode.OK, - Content = new StringContent(content(), encoding: null, mediaType: "application/json"), - }); - } + RequestMessage = request, + StatusCode = HttpStatusCode.OK, + Content = new StringContent(content(), encoding: null, mediaType: "application/json"), + }); + } - /// - /// Answer a URL with a status code and no content. The server answered: this is not a - /// transport failure. - /// - public FakeHttpMessageHandler Status(string url, HttpStatusCode statusCode) + /// + /// Answer a URL with a status code and no content. The server answered: this is not a + /// transport failure. + /// + public FakeHttpMessageHandler Status(string url, HttpStatusCode statusCode) + { + return Respond(url, request => new HttpResponseMessage { - return Respond(url, request => new HttpResponseMessage - { - RequestMessage = request, - StatusCode = statusCode, - Content = new StringContent(string.Empty), - }); - } + RequestMessage = request, + StatusCode = statusCode, + Content = new StringContent(string.Empty), + }); + } - /// - /// Fail a URL at the transport level, the way a refused connection, a DNS failure or a - /// dropped response does: an with no status code. - /// - public FakeHttpMessageHandler Unreachable(string url) - { - return Throws(url, () => new HttpRequestException($"Connection refused by {url}")); - } + /// + /// Fail a URL at the transport level, the way a refused connection, a DNS failure or a + /// dropped response does: an with no status code. + /// + public FakeHttpMessageHandler Unreachable(string url) + { + return Throws(url, () => new HttpRequestException($"Connection refused by {url}")); + } - /// - /// Fail a URL the way reports its own timeout: a cancellation - /// that the caller did not ask for. - /// - public FakeHttpMessageHandler TimesOut(string url) - { - return Throws(url, () => new TaskCanceledException( - $"The request to {url} timed out", - new TimeoutException())); - } + /// + /// Fail a URL the way reports its own timeout: a cancellation + /// that the caller did not ask for. + /// + public FakeHttpMessageHandler TimesOut(string url) + { + return Throws(url, () => new TaskCanceledException( + $"The request to {url} timed out", + new TimeoutException())); + } - /// - /// Throw when a URL is requested. - /// - public FakeHttpMessageHandler Throws(string url, Func exception) - { - return Respond(url, _ => throw exception()); - } + /// + /// Throw when a URL is requested. + /// + public FakeHttpMessageHandler Throws(string url, Func exception) + { + return Respond(url, _ => throw exception()); + } - private FakeHttpMessageHandler Respond(string url, Func respond) - { - _responses[Key(url)] = respond; - return this; - } + private FakeHttpMessageHandler Respond(string url, Func respond) + { + _responses[Key(url)] = respond; + return this; + } - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); - var key = Key(request.RequestUri); + var key = Key(request.RequestUri); - lock (_lock) - { - _requests.Add(key); - } + lock (_lock) + { + _requests.Add(key); + } - if (request.Method != HttpMethod.Get || !_responses.TryGetValue(key, out var respond)) + if (request.Method != HttpMethod.Get || !_responses.TryGetValue(key, out var respond)) + { + return Task.FromResult(new HttpResponseMessage { - return Task.FromResult(new HttpResponseMessage - { - RequestMessage = request, - StatusCode = HttpStatusCode.NotFound, - Content = new StringContent(string.Empty), - }); - } - - return Task.FromResult(respond(request)); + RequestMessage = request, + StatusCode = HttpStatusCode.NotFound, + Content = new StringContent(string.Empty), + }); } - private static string Key(string url) => Key(new Uri(url)); - - private static string Key(Uri url) => url.GetLeftPart(UriPartial.Path).TrimEnd('/'); + return Task.FromResult(respond(request)); } -} + + private static string Key(string url) => Key(new Uri(url)); + + private static string Key(Uri url) => url.GetLeftPart(UriPartial.Path).TrimEnd('/'); +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Support/FakeServiceIndex.cs b/tests/BaGet.Protocol.Tests/Support/FakeServiceIndex.cs index 437bbcdc4..2a8ea8b6b 100644 --- a/tests/BaGet.Protocol.Tests/Support/FakeServiceIndex.cs +++ b/tests/BaGet.Protocol.Tests/Support/FakeServiceIndex.cs @@ -1,41 +1,40 @@ using System.Collections.Generic; using System.Linq; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +/// +/// Builds service index responses that advertise a chosen set of endpoints, so that a test +/// can advertise several endpoints for one resource. is +/// the realistic, single-endpoint index. +/// +public static class FakeServiceIndex { /// - /// Builds service index responses that advertise a chosen set of endpoints, so that a test - /// can advertise several endpoints for one resource. is - /// the realistic, single-endpoint index. + /// A service index that advertises the given search and autocomplete endpoints, in order, + /// plus the package content and metadata resources every index is required to have. /// - public static class FakeServiceIndex + public static string Json( + IEnumerable searchUrls = null, + IEnumerable autocompleteUrls = null) { - /// - /// A service index that advertises the given search and autocomplete endpoints, in order, - /// plus the package content and metadata resources every index is required to have. - /// - public static string Json( - IEnumerable searchUrls = null, - IEnumerable autocompleteUrls = null) + var resources = new List { - var resources = new List - { - Resource(TestData.PackageContentUrl, "PackageBaseAddress/3.0.0"), - Resource(TestData.PackageMetadataUrl, "RegistrationsBaseUrl/3.6.0"), - }; + Resource(TestData.PackageContentUrl, "PackageBaseAddress/3.0.0"), + Resource(TestData.PackageMetadataUrl, "RegistrationsBaseUrl/3.6.0"), + }; - resources.AddRange((searchUrls ?? new[] { TestData.SearchUrl }) - .Select(url => Resource(url, "SearchQueryService/3.4.0"))); + resources.AddRange((searchUrls ?? new[] { TestData.SearchUrl }) + .Select(url => Resource(url, "SearchQueryService/3.4.0"))); - resources.AddRange((autocompleteUrls ?? new[] { TestData.AutocompleteUrl }) - .Select(url => Resource(url, "SearchAutocompleteService/3.0.0-beta"))); + resources.AddRange((autocompleteUrls ?? new[] { TestData.AutocompleteUrl }) + .Select(url => Resource(url, "SearchAutocompleteService/3.0.0-beta"))); - return "{\"version\":\"3.0.0\",\"resources\":[" + string.Join(",", resources) + "]}"; - } + return "{\"version\":\"3.0.0\",\"resources\":[" + string.Join(",", resources) + "]}"; + } - private static string Resource(string url, string type) - { - return "{\"@id\":\"" + url + "\",\"@type\":\"" + type + "\"}"; - } + private static string Resource(string url, string type) + { + return "{\"@id\":\"" + url + "\",\"@type\":\"" + type + "\"}"; } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Support/ProtocolFixture.cs b/tests/BaGet.Protocol.Tests/Support/ProtocolFixture.cs index cd7905870..bda096fd8 100644 --- a/tests/BaGet.Protocol.Tests/Support/ProtocolFixture.cs +++ b/tests/BaGet.Protocol.Tests/Support/ProtocolFixture.cs @@ -2,33 +2,32 @@ using System.Net.Http; using BaGet.Protocol.Internal; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +public class ProtocolFixture { - public class ProtocolFixture + public ProtocolFixture() { - public ProtocolFixture() - { - var httpClient = new HttpClient(new TestDataHttpMessageHandler()); + var httpClient = new HttpClient(new TestDataHttpMessageHandler()); - NuGetClientFactory = new NuGetClientFactory(httpClient, TestData.ServiceIndexUrl); - NuGetClient = new NuGetClient(NuGetClientFactory); + NuGetClientFactory = new NuGetClientFactory(httpClient, TestData.ServiceIndexUrl); + NuGetClient = new NuGetClient(NuGetClientFactory); - ServiceIndexClient = new RawServiceIndexClient(httpClient, TestData.ServiceIndexUrl); - ContentClient = new RawPackageContentClient(httpClient, TestData.PackageContentUrl); - MetadataClient = new RawPackageMetadataClient(httpClient, TestData.PackageMetadataUrl); - SearchClient = new RawSearchClient(httpClient, TestData.SearchUrl); - AutocompleteClient = new RawAutocompleteClient(httpClient, TestData.AutocompleteUrl); - CatalogClient = new RawCatalogClient(httpClient, TestData.CatalogIndexUrl); - } + ServiceIndexClient = new RawServiceIndexClient(httpClient, TestData.ServiceIndexUrl); + ContentClient = new RawPackageContentClient(httpClient, TestData.PackageContentUrl); + MetadataClient = new RawPackageMetadataClient(httpClient, TestData.PackageMetadataUrl); + SearchClient = new RawSearchClient(httpClient, TestData.SearchUrl); + AutocompleteClient = new RawAutocompleteClient(httpClient, TestData.AutocompleteUrl); + CatalogClient = new RawCatalogClient(httpClient, TestData.CatalogIndexUrl); + } - public NuGetClient NuGetClient { get; } - public NuGetClientFactory NuGetClientFactory { get; } + public NuGetClient NuGetClient { get; } + public NuGetClientFactory NuGetClientFactory { get; } - public RawServiceIndexClient ServiceIndexClient { get; } - public RawPackageContentClient ContentClient { get; } - public RawPackageMetadataClient MetadataClient { get; } - public RawSearchClient SearchClient { get; } - public RawAutocompleteClient AutocompleteClient { get; } - public RawCatalogClient CatalogClient { get; } - } -} + public RawServiceIndexClient ServiceIndexClient { get; } + public RawPackageContentClient ContentClient { get; } + public RawPackageMetadataClient MetadataClient { get; } + public RawSearchClient SearchClient { get; } + public RawAutocompleteClient AutocompleteClient { get; } + public RawCatalogClient CatalogClient { get; } +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Support/RecordingHttpMessageHandler.cs b/tests/BaGet.Protocol.Tests/Support/RecordingHttpMessageHandler.cs index 96104a12d..0965b9894 100644 --- a/tests/BaGet.Protocol.Tests/Support/RecordingHttpMessageHandler.cs +++ b/tests/BaGet.Protocol.Tests/Support/RecordingHttpMessageHandler.cs @@ -5,52 +5,51 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +/// +/// A handler that records the requests it receives and always replies with +/// the same payload. Use this to assert the URL a client asked for, instead +/// of the response it got back. +/// +public class RecordingHttpMessageHandler : HttpMessageHandler { + private readonly string _content; + private readonly List _requests = new List(); + + public RecordingHttpMessageHandler(string content = "{}") + { + _content = content ?? throw new ArgumentNullException(nameof(content)); + } + /// - /// A handler that records the requests it receives and always replies with - /// the same payload. Use this to assert the URL a client asked for, instead - /// of the response it got back. + /// The URLs that were requested, in order. /// - public class RecordingHttpMessageHandler : HttpMessageHandler + public IReadOnlyList Requests { - private readonly string _content; - private readonly List _requests = new List(); - - public RecordingHttpMessageHandler(string content = "{}") + get { - _content = content ?? throw new ArgumentNullException(nameof(content)); - } - - /// - /// The URLs that were requested, in order. - /// - public IReadOnlyList Requests - { - get + lock (_requests) { - lock (_requests) - { - return _requests.ToArray(); - } + return _requests.ToArray(); } } + } - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + lock (_requests) { - lock (_requests) - { - _requests.Add(request.RequestUri); - } - - return Task.FromResult(new HttpResponseMessage - { - RequestMessage = request, - StatusCode = HttpStatusCode.OK, - Content = new StringContent(_content, encoding: null, mediaType: "application/json"), - }); + _requests.Add(request.RequestUri); } + + return Task.FromResult(new HttpResponseMessage + { + RequestMessage = request, + StatusCode = HttpStatusCode.OK, + Content = new StringContent(_content, encoding: null, mediaType: "application/json"), + }); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Support/TestDataHttpMessageHandler.cs b/tests/BaGet.Protocol.Tests/Support/TestDataHttpMessageHandler.cs index ec138825f..fdd2c1d78 100644 --- a/tests/BaGet.Protocol.Tests/Support/TestDataHttpMessageHandler.cs +++ b/tests/BaGet.Protocol.Tests/Support/TestDataHttpMessageHandler.cs @@ -5,84 +5,83 @@ using System.Threading; using System.Threading.Tasks; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +// Based off https://github.com/NuGet/NuGet.Services.Metadata/blob/0c69b9dd47e01125c22f72c1e27cf3cdafc65233/tests/NuGet.Protocol.Catalog.Tests/TestDataHttpMessageHandler.cs +public class TestDataHttpMessageHandler : HttpMessageHandler { - // Based off https://github.com/NuGet/NuGet.Services.Metadata/blob/0c69b9dd47e01125c22f72c1e27cf3cdafc65233/tests/NuGet.Protocol.Catalog.Tests/TestDataHttpMessageHandler.cs - public class TestDataHttpMessageHandler : HttpMessageHandler + private static readonly Dictionary> UrlToGetContent = new Dictionary> { - private static readonly Dictionary> UrlToGetContent = new Dictionary> - { - { TestData.ServiceIndexUrl, () => TestData.ServiceIndex }, + { TestData.ServiceIndexUrl, () => TestData.ServiceIndex }, - { TestData.CatalogIndexUrl, () => TestData.CatalogIndex }, - { TestData.CatalogPageUrl, () => TestData.CatalogPage }, - { TestData.PackageDeleteCatalogLeafUrl, () => TestData.PackageDeleteCatalogLeaf }, - { TestData.PackageDetailsCatalogLeafUrl, () => TestData.PackageDetailsCatalogLeaf }, - //{ TestData.CatalogLeafInvalidDependencyVersionRangeUrl, () => TestData.CatalogLeafInvalidDependencyVersionRange }, + { TestData.CatalogIndexUrl, () => TestData.CatalogIndex }, + { TestData.CatalogPageUrl, () => TestData.CatalogPage }, + { TestData.PackageDeleteCatalogLeafUrl, () => TestData.PackageDeleteCatalogLeaf }, + { TestData.PackageDetailsCatalogLeafUrl, () => TestData.PackageDetailsCatalogLeaf }, + //{ TestData.CatalogLeafInvalidDependencyVersionRangeUrl, () => TestData.CatalogLeafInvalidDependencyVersionRange }, - { TestData.RegistrationIndexInlinedItemsUrl, () => TestData.RegistrationIndexInlinedItems }, - { TestData.RegistrationIndexPagedItemsUrl, () => TestData.RegistrationIndexPagedItems }, - { TestData.RegistrationLeafUnlistedUrl, () => TestData.RegistrationLeafUnlisted }, - { TestData.RegistrationLeafListedUrl, () => TestData.RegistrationLeafListed }, - { TestData.RegistrationPageUrl, () => TestData.RegistrationPage }, - { TestData.RegistrationPageFirstUrl, () => TestData.RegistrationPageFirst }, - { TestData.RegistrationPageDeprecatedUrl, () => TestData.RegistrationPageDeprecated }, + { TestData.RegistrationIndexInlinedItemsUrl, () => TestData.RegistrationIndexInlinedItems }, + { TestData.RegistrationIndexPagedItemsUrl, () => TestData.RegistrationIndexPagedItems }, + { TestData.RegistrationLeafUnlistedUrl, () => TestData.RegistrationLeafUnlisted }, + { TestData.RegistrationLeafListedUrl, () => TestData.RegistrationLeafListed }, + { TestData.RegistrationPageUrl, () => TestData.RegistrationPage }, + { TestData.RegistrationPageFirstUrl, () => TestData.RegistrationPageFirst }, + { TestData.RegistrationPageDeprecatedUrl, () => TestData.RegistrationPageDeprecated }, - { TestData.PackageContentVersionListUrl, () => TestData.PackageContentVersionList }, - { TestData.PagedPackageContentVersionListUrl, () => TestData.PagedPackageContentVersionList }, - { TestData.PackageContentNupkgUrl, () => TestData.PackageContentNupkg }, - { TestData.PackageContentNuspecUrl, () => TestData.PackageContentNuspec }, + { TestData.PackageContentVersionListUrl, () => TestData.PackageContentVersionList }, + { TestData.PagedPackageContentVersionListUrl, () => TestData.PagedPackageContentVersionList }, + { TestData.PackageContentNupkgUrl, () => TestData.PackageContentNupkg }, + { TestData.PackageContentNuspecUrl, () => TestData.PackageContentNuspec }, - { TestData.DefaultSearchUrl, () => TestData.DefaultSearch }, - { TestData.DefaultAutocompleteUrl, () => TestData.DefaultAutocomplete }, - { TestData.AutocompleteVersionsUrl, () => TestData.AutocompleteVersions }, - }; + { TestData.DefaultSearchUrl, () => TestData.DefaultSearch }, + { TestData.DefaultAutocompleteUrl, () => TestData.DefaultAutocomplete }, + { TestData.AutocompleteVersionsUrl, () => TestData.AutocompleteVersions }, + }; - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - return Task.FromResult(Send(request)); - } + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return Task.FromResult(Send(request)); + } - private HttpResponseMessage Send(HttpRequestMessage request) + private HttpResponseMessage Send(HttpRequestMessage request) + { + Func getContent; + if (request.Method != HttpMethod.Get + || !UrlToGetContent.TryGetValue(request.RequestUri.AbsoluteUri, out getContent)) { - Func getContent; - if (request.Method != HttpMethod.Get - || !UrlToGetContent.TryGetValue(request.RequestUri.AbsoluteUri, out getContent)) - { - return new HttpResponseMessage - { - RequestMessage = request, - StatusCode = HttpStatusCode.NotFound, - Content = new StringContent(string.Empty), - }; - } - return new HttpResponseMessage { RequestMessage = request, - StatusCode = HttpStatusCode.OK, - Content = new StringContent( - getContent(), - encoding: null, - mediaType: MediaTypeFor(request.RequestUri)), + StatusCode = HttpStatusCode.NotFound, + Content = new StringContent(string.Empty), }; } - private static string MediaTypeFor(Uri requestUri) + return new HttpResponseMessage { - var path = requestUri.AbsolutePath; + RequestMessage = request, + StatusCode = HttpStatusCode.OK, + Content = new StringContent( + getContent(), + encoding: null, + mediaType: MediaTypeFor(request.RequestUri)), + }; + } - if (path.EndsWith(".nupkg", StringComparison.OrdinalIgnoreCase)) - { - return "application/octet-stream"; - } + private static string MediaTypeFor(Uri requestUri) + { + var path = requestUri.AbsolutePath; - if (path.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase)) - { - return "application/xml"; - } + if (path.EndsWith(".nupkg", StringComparison.OrdinalIgnoreCase)) + { + return "application/octet-stream"; + } - return "application/json"; + if (path.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase)) + { + return "application/xml"; } + + return "application/json"; } -} +} \ No newline at end of file diff --git a/tests/BaGet.Protocol.Tests/Support/TestQueryString.cs b/tests/BaGet.Protocol.Tests/Support/TestQueryString.cs index 4ba0a7014..d7fab8ffc 100644 --- a/tests/BaGet.Protocol.Tests/Support/TestQueryString.cs +++ b/tests/BaGet.Protocol.Tests/Support/TestQueryString.cs @@ -1,43 +1,42 @@ using System; using System.Collections.Generic; -namespace BaGet.Protocol.Tests +namespace BaGet.Protocol.Tests; + +/// +/// Parses a request URL's query string so tests can assert the parameters +/// a client sent without depending on their order. +/// +public static class TestQueryString { - /// - /// Parses a request URL's query string so tests can assert the parameters - /// a client sent without depending on their order. - /// - public static class TestQueryString + public static IReadOnlyDictionary Parse(Uri url) { - public static IReadOnlyDictionary Parse(Uri url) - { - if (url == null) throw new ArgumentNullException(nameof(url)); - - var result = new Dictionary(StringComparer.Ordinal); - var query = url.Query; + if (url == null) throw new ArgumentNullException(nameof(url)); - if (query.StartsWith("?", StringComparison.Ordinal)) - { - query = query.Substring(1); - } + var result = new Dictionary(StringComparer.Ordinal); + var query = url.Query; - if (query.Length == 0) - { - return result; - } + if (query.StartsWith("?", StringComparison.Ordinal)) + { + query = query.Substring(1); + } - foreach (var pair in query.Split('&')) - { - if (pair.Length == 0) continue; + if (query.Length == 0) + { + return result; + } - var separator = pair.IndexOf('='); - var name = separator < 0 ? pair : pair.Substring(0, separator); - var value = separator < 0 ? string.Empty : pair.Substring(separator + 1); + foreach (var pair in query.Split('&')) + { + if (pair.Length == 0) continue; - result[Uri.UnescapeDataString(name)] = Uri.UnescapeDataString(value); - } + var separator = pair.IndexOf('='); + var name = separator < 0 ? pair : pair.Substring(0, separator); + var value = separator < 0 ? string.Empty : pair.Substring(separator + 1); - return result; + result[Uri.UnescapeDataString(name)] = Uri.UnescapeDataString(value); } + + return result; } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/AccountsDisabledTests.cs b/tests/BaGet.Tests/AccountsDisabledTests.cs index 11d34cd7f..b1b55a76b 100644 --- a/tests/BaGet.Tests/AccountsDisabledTests.cs +++ b/tests/BaGet.Tests/AccountsDisabledTests.cs @@ -5,46 +5,45 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Accounts are off by default, and an upgraded server must not grow account pages. +/// +public class AccountsDisabledTests : IDisposable { - /// - /// Accounts are off by default, and an upgraded server must not grow account pages. - /// - public class AccountsDisabledTests : IDisposable + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public AccountsDisabledTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output); + _client = _app.CreateClient(); + } + + [Theory] + [InlineData("account/login")] + [InlineData("account/register")] + [InlineData("account/logout")] + [InlineData("account/apikeys")] + public async Task AccountPagesAreNotFound(string url) + { + using var response = await _client.GetAsync(url); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task TheLayoutHasNoSignInLink() + { + var html = await _client.GetStringAsync("upload"); + + Assert.DoesNotContain("account/login", html); + } + + public void Dispose() { - private readonly BaGetApplication _app; - private readonly HttpClient _client; - - public AccountsDisabledTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); - _client = _app.CreateClient(); - } - - [Theory] - [InlineData("account/login")] - [InlineData("account/register")] - [InlineData("account/logout")] - [InlineData("account/apikeys")] - public async Task AccountPagesAreNotFound(string url) - { - using var response = await _client.GetAsync(url); - - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } - - [Fact] - public async Task TheLayoutHasNoSignInLink() - { - var html = await _client.GetStringAsync("upload"); - - Assert.DoesNotContain("account/login", html); - } - - public void Dispose() - { - _app.Dispose(); - _client.Dispose(); - } + _app.Dispose(); + _client.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/AccountsIntegrationTests.cs b/tests/BaGet.Tests/AccountsIntegrationTests.cs index 3ceca3d4c..1ae5b89dc 100644 --- a/tests/BaGet.Tests/AccountsIntegrationTests.cs +++ b/tests/BaGet.Tests/AccountsIntegrationTests.cs @@ -13,299 +13,298 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Accounts enabled on a closed server: the global key is the superuser, and users' +/// keys act within their scopes, their globs and the packages they own. +/// +public class AccountsIntegrationTests : IDisposable { - /// - /// Accounts enabled on a closed server: the global key is the superuser, and users' - /// keys act within their scopes, their globs and the packages they own. - /// - public class AccountsIntegrationTests : IDisposable - { - private const string GlobalKey = "global-key"; + private const string GlobalKey = "global-key"; - private readonly BaGetApplication _app; - private readonly HttpClient _client; + private readonly BaGetApplication _app; + private readonly HttpClient _client; - // Keeps cookies and does not follow redirects, like a browser seen one hop at a time. - private readonly HttpClient _browser; + // Keeps cookies and does not follow redirects, like a browser seen one hop at a time. + private readonly HttpClient _browser; - public AccountsIntegrationTests(ITestOutputHelper output) + public AccountsIntegrationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "ApiKey", GlobalKey }, - { "Accounts:Enabled", "true" }, - }); - _client = _app.CreateClient(); - _browser = _app.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); - } + { "ApiKey", GlobalKey }, + { "Accounts:Enabled", "true" }, + }); + _client = _app.CreateClient(); + _browser = _app.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + } - [Fact] - public async Task TheGlobalKeyStillPushes() - { - Assert.Equal(HttpStatusCode.Created, await PushAsync("Legacy.Package", "1.0.0", GlobalKey)); - } + [Fact] + public async Task TheGlobalKeyStillPushes() + { + Assert.Equal(HttpStatusCode.Created, await PushAsync("Legacy.Package", "1.0.0", GlobalKey)); + } - [Fact] - public async Task AWrongKeyIsUnauthorized() - { - Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Any.Package", "1.0.0", "bgt_wrong")); - } + [Fact] + public async Task AWrongKeyIsUnauthorized() + { + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Any.Package", "1.0.0", "bgt_wrong")); + } - [Fact] - public async Task PushingANewIdMakesThePusherItsOwner() - { - var alice = await CreateUserAsync("alice"); - var key = await CreateKeyAsync(alice, ApiKeyScopes.Push); + [Fact] + public async Task PushingANewIdMakesThePusherItsOwner() + { + var alice = await CreateUserAsync("alice"); + var key = await CreateKeyAsync(alice, ApiKeyScopes.Push); - Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "1.0.0", key)); - Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "2.0.0", key)); + Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "1.0.0", key)); + Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "2.0.0", key)); - var owners = await WithServiceAsync>( - s => s.GetOwnersAsync("alice.package", CancellationToken.None)); - Assert.Equal("alice", Assert.Single(owners).OwnerName); - } + var owners = await WithServiceAsync>( + s => s.GetOwnersAsync("alice.package", CancellationToken.None)); + Assert.Equal("alice", Assert.Single(owners).OwnerName); + } - [Fact] - public async Task AnotherUserCannotPushToAnOwnedId() - { - var alice = await CreateUserAsync("alice"); - var bob = await CreateUserAsync("bob"); - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + [Fact] + public async Task AnotherUserCannotPushToAnOwnedId() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Alice.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Push))); - } + Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Alice.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Push))); + } - [Fact] - public async Task AnIdWithoutOwnersIsForTheGlobalKeyOnly() - { - // Pushed before accounts existed, so it has no owner and nobody may claim it. - await PushAsync("Legacy.Package", "1.0.0", GlobalKey); - var alice = await CreateUserAsync("alice"); + [Fact] + public async Task AnIdWithoutOwnersIsForTheGlobalKeyOnly() + { + // Pushed before accounts existed, so it has no owner and nobody may claim it. + await PushAsync("Legacy.Package", "1.0.0", GlobalKey); + var alice = await CreateUserAsync("alice"); - Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Legacy.Package", "2.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); - Assert.Equal(HttpStatusCode.Created, await PushAsync("Legacy.Package", "2.0.0", GlobalKey)); - } + Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Legacy.Package", "2.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); + Assert.Equal(HttpStatusCode.Created, await PushAsync("Legacy.Package", "2.0.0", GlobalKey)); + } - [Fact] - public async Task PushVersionCannotClaimANewId() - { - var alice = await CreateUserAsync("alice"); - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - var versionOnly = await CreateKeyAsync(alice, ApiKeyScopes.PushVersion); + [Fact] + public async Task PushVersionCannotClaimANewId() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + var versionOnly = await CreateKeyAsync(alice, ApiKeyScopes.PushVersion); - Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "2.0.0", versionOnly)); - Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Alice.Other", "1.0.0", versionOnly)); - } + Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "2.0.0", versionOnly)); + Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Alice.Other", "1.0.0", versionOnly)); + } - [Fact] - public async Task AKeyOnlyActsWithinItsGlob() - { - var alice = await CreateUserAsync("alice"); - var key = await CreateKeyAsync(alice, ApiKeyScopes.Push, glob: "Alice.*"); + [Fact] + public async Task AKeyOnlyActsWithinItsGlob() + { + var alice = await CreateUserAsync("alice"); + var key = await CreateKeyAsync(alice, ApiKeyScopes.Push, glob: "Alice.*"); - Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "1.0.0", key)); - Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Elsewhere.Package", "1.0.0", key)); - } + Assert.Equal(HttpStatusCode.Created, await PushAsync("Alice.Package", "1.0.0", key)); + Assert.Equal(HttpStatusCode.Forbidden, await PushAsync("Elsewhere.Package", "1.0.0", key)); + } - [Fact] - public async Task AnExpiredKeyIsUnauthorized() - { - var alice = await CreateUserAsync("alice"); - // The test host's clock is frozen at 2020-01-01. - var key = await CreateKeyAsync(alice, ApiKeyScopes.Push, expires: new DateTime(2019, 12, 31, 0, 0, 0, DateTimeKind.Utc)); + [Fact] + public async Task AnExpiredKeyIsUnauthorized() + { + var alice = await CreateUserAsync("alice"); + // The test host's clock is frozen at 2020-01-01. + var key = await CreateKeyAsync(alice, ApiKeyScopes.Push, expires: new DateTime(2019, 12, 31, 0, 0, 0, DateTimeKind.Utc)); - Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "1.0.0", key)); - } + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "1.0.0", key)); + } - [Fact] - public async Task ARevokedKeyIsUnauthorized() + [Fact] + public async Task ARevokedKeyIsUnauthorized() + { + var alice = await CreateUserAsync("alice"); + var key = await CreateKeyAsync(alice, ApiKeyScopes.Push); + + await WithServiceAsync(async s => { - var alice = await CreateUserAsync("alice"); - var key = await CreateKeyAsync(alice, ApiKeyScopes.Push); + var stored = Assert.Single(await s.ListAsync(alice.Id, CancellationToken.None)); + return await s.RevokeAsync(alice.Id, stored.Key, CancellationToken.None); + }); - await WithServiceAsync(async s => - { - var stored = Assert.Single(await s.ListAsync(alice.Id, CancellationToken.None)); - return await s.RevokeAsync(alice.Id, stored.Key, CancellationToken.None); - }); + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "1.0.0", key)); + } - Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "1.0.0", key)); - } + [Fact] + public async Task UnlistingNeedsTheUnlistScopeAndOwnership() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - [Fact] - public async Task UnlistingNeedsTheUnlistScopeAndOwnership() - { - var alice = await CreateUserAsync("alice"); - var bob = await CreateUserAsync("bob"); - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + Assert.Equal(HttpStatusCode.Forbidden, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); + Assert.Equal(HttpStatusCode.Forbidden, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Unlist))); + Assert.Equal(HttpStatusCode.NoContent, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Unlist))); + } - Assert.Equal(HttpStatusCode.Forbidden, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); - Assert.Equal(HttpStatusCode.Forbidden, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Unlist))); - Assert.Equal(HttpStatusCode.NoContent, await DeleteAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Unlist))); - } + [Fact] + public async Task AnOrganizationMemberActsForTheOrganizationsPackages() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); + await PushAsync("Contoso.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - [Fact] - public async Task AnOrganizationMemberActsForTheOrganizationsPackages() + await WithServiceAsync(async s => { - var alice = await CreateUserAsync("alice"); - var bob = await CreateUserAsync("bob"); - await PushAsync("Contoso.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - - await WithServiceAsync(async s => - { - Assert.True(await s.CreateOrganizationAsync("contoso", alice.Id, CancellationToken.None)); - Assert.True(await s.AddMemberAsync("contoso", bob.Id, isAdmin: false, CancellationToken.None)); - Assert.Equal(OwnerChangeResult.Success, await s.AddOwnerAsync("Contoso.Package", "contoso", CancellationToken.None)); - return true; - }); - - Assert.Equal(HttpStatusCode.Created, await PushAsync("Contoso.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.PushVersion))); - } + Assert.True(await s.CreateOrganizationAsync("contoso", alice.Id, CancellationToken.None)); + Assert.True(await s.AddMemberAsync("contoso", bob.Id, isAdmin: false, CancellationToken.None)); + Assert.Equal(OwnerChangeResult.Success, await s.AddOwnerAsync("Contoso.Package", "contoso", CancellationToken.None)); + return true; + }); - [Fact] - public async Task AnOrganizationCannotTakeAUsersName() - { - var alice = await CreateUserAsync("alice"); + Assert.Equal(HttpStatusCode.Created, await PushAsync("Contoso.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.PushVersion))); + } - Assert.False(await WithServiceAsync( - s => s.CreateOrganizationAsync("Alice", alice.Id, CancellationToken.None))); - } + [Fact] + public async Task AnOrganizationCannotTakeAUsersName() + { + var alice = await CreateUserAsync("alice"); - [Fact] - public async Task ThePackagesLastOwnerCannotBeRemoved() - { - var alice = await CreateUserAsync("alice"); - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + Assert.False(await WithServiceAsync( + s => s.CreateOrganizationAsync("Alice", alice.Id, CancellationToken.None))); + } - Assert.Equal(OwnerChangeResult.LastOwner, await WithServiceAsync( - s => s.RemoveOwnerAsync("Alice.Package", "alice", CancellationToken.None))); - } + [Fact] + public async Task ThePackagesLastOwnerCannotBeRemoved() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - [Fact] - public async Task SearchReportsOwnersAndVerification() + Assert.Equal(OwnerChangeResult.LastOwner, await WithServiceAsync( + s => s.RemoveOwnerAsync("Alice.Package", "alice", CancellationToken.None))); + } + + [Fact] + public async Task SearchReportsOwnersAndVerification() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + await PushAsync("Legacy.Package", "1.0.0", GlobalKey); + await WithServiceAsync( + s => s.SetVerifiedAsync("Alice.Package", verified: true, CancellationToken.None)); + + using var search = System.Text.Json.JsonDocument.Parse(await _client.GetStringAsync("v3/search")); + var results = search.RootElement.GetProperty("data").EnumerateArray() + .ToDictionary(r => r.GetProperty("id").GetString()); + + Assert.Equal("alice", results["Alice.Package"].GetProperty("owners")[0].GetString()); + Assert.True(results["Alice.Package"].GetProperty("verified").GetBoolean()); + Assert.False(results["Legacy.Package"].TryGetProperty("owners", out _)); + Assert.False(results["Legacy.Package"].TryGetProperty("verified", out _)); + } + + [Fact] + public async Task ARegisteredUserCanCreateAKeyThatPushes() + { + // The whole browser flow: register, then create a key on the API keys page. + var register = await GetFormAsync("account/register"); + using (var response = await PostFormAsync("account/register", register, new Dictionary + { + { "UserName", "carol" }, + { "Password", "Passw0rd!" }, + { "ConfirmPassword", "Passw0rd!" }, + })) { - var alice = await CreateUserAsync("alice"); - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - await PushAsync("Legacy.Package", "1.0.0", GlobalKey); - await WithServiceAsync( - s => s.SetVerifiedAsync("Alice.Package", verified: true, CancellationToken.None)); - - using var search = System.Text.Json.JsonDocument.Parse(await _client.GetStringAsync("v3/search")); - var results = search.RootElement.GetProperty("data").EnumerateArray() - .ToDictionary(r => r.GetProperty("id").GetString()); - - Assert.Equal("alice", results["Alice.Package"].GetProperty("owners")[0].GetString()); - Assert.True(results["Alice.Package"].GetProperty("verified").GetBoolean()); - Assert.False(results["Legacy.Package"].TryGetProperty("owners", out _)); - Assert.False(results["Legacy.Package"].TryGetProperty("verified", out _)); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } - [Fact] - public async Task ARegisteredUserCanCreateAKeyThatPushes() + var keys = await GetFormAsync("account/apikeys"); + string key; + using (var response = await PostFormAsync("account/apikeys?handler=Create", keys, new Dictionary + { + { "Description", "ci" }, + { "Scopes", ApiKeyScopes.Push }, + { "PackageGlobPattern", "*" }, + { "ExpiresInDays", "30" }, + })) { - // The whole browser flow: register, then create a key on the API keys page. - var register = await GetFormAsync("account/register"); - using (var response = await PostFormAsync("account/register", register, new Dictionary - { - { "UserName", "carol" }, - { "Password", "Passw0rd!" }, - { "ConfirmPassword", "Passw0rd!" }, - })) - { - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - } - - var keys = await GetFormAsync("account/apikeys"); - string key; - using (var response = await PostFormAsync("account/apikeys?handler=Create", keys, new Dictionary - { - { "Description", "ci" }, - { "Scopes", ApiKeyScopes.Push }, - { "PackageGlobPattern", "*" }, - { "ExpiresInDays", "30" }, - })) - { - var html = await response.Content.ReadAsStringAsync(); - key = Regex.Match(html, "
([^<]+)
").Groups[1].Value; - } - - Assert.StartsWith("bgt_", key); - Assert.Equal(HttpStatusCode.Created, await PushAsync("Carol.Package", "1.0.0", key)); + var html = await response.Content.ReadAsStringAsync(); + key = Regex.Match(html, "
([^<]+)
").Groups[1].Value; } - [Fact] - public async Task TheApiKeysPageNeedsASignedInUser() - { - using var response = await _browser.GetAsync("account/apikeys"); + Assert.StartsWith("bgt_", key); + Assert.Equal(HttpStatusCode.Created, await PushAsync("Carol.Package", "1.0.0", key)); + } - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Contains("/account/login", response.Headers.Location.ToString()); - } + [Fact] + public async Task TheApiKeysPageNeedsASignedInUser() + { + using var response = await _browser.GetAsync("account/apikeys"); - private async Task PushAsync(string id, string version, string apiKey) - { - using var package = TestPackages.Build(id, version); - using var request = TestPackages.PushRequest(package, apiKey); - using var response = await _client.SendAsync(request); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/account/login", response.Headers.Location.ToString()); + } - return response.StatusCode; - } + private async Task PushAsync(string id, string version, string apiKey) + { + using var package = TestPackages.Build(id, version); + using var request = TestPackages.PushRequest(package, apiKey); + using var response = await _client.SendAsync(request); - private async Task DeleteAsync(string id, string version, string apiKey) - { - using var request = new HttpRequestMessage(HttpMethod.Delete, $"api/v2/package/{id}/{version}"); - request.Headers.Add("X-NuGet-ApiKey", apiKey); - using var response = await _client.SendAsync(request); + return response.StatusCode; + } - return response.StatusCode; - } + private async Task DeleteAsync(string id, string version, string apiKey) + { + using var request = new HttpRequestMessage(HttpMethod.Delete, $"api/v2/package/{id}/{version}"); + request.Headers.Add("X-NuGet-ApiKey", apiKey); + using var response = await _client.SendAsync(request); - private async Task CreateUserAsync(string name) - { - using var scope = _app.Services.CreateScope(); - var users = scope.ServiceProvider.GetRequiredService>(); - var user = new BaGetUser { UserName = name }; + return response.StatusCode; + } - var result = await users.CreateAsync(user, "Passw0rd!"); - Assert.True(result.Succeeded, string.Join(" ", result.Errors.Select(e => e.Description))); + private async Task CreateUserAsync(string name) + { + using var scope = _app.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + var user = new BaGetUser { UserName = name }; - return user; - } + var result = await users.CreateAsync(user, "Passw0rd!"); + Assert.True(result.Succeeded, string.Join(" ", result.Errors.Select(e => e.Description))); - private Task CreateKeyAsync(BaGetUser user, string scope, string glob = "*", DateTime? expires = null) - => WithServiceAsync( - s => s.CreateAsync(user.Id, "test", new[] { scope }, glob, expires, CancellationToken.None)); + return user; + } - private async Task WithServiceAsync(Func> action) - { - using var scope = _app.Services.CreateScope(); + private Task CreateKeyAsync(BaGetUser user, string scope, string glob = "*", DateTime? expires = null) + => WithServiceAsync( + s => s.CreateAsync(user.Id, "test", new[] { scope }, glob, expires, CancellationToken.None)); - return await action(scope.ServiceProvider.GetRequiredService()); - } + private async Task WithServiceAsync(Func> action) + { + using var scope = _app.Services.CreateScope(); - private async Task GetFormAsync(string url) - { - using var response = await _browser.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return await action(scope.ServiceProvider.GetRequiredService()); + } - var html = await response.Content.ReadAsStringAsync(); + private async Task GetFormAsync(string url) + { + using var response = await _browser.GetAsync(url); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); - return Regex.Match(html, "name=\"__RequestVerificationToken\" type=\"hidden\" value=\"([^\"]+)\"").Groups[1].Value; - } + var html = await response.Content.ReadAsStringAsync(); - private async Task PostFormAsync(string url, string token, Dictionary fields) - { - fields["__RequestVerificationToken"] = token; + return Regex.Match(html, "name=\"__RequestVerificationToken\" type=\"hidden\" value=\"([^\"]+)\"").Groups[1].Value; + } - return await _browser.PostAsync(url, new FormUrlEncodedContent(fields)); - } + private async Task PostFormAsync(string url, string token, Dictionary fields) + { + fields["__RequestVerificationToken"] = token; - public void Dispose() - { - _app.Dispose(); - _client.Dispose(); - _browser.Dispose(); - } + return await _browser.PostAsync(url, new FormUrlEncodedContent(fields)); + } + + public void Dispose() + { + _app.Dispose(); + _client.Dispose(); + _browser.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/AccountsWithoutGlobalKeyTests.cs b/tests/BaGet.Tests/AccountsWithoutGlobalKeyTests.cs index 5fe1eba08..a1b24fa10 100644 --- a/tests/BaGet.Tests/AccountsWithoutGlobalKeyTests.cs +++ b/tests/BaGet.Tests/AccountsWithoutGlobalKeyTests.cs @@ -11,130 +11,129 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Accounts enabled with no global API key configured. Enabling accounts is asking for +/// ownership to decide who may push what, so an unset global key must mean "there is no +/// global key" - not "every caller is the superuser", which would bypass ownership +/// entirely. +/// +public class AccountsWithoutGlobalKeyTests : IDisposable { - /// - /// Accounts enabled with no global API key configured. Enabling accounts is asking for - /// ownership to decide who may push what, so an unset global key must mean "there is no - /// global key" - not "every caller is the superuser", which would bypass ownership - /// entirely. - /// - public class AccountsWithoutGlobalKeyTests : IDisposable - { - private readonly BaGetApplication _app; - private readonly HttpClient _client; + private readonly BaGetApplication _app; + private readonly HttpClient _client; - public AccountsWithoutGlobalKeyTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - // As src/BaGet/appsettings.json ships it, with accounts turned on. - { "ApiKey", "" }, - { "Accounts:Enabled", "true" }, - }); - _client = _app.CreateClient(); - } - - [Fact] - public async Task APushWithNoApiKeyIsRefused() + public AccountsWithoutGlobalKeyTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary { - Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Anonymous.Package", "1.0.0", apiKey: null)); - } + // As src/BaGet/appsettings.json ships it, with accounts turned on. + { "ApiKey", "" }, + { "Accounts:Enabled", "true" }, + }); + _client = _app.CreateClient(); + } - [Fact] - public async Task APushWithAnUnknownApiKeyIsRefused() - { - Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Anonymous.Package", "1.0.0", "not-a-key")); - } + [Fact] + public async Task APushWithNoApiKeyIsRefused() + { + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Anonymous.Package", "1.0.0", apiKey: null)); + } - [Fact] - public async Task AUsersOwnKeyStillPushes() - { - var alice = await CreateUserAsync("alice"); + [Fact] + public async Task APushWithAnUnknownApiKeyIsRefused() + { + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Anonymous.Package", "1.0.0", "not-a-key")); + } - Assert.Equal( - HttpStatusCode.Created, - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); - } + [Fact] + public async Task AUsersOwnKeyStillPushes() + { + var alice = await CreateUserAsync("alice"); - [Fact] - public async Task OwnershipStillGatesAnIdSomeoneElseOwns() - { - var alice = await CreateUserAsync("alice"); - var bob = await CreateUserAsync("bob"); + Assert.Equal( + HttpStatusCode.Created, + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); + } - Assert.Equal( - HttpStatusCode.Created, - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); + [Fact] + public async Task OwnershipStillGatesAnIdSomeoneElseOwns() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); - // Bob's own key is refused, and so is no key at all: without the second check a - // keyless push would be the superuser and would overwrite Alice's ID. - Assert.Equal( - HttpStatusCode.Forbidden, - await PushAsync("Alice.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Push))); - Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "3.0.0", apiKey: null)); + Assert.Equal( + HttpStatusCode.Created, + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push))); - Assert.Equal(new[] { "alice" }, await OwnersAsync("Alice.Package")); - } + // Bob's own key is refused, and so is no key at all: without the second check a + // keyless push would be the superuser and would overwrite Alice's ID. + Assert.Equal( + HttpStatusCode.Forbidden, + await PushAsync("Alice.Package", "2.0.0", await CreateKeyAsync(bob, ApiKeyScopes.Push))); + Assert.Equal(HttpStatusCode.Unauthorized, await PushAsync("Alice.Package", "3.0.0", apiKey: null)); - [Fact] - public async Task ADeleteWithNoApiKeyIsRefused() - { - var alice = await CreateUserAsync("alice"); - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + Assert.Equal(new[] { "alice" }, await OwnersAsync("Alice.Package")); + } - using var request = new HttpRequestMessage(HttpMethod.Delete, "api/v2/package/Alice.Package/1.0.0"); - using var response = await _client.SendAsync(request); + [Fact] + public async Task ADeleteWithNoApiKeyIsRefused() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } + using var request = new HttpRequestMessage(HttpMethod.Delete, "api/v2/package/Alice.Package/1.0.0"); + using var response = await _client.SendAsync(request); - private async Task PushAsync(string id, string version, string apiKey) - { - using var package = TestPackages.Build(id, version); - using var request = TestPackages.PushRequest(package, apiKey); - using var response = await _client.SendAsync(request); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } - return response.StatusCode; - } + private async Task PushAsync(string id, string version, string apiKey) + { + using var package = TestPackages.Build(id, version); + using var request = TestPackages.PushRequest(package, apiKey); + using var response = await _client.SendAsync(request); - private async Task> OwnersAsync(string id) - { - using var scope = _app.Services.CreateScope(); - var ownership = scope.ServiceProvider.GetRequiredService(); + return response.StatusCode; + } - var owners = await ownership.GetOwnersAsync(id, CancellationToken.None); - var names = new List(); - foreach (var owner in owners) names.Add(owner.OwnerName); + private async Task> OwnersAsync(string id) + { + using var scope = _app.Services.CreateScope(); + var ownership = scope.ServiceProvider.GetRequiredService(); - return names; - } + var owners = await ownership.GetOwnersAsync(id, CancellationToken.None); + var names = new List(); + foreach (var owner in owners) names.Add(owner.OwnerName); - private async Task CreateUserAsync(string userName) - { - using var scope = _app.Services.CreateScope(); - var users = scope.ServiceProvider.GetRequiredService>(); + return names; + } - var user = new BaGetUser { UserName = userName, Created = DateTime.UtcNow }; - var result = await users.CreateAsync(user, "Passw0rd!"); + private async Task CreateUserAsync(string userName) + { + using var scope = _app.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); - Assert.True(result.Succeeded, string.Join(", ", result.Errors)); + var user = new BaGetUser { UserName = userName, Created = DateTime.UtcNow }; + var result = await users.CreateAsync(user, "Passw0rd!"); - return user; - } + Assert.True(result.Succeeded, string.Join(", ", result.Errors)); - private async Task CreateKeyAsync(BaGetUser user, string scope) - { - using var serviceScope = _app.Services.CreateScope(); - var keys = serviceScope.ServiceProvider.GetRequiredService(); + return user; + } + + private async Task CreateKeyAsync(BaGetUser user, string scope) + { + using var serviceScope = _app.Services.CreateScope(); + var keys = serviceScope.ServiceProvider.GetRequiredService(); - return await keys.CreateAsync(user.Id, "test", new[] { scope }, "*", expires: null, CancellationToken.None); - } + return await keys.CreateAsync(user.Id, "test", new[] { scope }, "*", expires: null, CancellationToken.None); + } - public void Dispose() - { - _client.Dispose(); - _app.Dispose(); - } + public void Dispose() + { + _client.Dispose(); + _app.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/AllowedHostsIntegrationTests.cs b/tests/BaGet.Tests/AllowedHostsIntegrationTests.cs index 81db5ccaa..33ec8fb4a 100644 --- a/tests/BaGet.Tests/AllowedHostsIntegrationTests.cs +++ b/tests/BaGet.Tests/AllowedHostsIntegrationTests.cs @@ -12,192 +12,191 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Every absolute URL BaGet advertises is built from the incoming request's "Host" +/// header, so a forged host decides where clients are sent. The host must therefore +/// be checked against the configured allow-list before a request reaches a handler, +/// and the default must stay permissive: BaGet is routinely run behind a reverse +/// proxy on an arbitrary host name. +/// +public class AllowedHostsIntegrationTests { - /// - /// Every absolute URL BaGet advertises is built from the incoming request's "Host" - /// header, so a forged host decides where clients are sent. The host must therefore - /// be checked against the configured allow-list before a request reaches a handler, - /// and the default must stay permissive: BaGet is routinely run behind a reverse - /// proxy on an arbitrary host name. - /// - public class AllowedHostsIntegrationTests - { - private readonly ITestOutputHelper _output; + private readonly ITestOutputHelper _output; - public AllowedHostsIntegrationTests(ITestOutputHelper output) - { - _output = output; - } + public AllowedHostsIntegrationTests(ITestOutputHelper output) + { + _output = output; + } - [Fact] - public async Task ServesAnAllowedHost() - { - using var app = CreateApplication("baget.example.com"); - using var client = app.CreateDefaultClient(); + [Fact] + public async Task ServesAnAllowedHost() + { + using var app = CreateApplication("baget.example.com"); + using var client = app.CreateDefaultClient(); - using var response = await client.GetAsync("http://baget.example.com/v3/index.json"); + using var response = await client.GetAsync("http://baget.example.com/v3/index.json"); - response.EnsureSuccessStatusCode(); - var content = JObject.Parse(await response.Content.ReadAsStringAsync()); + response.EnsureSuccessStatusCode(); + var content = JObject.Parse(await response.Content.ReadAsStringAsync()); - foreach (var resource in content["resources"]) - { - Assert.StartsWith( - "http://baget.example.com/", - resource["@id"].Value()); - } + foreach (var resource in content["resources"]) + { + Assert.StartsWith( + "http://baget.example.com/", + resource["@id"].Value()); } + } - [Fact] - public async Task RejectsAHostThatIsNotAllowed() - { - using var app = CreateApplication("baget.example.com"); - using var client = app.CreateDefaultClient(); + [Fact] + public async Task RejectsAHostThatIsNotAllowed() + { + using var app = CreateApplication("baget.example.com"); + using var client = app.CreateDefaultClient(); - using var response = await client.GetAsync("http://attacker.example.com/v3/index.json"); + using var response = await client.GetAsync("http://attacker.example.com/v3/index.json"); - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } - [Fact] - public async Task ServesAnyHostWhenNothingIsConfigured() - { - using var app = CreateApplication(allowedHosts: null); - using var client = app.CreateDefaultClient(); + [Fact] + public async Task ServesAnyHostWhenNothingIsConfigured() + { + using var app = CreateApplication(allowedHosts: null); + using var client = app.CreateDefaultClient(); - using var response = await client.GetAsync("http://anything.example.com/v3/index.json"); + using var response = await client.GetAsync("http://anything.example.com/v3/index.json"); - response.EnsureSuccessStatusCode(); - var content = JObject.Parse(await response.Content.ReadAsStringAsync()); + response.EnsureSuccessStatusCode(); + var content = JObject.Parse(await response.Content.ReadAsStringAsync()); - foreach (var resource in content["resources"]) - { - Assert.StartsWith( - "http://anything.example.com/", - resource["@id"].Value()); - } + foreach (var resource in content["resources"]) + { + Assert.StartsWith( + "http://anything.example.com/", + resource["@id"].Value()); } + } - [Fact] - public async Task ServesEveryHostOfAWhitespaceSeparatedList() - { - // A semicolon separated list is normally written with spaces after the - // separators. Those entries must not become unmatchable patterns. - using var app = CreateApplication("baget.example.com; cdn.example.com"); - using var client = app.CreateDefaultClient(); + [Fact] + public async Task ServesEveryHostOfAWhitespaceSeparatedList() + { + // A semicolon separated list is normally written with spaces after the + // separators. Those entries must not become unmatchable patterns. + using var app = CreateApplication("baget.example.com; cdn.example.com"); + using var client = app.CreateDefaultClient(); - using var allowed = await client.GetAsync("http://cdn.example.com/v3/index.json"); - using var rejected = await client.GetAsync("http://attacker.example.com/v3/index.json"); + using var allowed = await client.GetAsync("http://cdn.example.com/v3/index.json"); + using var rejected = await client.GetAsync("http://attacker.example.com/v3/index.json"); - allowed.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.BadRequest, rejected.StatusCode); - } + allowed.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.BadRequest, rejected.StatusCode); + } - [Fact] - public async Task RejectsAForgedHostWithoutTheHostBuilderDefaults() - { - // The default builder happens to add the host filtering middleware, but BaGet - // must not depend on it: a consumer of AddBaGetWebApplication may build its host - // with a slim or empty builder, which does not add it. With the builder's own - // copy removed, a rejection here can only come from BaGet's pipeline. - using var app = WithoutTheBuildersHostFiltering( - _output, - new Dictionary { { "AllowedHosts", "baget.example.com" } }); - using var client = app.CreateDefaultClient(); - - using var allowed = await client.GetAsync("http://baget.example.com/v3/index.json"); - using var rejected = await client.GetAsync("http://attacker.example.com/v3/index.json"); - - allowed.EnsureSuccessStatusCode(); - Assert.Equal(HttpStatusCode.BadRequest, rejected.StatusCode); - } + [Fact] + public async Task RejectsAForgedHostWithoutTheHostBuilderDefaults() + { + // The default builder happens to add the host filtering middleware, but BaGet + // must not depend on it: a consumer of AddBaGetWebApplication may build its host + // with a slim or empty builder, which does not add it. With the builder's own + // copy removed, a rejection here can only come from BaGet's pipeline. + using var app = WithoutTheBuildersHostFiltering( + _output, + new Dictionary { { "AllowedHosts", "baget.example.com" } }); + using var client = app.CreateDefaultClient(); + + using var allowed = await client.GetAsync("http://baget.example.com/v3/index.json"); + using var rejected = await client.GetAsync("http://attacker.example.com/v3/index.json"); + + allowed.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.BadRequest, rejected.StatusCode); + } - [Theory] - [InlineData(null, "*")] - [InlineData("", "*")] - [InlineData(" ", "*")] - [InlineData(";;", "*")] - [InlineData("*", "*")] - [InlineData("baget.example.com", "baget.example.com")] - [InlineData(" baget.example.com ", "baget.example.com")] - [InlineData("a.example.com; b.example.com", "a.example.com|b.example.com")] - [InlineData("a.example.com;;b.example.com", "a.example.com|b.example.com")] - [InlineData("a.example.com;A.EXAMPLE.COM", "a.example.com")] - [InlineData("*.example.com;example.com:8080", "*.example.com|example.com:8080")] - public void ParseAllowedHostsMapsConfiguredValues(string configured, string expected) - { - var hosts = ConfigureBaGetOptions.ParseAllowedHosts(configured); + [Theory] + [InlineData(null, "*")] + [InlineData("", "*")] + [InlineData(" ", "*")] + [InlineData(";;", "*")] + [InlineData("*", "*")] + [InlineData("baget.example.com", "baget.example.com")] + [InlineData(" baget.example.com ", "baget.example.com")] + [InlineData("a.example.com; b.example.com", "a.example.com|b.example.com")] + [InlineData("a.example.com;;b.example.com", "a.example.com|b.example.com")] + [InlineData("a.example.com;A.EXAMPLE.COM", "a.example.com")] + [InlineData("*.example.com;example.com:8080", "*.example.com|example.com:8080")] + public void ParseAllowedHostsMapsConfiguredValues(string configured, string expected) + { + var hosts = ConfigureBaGetOptions.ParseAllowedHosts(configured); - Assert.Equal(expected, string.Join("|", hosts)); - } + Assert.Equal(expected, string.Join("|", hosts)); + } - [Theory] - [InlineData(null, true)] - [InlineData("*", true)] - [InlineData("baget.example.com", false)] - public void EmptyHostsAreOnlyToleratedWhileFilteringIsDisabled( - string allowedHosts, - bool expected) - { - var configuration = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary - { - { nameof(BaGetOptions.AllowedHosts), allowedHosts }, - }) - .Build(); - var options = new HostFilteringOptions(); + [Theory] + [InlineData(null, true)] + [InlineData("*", true)] + [InlineData("baget.example.com", false)] + public void EmptyHostsAreOnlyToleratedWhileFilteringIsDisabled( + string allowedHosts, + bool expected) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + { nameof(BaGetOptions.AllowedHosts), allowedHosts }, + }) + .Build(); + var options = new HostFilteringOptions(); - new ConfigureBaGetOptions(configuration).Configure(options); + new ConfigureBaGetOptions(configuration).Configure(options); - Assert.Equal(expected, options.AllowEmptyHosts); - } + Assert.Equal(expected, options.AllowEmptyHosts); + } - private BaGetApplication CreateApplication(string allowedHosts) + private BaGetApplication CreateApplication(string allowedHosts) + { + var overrides = new Dictionary(); + if (allowedHosts != null) { - var overrides = new Dictionary(); - if (allowedHosts != null) + overrides["AllowedHosts"] = allowedHosts; + } + + return new BaGetApplication(_output, configOverrides: overrides); + } + + /// + /// The same application, with the host filtering that the default builder adds taken + /// away again, so that the only such middleware left is the one BaGet puts in its own + /// pipeline. + /// + /// + /// The builder contributes its host filtering through an + /// whose type is internal to ASP.NET Core, so the registration is matched by name. + /// Hosting the application on a builder without the defaults, which is what this test + /// used to do, is not open to it under the minimal hosting model: the pipeline is + /// built by the entry point, and a bare host builder would not run it at all. + /// + private static BaGetApplication WithoutTheBuildersHostFiltering( + ITestOutputHelper output, + Dictionary configOverrides) + { + return new BaGetApplication( + output, + configOverrides: configOverrides, + configureServices: services => { - overrides["AllowedHosts"] = allowedHosts; - } + var hostFiltering = services + .Where(service => + service.ServiceType == typeof(IStartupFilter) && + service.ImplementationType?.Name == "HostFilteringStartupFilter") + .ToList(); - return new BaGetApplication(_output, configOverrides: overrides); - } + Assert.NotEmpty(hostFiltering); - /// - /// The same application, with the host filtering that the default builder adds taken - /// away again, so that the only such middleware left is the one BaGet puts in its own - /// pipeline. - /// - /// - /// The builder contributes its host filtering through an - /// whose type is internal to ASP.NET Core, so the registration is matched by name. - /// Hosting the application on a builder without the defaults, which is what this test - /// used to do, is not open to it under the minimal hosting model: the pipeline is - /// built by the entry point, and a bare host builder would not run it at all. - /// - private static BaGetApplication WithoutTheBuildersHostFiltering( - ITestOutputHelper output, - Dictionary configOverrides) - { - return new BaGetApplication( - output, - configOverrides: configOverrides, - configureServices: services => + foreach (var service in hostFiltering) { - var hostFiltering = services - .Where(service => - service.ServiceType == typeof(IStartupFilter) && - service.ImplementationType?.Name == "HostFilteringStartupFilter") - .ToList(); - - Assert.NotEmpty(hostFiltering); - - foreach (var service in hostFiltering) - { - services.Remove(service); - } - }); - } + services.Remove(service); + } + }); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/ApiIntegrationTests.cs b/tests/BaGet.Tests/ApiIntegrationTests.cs index 547f51b79..01eaac435 100644 --- a/tests/BaGet.Tests/ApiIntegrationTests.cs +++ b/tests/BaGet.Tests/ApiIntegrationTests.cs @@ -6,46 +6,46 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +public class ApiIntegrationTests : IDisposable { - public class ApiIntegrationTests : IDisposable - { - private readonly BaGetApplication _app; - private readonly HttpClient _client; + private readonly BaGetApplication _app; + private readonly HttpClient _client; - private readonly Stream _packageStream; - private readonly Stream _symbolPackageStream; + private readonly Stream _packageStream; + private readonly Stream _symbolPackageStream; - public ApiIntegrationTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); - _client = _app.CreateClient(); + public ApiIntegrationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output); + _client = _app.CreateClient(); - _packageStream = TestResources.GetResourceStream(TestResources.Package); - _symbolPackageStream = TestResources.GetResourceStream(TestResources.SymbolPackage); - } + _packageStream = TestResources.GetResourceStream(TestResources.Package); + _symbolPackageStream = TestResources.GetResourceStream(TestResources.SymbolPackage); + } - [Fact] - public async Task IndexReturnsOk() - { - using var response = await _client.GetAsync("v3/index.json"); - var content = await response.Content.ReadAsStringAsync(); + [Fact] + public async Task IndexReturnsOk() + { + using var response = await _client.GetAsync("v3/index.json"); + var content = await response.Content.ReadAsStringAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(TestData.ServiceIndex, content); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(TestData.ServiceIndex, content); + } - [Fact] - public async Task SearchReturnsOk() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task SearchReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync("v3/search"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + using var response = await _client.GetAsync("v3/search"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@context"": { ""@vocab"": ""http://schema.nuget.org/schema#"", ""@base"": ""http://localhost/v3/registration"" @@ -77,17 +77,17 @@ public async Task SearchReturnsOk() } ] }", json); - } + } - [Fact] - public async Task SearchReturnsEmpty() - { - using var response = await _client.GetAsync("v3/search?q=PackageDoesNotExist"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + [Fact] + public async Task SearchReturnsEmpty() + { + using var response = await _client.GetAsync("v3/search?q=PackageDoesNotExist"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@context"": { ""@vocab"": ""http://schema.nuget.org/schema#"", ""@base"": ""http://localhost/v3/registration"" @@ -95,19 +95,19 @@ public async Task SearchReturnsEmpty() ""totalHits"": 0, ""data"": [] }", json); - } + } - [Fact] - public async Task AutocompleteReturnsOk() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AutocompleteReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync("v3/autocomplete"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + using var response = await _client.GetAsync("v3/autocomplete"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@context"": { ""@vocab"": ""http://schema.nuget.org/schema#"" }, @@ -116,36 +116,36 @@ public async Task AutocompleteReturnsOk() ""TestData"" ] }", json); - } + } - [Fact] - public async Task AutocompleteReturnsEmpty() - { - using var response = await _client.GetAsync("v3/autocomplete?q=PackageDoesNotExist"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + [Fact] + public async Task AutocompleteReturnsEmpty() + { + using var response = await _client.GetAsync("v3/autocomplete?q=PackageDoesNotExist"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@context"": { ""@vocab"": ""http://schema.nuget.org/schema#"" }, ""totalHits"": 0, ""data"": [] }", json); - } + } - [Fact] - public async Task AutocompleteVersionsReturnsOk() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AutocompleteVersionsReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync("v3/autocomplete?id=TestData"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + using var response = await _client.GetAsync("v3/autocomplete?id=TestData"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@context"": { ""@vocab"": ""http://schema.nuget.org/schema#"" }, @@ -154,95 +154,95 @@ public async Task AutocompleteVersionsReturnsOk() ""1.2.3"" ] }", json); - } + } - [Fact] - public async Task AutocompleteVersionsReturnsEmpty() - { - using var response = await _client.GetAsync("v3/autocomplete?id=PackageDoesNotExist"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + [Fact] + public async Task AutocompleteVersionsReturnsEmpty() + { + using var response = await _client.GetAsync("v3/autocomplete?id=PackageDoesNotExist"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@context"": { ""@vocab"": ""http://schema.nuget.org/schema#"" }, ""totalHits"": 0, ""data"": [] }", json); - } + } - [Fact] - public async Task VersionListReturnsOk() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task VersionListReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - var response = await _client.GetAsync("v3/package/TestData/index.json"); - var content = await response.Content.ReadAsStringAsync(); + var response = await _client.GetAsync("v3/package/TestData/index.json"); + var content = await response.Content.ReadAsStringAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{""versions"":[""1.2.3""]}", content); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{""versions"":[""1.2.3""]}", content); + } - [Fact] - public async Task VersionListReturnsNotFound() - { - using var response = await _client.GetAsync("v3/package/PackageDoesNotExist/index.json"); + [Fact] + public async Task VersionListReturnsNotFound() + { + using var response = await _client.GetAsync("v3/package/PackageDoesNotExist/index.json"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - [Fact] - public async Task PackageDownloadReturnsOk() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task PackageDownloadReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync("v3/package/TestData/1.2.3/TestData.1.2.3.nupkg"); + using var response = await _client.GetAsync("v3/package/TestData/1.2.3/TestData.1.2.3.nupkg"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - [Fact] - public async Task PackageDownloadReturnsNotFound() - { - using var response = await _client.GetAsync( - "v3/package/PackageDoesNotExist/1.0.0/PackageDoesNotExist.1.0.0.nupkg"); + [Fact] + public async Task PackageDownloadReturnsNotFound() + { + using var response = await _client.GetAsync( + "v3/package/PackageDoesNotExist/1.0.0/PackageDoesNotExist.1.0.0.nupkg"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - [Fact] - public async Task NuspecDownloadReturnsOk() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task NuspecDownloadReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync( - "v3/package/TestData/1.2.3/TestData.1.2.3.nuspec"); + using var response = await _client.GetAsync( + "v3/package/TestData/1.2.3/TestData.1.2.3.nuspec"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - [Fact] - public async Task NuspecDownloadReturnsNotFound() - { - using var response = await _client.GetAsync( - "v3/package/PackageDoesNotExist/1.0.0/PackageDoesNotExist.1.0.0.nuspec"); + [Fact] + public async Task NuspecDownloadReturnsNotFound() + { + using var response = await _client.GetAsync( + "v3/package/PackageDoesNotExist/1.0.0/PackageDoesNotExist.1.0.0.nuspec"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - [Fact] - public async Task PackageMetadataReturnsOk() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task PackageMetadataReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync("v3/registration/TestData/index.json"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + using var response = await _client.GetAsync("v3/registration/TestData/index.json"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@id"": ""http://localhost/v3/registration/testdata/index.json"", ""@type"": [ ""catalog:CatalogRoot"", @@ -297,27 +297,27 @@ public async Task PackageMetadataReturnsOk() ], ""totalDownloads"": 0 }", json); - } + } - [Fact] - public async Task PackageMetadataReturnsNotFound() - { - using var response = await _client.GetAsync("v3/registration/PackageDoesNotExist/index.json"); + [Fact] + public async Task PackageMetadataReturnsNotFound() + { + using var response = await _client.GetAsync("v3/registration/PackageDoesNotExist/index.json"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - [Fact] - public async Task PackageMetadataLeafReturnsOk() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task PackageMetadataLeafReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync("v3/registration/TestData/1.2.3.json"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + using var response = await _client.GetAsync("v3/registration/TestData/1.2.3.json"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@id"": ""http://localhost/v3/registration/testdata/1.2.3.json"", ""@type"": [ ""Package"", @@ -328,78 +328,77 @@ public async Task PackageMetadataLeafReturnsOk() ""published"": ""2020-01-01T00:00:00Z"", ""registration"": ""http://localhost/v3/registration/testdata/index.json"" }", json); - } + } - [Fact] - public async Task PackageMetadataLeafReturnsNotFound() - { - using var response = await _client.GetAsync("v3/registration/PackageDoesNotExist/1.0.0.json"); + [Fact] + public async Task PackageMetadataLeafReturnsNotFound() + { + using var response = await _client.GetAsync("v3/registration/PackageDoesNotExist/1.0.0.json"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - [Fact] - public async Task PackageDependentsReturnsOk() - { - using var response = await _client.GetAsync("v3/dependents?packageId=TestData"); + [Fact] + public async Task PackageDependentsReturnsOk() + { + using var response = await _client.GetAsync("v3/dependents?packageId=TestData"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""totalHits"": 0, ""data"": [] }", json); - } + } - [Fact] - public async Task PackageDependentsReturnsBadRequest() - { - using var response = await _client.GetAsync("v3/dependents"); + [Fact] + public async Task PackageDependentsReturnsBadRequest() + { + using var response = await _client.GetAsync("v3/dependents"); - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } - [Fact] - public async Task SymbolDownloadReturnsOk() - { - await _app.AddPackageAsync(_packageStream); - await _app.AddSymbolPackageAsync(_symbolPackageStream); + [Fact] + public async Task SymbolDownloadReturnsOk() + { + await _app.AddPackageAsync(_packageStream); + await _app.AddSymbolPackageAsync(_symbolPackageStream); - using var response = await _client.GetAsync( - "api/download/symbols/testdata.pdb/16F71ED8DD574AA2AD4A22D29E9C981Bffffffff/testdata.pdb"); + using var response = await _client.GetAsync( + "api/download/symbols/testdata.pdb/16F71ED8DD574AA2AD4A22D29E9C981Bffffffff/testdata.pdb"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - [Theory] - [InlineData("api/download/symbols/testdata.pdb/16F71ED8DD574AA2AD4A22D29E9C981B1/testdata.pdb")] - [InlineData("api/download/symbols/testdata.pdb/16F71ED8DD574AA2AD4A22D29E9C981B/testdata.pdb")] - [InlineData("api/download/symbols/testprefix/testdata.pdb/16F71ED8DD574AA2AD4A22D29E9C981Bffffffff/testdata.pdb")] - public async Task MalformedSymbolDownloadReturnsOk(string uri) - { - await _app.AddPackageAsync(_packageStream); - await _app.AddSymbolPackageAsync(_symbolPackageStream); + [Theory] + [InlineData("api/download/symbols/testdata.pdb/16F71ED8DD574AA2AD4A22D29E9C981B1/testdata.pdb")] + [InlineData("api/download/symbols/testdata.pdb/16F71ED8DD574AA2AD4A22D29E9C981B/testdata.pdb")] + [InlineData("api/download/symbols/testprefix/testdata.pdb/16F71ED8DD574AA2AD4A22D29E9C981Bffffffff/testdata.pdb")] + public async Task MalformedSymbolDownloadReturnsOk(string uri) + { + await _app.AddPackageAsync(_packageStream); + await _app.AddSymbolPackageAsync(_symbolPackageStream); - using var response = await _client.GetAsync(uri); + using var response = await _client.GetAsync(uri); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - [Fact] - public async Task SymbolDownloadReturnsNotFound() - { - using var response = await _client.GetAsync( - "api/download/symbols/doesnotexist.pdb/16F71ED8DD574AA2AD4A22D29E9C981Bffffffff/doesnotexist.pdb"); + [Fact] + public async Task SymbolDownloadReturnsNotFound() + { + using var response = await _client.GetAsync( + "api/download/symbols/doesnotexist.pdb/16F71ED8DD574AA2AD4A22D29E9C981Bffffffff/doesnotexist.pdb"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - public void Dispose() - { - _app.Dispose(); - _client.Dispose(); - } + public void Dispose() + { + _app.Dispose(); + _client.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/BaGetClientIntegrationTests.cs b/tests/BaGet.Tests/BaGetClientIntegrationTests.cs index e3192b944..5e3045bc7 100644 --- a/tests/BaGet.Tests/BaGetClientIntegrationTests.cs +++ b/tests/BaGet.Tests/BaGetClientIntegrationTests.cs @@ -8,227 +8,226 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Uses BaGet's client SDK to interact with the BaGet test host. +/// +public class BaGetClientIntegrationTests : IDisposable { - /// - /// Uses BaGet's client SDK to interact with the BaGet test host. - /// - public class BaGetClientIntegrationTests : IDisposable - { - private readonly BaGetApplication _app; - private readonly HttpClient _httpClient; - private readonly NuGetClientFactory _clientFactory; - private readonly NuGetClient _client; + private readonly BaGetApplication _app; + private readonly HttpClient _httpClient; + private readonly NuGetClientFactory _clientFactory; + private readonly NuGetClient _client; - private readonly Stream _packageStream; + private readonly Stream _packageStream; - public BaGetClientIntegrationTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); + public BaGetClientIntegrationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output); - var serviceIndexUrl = new Uri(_app.Server.BaseAddress, "v3/index.json"); + var serviceIndexUrl = new Uri(_app.Server.BaseAddress, "v3/index.json"); - _httpClient = _app.CreateClient(); - _clientFactory = new NuGetClientFactory(_httpClient, serviceIndexUrl.AbsoluteUri); - _client = new NuGetClient(_clientFactory); + _httpClient = _app.CreateClient(); + _clientFactory = new NuGetClientFactory(_httpClient, serviceIndexUrl.AbsoluteUri); + _client = new NuGetClient(_clientFactory); - _packageStream = TestResources.GetResourceStream(TestResources.Package); - } + _packageStream = TestResources.GetResourceStream(TestResources.Package); + } - [Fact] - public async Task ValidIndex() - { - var client = _clientFactory.CreateServiceIndexClient(); - var index = await client.GetAsync(); - - Assert.Equal("3.0.0", index.Version); - Assert.Equal(17, index.Resources.Count); - - Assert.NotEmpty(index.GetResourceUrl(new[] { "PackageBaseAddress/3.0.0" })); - Assert.NotEmpty(index.GetResourceUrl(new[] { "PackagePublish/2.0.0" })); - Assert.NotEmpty(index.GetResourceUrl(new[] { "RegistrationsBaseUrl" })); - Assert.NotEmpty(index.GetResourceUrl(new[] { "SearchAutocompleteService" })); - Assert.NotEmpty(index.GetResourceUrl(new[] { "SearchQueryService" })); - Assert.NotEmpty(index.GetResourceUrl(new[] { "PackageDetailsUriTemplate/5.1.0" })); - Assert.NotEmpty(index.GetResourceUrl(new[] { "ReportAbuseUriTemplate/3.0.0-rc" })); - Assert.NotEmpty(index.GetResourceUrl(new[] { "SymbolPackagePublish/4.9.0" })); - } + [Fact] + public async Task ValidIndex() + { + var client = _clientFactory.CreateServiceIndexClient(); + var index = await client.GetAsync(); + + Assert.Equal("3.0.0", index.Version); + Assert.Equal(17, index.Resources.Count); + + Assert.NotEmpty(index.GetResourceUrl(new[] { "PackageBaseAddress/3.0.0" })); + Assert.NotEmpty(index.GetResourceUrl(new[] { "PackagePublish/2.0.0" })); + Assert.NotEmpty(index.GetResourceUrl(new[] { "RegistrationsBaseUrl" })); + Assert.NotEmpty(index.GetResourceUrl(new[] { "SearchAutocompleteService" })); + Assert.NotEmpty(index.GetResourceUrl(new[] { "SearchQueryService" })); + Assert.NotEmpty(index.GetResourceUrl(new[] { "PackageDetailsUriTemplate/5.1.0" })); + Assert.NotEmpty(index.GetResourceUrl(new[] { "ReportAbuseUriTemplate/3.0.0-rc" })); + Assert.NotEmpty(index.GetResourceUrl(new[] { "SymbolPackagePublish/4.9.0" })); + } - [Fact] - public async Task SearchReturnsResults() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task SearchReturnsResults() + { + await _app.AddPackageAsync(_packageStream); - var results = await _client.SearchAsync(); + var results = await _client.SearchAsync(); - var result = Assert.Single(results); - var author = Assert.Single(result.Authors); - var version = Assert.Single(result.Versions); + var result = Assert.Single(results); + var author = Assert.Single(result.Authors); + var version = Assert.Single(result.Versions); - Assert.Equal("TestData", result.PackageId); - Assert.Equal("1.2.3", result.Version); - Assert.Equal("Test description", result.Description); - Assert.Equal("Test author", author); - Assert.Equal(0, result.TotalDownloads); + Assert.Equal("TestData", result.PackageId); + Assert.Equal("1.2.3", result.Version); + Assert.Equal("Test description", result.Description); + Assert.Equal("Test author", author); + Assert.Equal(0, result.TotalDownloads); - Assert.Equal("1.2.3", version.Version); - Assert.Equal(0, version.Downloads); - } + Assert.Equal("1.2.3", version.Version); + Assert.Equal(0, version.Downloads); + } - [Fact] - public async Task SearchReturnsEmpty() - { - var results = await _client.SearchAsync("PackageDoesNotExist"); + [Fact] + public async Task SearchReturnsEmpty() + { + var results = await _client.SearchAsync("PackageDoesNotExist"); - Assert.Empty(results); - } + Assert.Empty(results); + } - [Fact] - public async Task AutocompleteReturnsResults() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AutocompleteReturnsResults() + { + await _app.AddPackageAsync(_packageStream); - var results = await _client.AutocompleteAsync(); + var results = await _client.AutocompleteAsync(); - var result = Assert.Single(results); + var result = Assert.Single(results); - Assert.Equal("TestData", result); - } + Assert.Equal("TestData", result); + } - [Fact] - public async Task AutocompleteReturnsEmpty() - { - var results = await _client.AutocompleteAsync("PackageDoesNotExist"); + [Fact] + public async Task AutocompleteReturnsEmpty() + { + var results = await _client.AutocompleteAsync("PackageDoesNotExist"); - Assert.Empty(results); - } + Assert.Empty(results); + } - [Fact] - public async Task AutocompleteVersions() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AutocompleteVersions() + { + await _app.AddPackageAsync(_packageStream); - var client = _clientFactory.CreateAutocompleteClient(); - var results = await client.ListPackageVersionsAsync("TestData"); + var client = _clientFactory.CreateAutocompleteClient(); + var results = await client.ListPackageVersionsAsync("TestData"); - var result = Assert.Single(results.Data); + var result = Assert.Single(results.Data); - Assert.Equal(1, results.TotalHits); - Assert.Equal("1.2.3", result); - } + Assert.Equal(1, results.TotalHits); + Assert.Equal("1.2.3", result); + } - [Fact] - public async Task AutocompleteVersionsReturnsEmpty() - { - var client = _clientFactory.CreateAutocompleteClient(); - var results = await client.ListPackageVersionsAsync("PackageDoesNotExist"); + [Fact] + public async Task AutocompleteVersionsReturnsEmpty() + { + var client = _clientFactory.CreateAutocompleteClient(); + var results = await client.ListPackageVersionsAsync("PackageDoesNotExist"); - Assert.Empty(results.Data); - Assert.Equal(0, results.TotalHits); - } + Assert.Empty(results.Data); + Assert.Equal(0, results.TotalHits); + } - [Fact] - public async Task VersionListReturnsResults() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task VersionListReturnsResults() + { + await _app.AddPackageAsync(_packageStream); - var versions = await _client.ListPackageVersionsAsync("TestData"); + var versions = await _client.ListPackageVersionsAsync("TestData"); - var version = Assert.Single(versions); + var version = Assert.Single(versions); - Assert.Equal("1.2.3", version.ToNormalizedString()); - } + Assert.Equal("1.2.3", version.ToNormalizedString()); + } - [Fact] - public async Task VersionListReturnsEmpty() - { - var versions = await _client.ListPackageVersionsAsync("PackageDoesNotExist"); + [Fact] + public async Task VersionListReturnsEmpty() + { + var versions = await _client.ListPackageVersionsAsync("PackageDoesNotExist"); - Assert.Empty(versions); - } + Assert.Empty(versions); + } - [Theory] - [InlineData("TestData", "1.0.0", false)] - [InlineData("TestData", "1.2.3", true)] - [InlineData("PackageDoesNotExists", "1.0.0", false)] - public async Task PackageDownloadWorks(string packageId, string packageVersion, bool exists) - { - await _app.AddPackageAsync(_packageStream); + [Theory] + [InlineData("TestData", "1.0.0", false)] + [InlineData("TestData", "1.2.3", true)] + [InlineData("PackageDoesNotExists", "1.0.0", false)] + public async Task PackageDownloadWorks(string packageId, string packageVersion, bool exists) + { + await _app.AddPackageAsync(_packageStream); - try - { - var version = NuGetVersion.Parse(packageVersion); + try + { + var version = NuGetVersion.Parse(packageVersion); - using var memoryStream = new MemoryStream(); - using var packageStream = await _client.DownloadPackageAsync(packageId, version); + using var memoryStream = new MemoryStream(); + using var packageStream = await _client.DownloadPackageAsync(packageId, version); - await packageStream.CopyToAsync(memoryStream); - memoryStream.Position = 0; + await packageStream.CopyToAsync(memoryStream); + memoryStream.Position = 0; - Assert.True(exists); - Assert.Equal(exists, memoryStream.Length > 0); - } - catch (PackageNotFoundException) - { - Assert.False(exists); - } + Assert.True(exists); + Assert.Equal(exists, memoryStream.Length > 0); } - - [Theory] - [InlineData("TestData", "1.0.0", false)] - [InlineData("TestData", "1.2.3", true)] - [InlineData("PackageDoesNotExists", "1.0.0", false)] - public async Task ManifestDownloadWorks(string packageId, string packageVersion, bool exists) + catch (PackageNotFoundException) { - await _app.AddPackageAsync(_packageStream); + Assert.False(exists); + } + } + + [Theory] + [InlineData("TestData", "1.0.0", false)] + [InlineData("TestData", "1.2.3", true)] + [InlineData("PackageDoesNotExists", "1.0.0", false)] + public async Task ManifestDownloadWorks(string packageId, string packageVersion, bool exists) + { + await _app.AddPackageAsync(_packageStream); - try - { - var version = NuGetVersion.Parse(packageVersion); + try + { + var version = NuGetVersion.Parse(packageVersion); - using var memoryStream = new MemoryStream(); - using var packageStream = await _client.DownloadPackageManifestAsync(packageId, version); + using var memoryStream = new MemoryStream(); + using var packageStream = await _client.DownloadPackageManifestAsync(packageId, version); - await packageStream.CopyToAsync(memoryStream); - memoryStream.Position = 0; + await packageStream.CopyToAsync(memoryStream); + memoryStream.Position = 0; - Assert.True(exists); - Assert.Equal(exists, memoryStream.Length > 0); - } - catch (PackageNotFoundException) - { - Assert.False(exists); - } + Assert.True(exists); + Assert.Equal(exists, memoryStream.Length > 0); } - - [Fact] - public async Task PackageMetadataReturnsOk() + catch (PackageNotFoundException) { - await _app.AddPackageAsync(_packageStream); + Assert.False(exists); + } + } - var packages = await _client.GetPackageMetadataAsync("TestData"); + [Fact] + public async Task PackageMetadataReturnsOk() + { + await _app.AddPackageAsync(_packageStream); - var package = Assert.Single(packages); + var packages = await _client.GetPackageMetadataAsync("TestData"); - Assert.Equal("TestData", package.PackageId); - Assert.Equal("1.2.3", package.Version); - Assert.Equal("Test description", package.Description); - Assert.Equal("Test author", package.Authors); - Assert.True(package.Listed); - } + var package = Assert.Single(packages); - [Fact] - public async Task PackageMetadataReturnsEmty() - { - var packages = await _client.GetPackageMetadataAsync("PackageDoesNotExist"); + Assert.Equal("TestData", package.PackageId); + Assert.Equal("1.2.3", package.Version); + Assert.Equal("Test description", package.Description); + Assert.Equal("Test author", package.Authors); + Assert.True(package.Listed); + } - Assert.Empty(packages); - } + [Fact] + public async Task PackageMetadataReturnsEmty() + { + var packages = await _client.GetPackageMetadataAsync("PackageDoesNotExist"); - public void Dispose() - { - _app.Dispose(); - _httpClient.Dispose(); - } + Assert.Empty(packages); + } + + public void Dispose() + { + _app.Dispose(); + _httpClient.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/BrowserUploadReviewTests.cs b/tests/BaGet.Tests/BrowserUploadReviewTests.cs new file mode 100644 index 000000000..1370d3437 --- /dev/null +++ b/tests/BaGet.Tests/BrowserUploadReviewTests.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using BaGet.Core; +using BaGet.Web; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Xunit; +using Xunit.Abstractions; + +namespace BaGet.Tests +{ + /// + /// Publishing leaves nothing behind in staging, and a rejected API key does not cost the + /// user their staged upload. + /// + public class BrowserUploadCleanupTests : IDisposable + { + private const string GlobalKey = "global-key"; + + private readonly BaGetApplication _app; + + public BrowserUploadCleanupTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary + { + { "ApiKey", GlobalKey }, + }); + } + + [Fact] + public async Task PublishingRemovesTheStagedPackageBlobAsWellAsItsMetadata() + { + using var browser = new Browser(_app); + var token = await StageAsync(browser); + + using var published = await browser.SubmitAsync(token, apiKey: GlobalKey); + + Assert.Contains("was published", await published.Content.ReadAsStringAsync()); + Assert.False(await StoredAsync($"staging/{token}.nupkg"), "The staged package blob was left behind."); + Assert.False(await StoredAsync($"staging/{token}.json")); + } + + [Fact] + public async Task AWrongKeyOnConfirmKeepsTheUploadAndOffersTheKeyAgain() + { + using var browser = new Browser(_app); + var token = await StageAsync(browser); + + using var wrong = await browser.SubmitAsync(token, apiKey: "nope"); + var html = await wrong.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.Unauthorized, wrong.StatusCode); + Assert.Equal(token, BrowserUpload.StagedToken(html)); + + using var retried = await browser.SubmitAsync(token, apiKey: GlobalKey); + Assert.Contains("was published", await retried.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task DiscardingWithoutTheKeyKeepsTheUploadAndTheKeyDiscardsIt() + { + using var browser = new Browser(_app); + var token = await StageAsync(browser); + + using var wrong = await browser.CancelAsync(token); + Assert.Equal(HttpStatusCode.Unauthorized, wrong.StatusCode); + Assert.Equal(token, BrowserUpload.StagedToken(await wrong.Content.ReadAsStringAsync())); + Assert.True(await StoredAsync($"staging/{token}.nupkg")); + + using var right = await browser.CancelAsync(token, GlobalKey); + Assert.Equal(HttpStatusCode.OK, right.StatusCode); + Assert.False(await StoredAsync($"staging/{token}.nupkg")); + } + + private static async Task StageAsync(Browser browser) + { + using var staged = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + GlobalKey); + + Assert.Equal(HttpStatusCode.OK, staged.StatusCode); + + return BrowserUpload.StagedToken(await staged.Content.ReadAsStringAsync()); + } + + private async Task StoredAsync(string path) + { + using var scope = _app.Services.CreateScope(); + var storage = scope.ServiceProvider.GetRequiredService(); + + try + { + using var stream = await storage.GetAsync(path, CancellationToken.None); + return stream != null; + } + catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) + { + return false; + } + } + + public void Dispose() => _app.Dispose(); + } + + /// + /// The package is published before ownership is recorded, so a failure recording it is + /// reported on the page rather than as a bare 500, and the staged upload is still removed. + /// + public class BrowserUploadOwnershipFailureTests : IDisposable + { + private const string GlobalKey = "global-key"; + + private readonly BaGetApplication _app; + + public BrowserUploadOwnershipFailureTests(ITestOutputHelper output) + { + _app = new BaGetApplication( + output, + configOverrides: new Dictionary { { "ApiKey", GlobalKey } }, + configureServices: services => services.Replace( + ServiceDescriptor.Transient())); + } + + [Fact] + public async Task AFailureRecordingOwnershipIsReportedAndTheStagedUploadRemoved() + { + using var browser = new Browser(_app); + using var staged = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + GlobalKey); + var token = BrowserUpload.StagedToken(await staged.Content.ReadAsStringAsync()); + + using var response = await browser.SubmitAsync(token, apiKey: GlobalKey); + var html = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("was published", html); + Assert.Contains("Recording you as the owner", html); + + using var again = await browser.SubmitAsync(token, apiKey: GlobalKey); + Assert.Equal(HttpStatusCode.NotFound, again.StatusCode); + } + + public void Dispose() => _app.Dispose(); + + private sealed class FailingOwnership : IPackageAuthorizationService + { + public Task AuthorizeAsync(BaGetPrincipal principal, PackageAction action, string packageId, CancellationToken cancellationToken) + => Task.FromResult(true); + + public Task OnPushedAsync(BaGetPrincipal principal, string packageId, CancellationToken cancellationToken) + => throw new InvalidOperationException("the database is down"); + } + } + + /// + /// With validation on, a confirmed upload is queued, not indexed: there is no package + /// page to link to yet. + /// + public class BrowserUploadValidationTests : IDisposable + { + private const string GlobalKey = "global-key"; + + private readonly BaGetApplication _app; + + public BrowserUploadValidationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary + { + { "ApiKey", GlobalKey }, + { "Validation:Enabled", "true" }, + }); + } + + [Fact] + public async Task AnAcceptedUploadIsNotLinkedToAPageThatDoesNotExistYet() + { + using var browser = new Browser(_app); + using var staged = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + GlobalKey); + var token = BrowserUpload.StagedToken(await staged.Content.ReadAsStringAsync()); + + using var response = await browser.SubmitAsync(token, apiKey: GlobalKey); + var html = await response.Content.ReadAsStringAsync(); + + Assert.Contains("is being validated", html); + Assert.DoesNotContain("View it", html); + } + + public void Dispose() => _app.Dispose(); + } +} diff --git a/tests/BaGet.Tests/BrowserUploadSecurityTests.cs b/tests/BaGet.Tests/BrowserUploadSecurityTests.cs index e11d9b010..cf2288e8a 100644 --- a/tests/BaGet.Tests/BrowserUploadSecurityTests.cs +++ b/tests/BaGet.Tests/BrowserUploadSecurityTests.cs @@ -14,231 +14,230 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// The shipped default: no API key and no accounts. Nothing can tell one caller from +/// another there, so the browser upload is closed rather than a publish button for +/// whoever finds the page. +/// +public class BrowserUploadWithoutAnyApiKeyTests : IDisposable { - /// - /// The shipped default: no API key and no accounts. Nothing can tell one caller from - /// another there, so the browser upload is closed rather than a publish button for - /// whoever finds the page. - /// - public class BrowserUploadWithoutAnyApiKeyTests : IDisposable - { - private readonly BaGetApplication _app; - private readonly HttpClient _client; + private readonly BaGetApplication _app; + private readonly HttpClient _client; - public BrowserUploadWithoutAnyApiKeyTests(ITestOutputHelper output) - { - // Exactly src/BaGet/appsettings.json as it ships: ApiKey "" and no accounts. - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "ApiKey", "" }, - }); - _client = _app.CreateClient(); - } - - [Fact] - public async Task TheFormIsNotOfferedWhenNothingCanAuthenticateAnUpload() + public BrowserUploadWithoutAnyApiKeyTests(ITestOutputHelper output) + { + // Exactly src/BaGet/appsettings.json as it ships: ApiKey "" and no accounts. + _app = new BaGetApplication(output, configOverrides: new Dictionary { - using var browser = new Browser(_app); + { "ApiKey", "" }, + }); + _client = _app.CreateClient(); + } - using var response = await browser.GetAsync("upload"); - var html = await response.Content.ReadAsStringAsync(); + [Fact] + public async Task TheFormIsNotOfferedWhenNothingCanAuthenticateAnUpload() + { + using var browser = new Browser(_app); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using var response = await browser.GetAsync("upload"); + var html = await response.Content.ReadAsStringAsync(); - // No file picker, and no API key box that would be ignored if filled in. - Assert.DoesNotContain("name=\"package\"", html); - Assert.DoesNotContain("name=\"apiKey\"", html); - Assert.Contains("upload-no-api-key", html); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); - [Fact] - public async Task AnAnonymousVisitorCannotStageAnything() - { - using var browser = new Browser(_app); + // No file picker, and no API key box that would be ignored if filled in. + Assert.DoesNotContain("name=\"package\"", html); + Assert.DoesNotContain("name=\"apiKey\"", html); + Assert.Contains("upload-no-api-key", html); + } - using var response = await browser.StageAsync( - "TestData.1.2.3.nupkg", - TestResources.GetResourceStream(TestResources.Package), - apiKey: null, - tokenPage: BrowserUpload.TokenPage); + [Fact] + public async Task AnAnonymousVisitorCannotStageAnything() + { + using var browser = new Browser(_app); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.DoesNotMatch("name=\"token\" value=\"[0-9a-f]{32}\"", await response.Content.ReadAsStringAsync()); - Assert.False(await ExistsAsync("TestData", "1.2.3")); - } + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + apiKey: null, + tokenPage: BrowserUpload.TokenPage); - [Fact] - public async Task AnEmptyApiKeyBoxIsNotAWayIn() - { - using var browser = new Browser(_app); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotMatch("name=\"token\" value=\"[0-9a-f]{32}\"", await response.Content.ReadAsStringAsync()); + Assert.False(await ExistsAsync("TestData", "1.2.3")); + } - using var response = await browser.StageAsync( - "TestData.1.2.3.nupkg", - TestResources.GetResourceStream(TestResources.Package), - apiKey: "", - tokenPage: BrowserUpload.TokenPage); + [Fact] + public async Task AnEmptyApiKeyBoxIsNotAWayIn() + { + using var browser = new Browser(_app); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.False(await ExistsAsync("TestData", "1.2.3")); - } + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + apiKey: "", + tokenPage: BrowserUpload.TokenPage); - [Fact] - public async Task ThePushEndpointIsUnchanged() - { - // Closing the browser form must not close the API an open server already has: - // the page is a convenience, not the authorization model. - using var package = TestPackages.Build("Open.Package", "1.0.0"); - using var request = TestPackages.PushRequest(package, apiKey: null); - using var response = await _client.SendAsync(request); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.False(await ExistsAsync("TestData", "1.2.3")); + } - Assert.Equal(HttpStatusCode.Created, response.StatusCode); - } + [Fact] + public async Task ThePushEndpointIsUnchanged() + { + // Closing the browser form must not close the API an open server already has: + // the page is a convenience, not the authorization model. + using var package = TestPackages.Build("Open.Package", "1.0.0"); + using var request = TestPackages.PushRequest(package, apiKey: null); + using var response = await _client.SendAsync(request); - private async Task ExistsAsync(string id, string version) - { - using var scope = _app.Services.CreateScope(); - var packages = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } - return await packages.ExistsAsync(id, NuGetVersion.Parse(version), CancellationToken.None); - } + private async Task ExistsAsync(string id, string version) + { + using var scope = _app.Services.CreateScope(); + var packages = scope.ServiceProvider.GetRequiredService(); - public void Dispose() - { - _client.Dispose(); - _app.Dispose(); - } + return await packages.ExistsAsync(id, NuGetVersion.Parse(version), CancellationToken.None); } - /// - /// A store that fails while an upload is being staged is reported as a sentence, as the - /// equivalent failure on the confirm step already is - not as a bare 500 or a stack - /// trace. - /// - public class BrowserUploadStorageFailureTests : IDisposable + public void Dispose() { - private const string GlobalKey = "global-key"; + _client.Dispose(); + _app.Dispose(); + } +} - private readonly BaGetApplication _app; +/// +/// A store that fails while an upload is being staged is reported as a sentence, as the +/// equivalent failure on the confirm step already is - not as a bare 500 or a stack +/// trace. +/// +public class BrowserUploadStorageFailureTests : IDisposable +{ + private const string GlobalKey = "global-key"; - public BrowserUploadStorageFailureTests(ITestOutputHelper output) - { - _app = new BaGetApplication( - output, - configOverrides: new Dictionary { { "ApiKey", GlobalKey } }, - configureServices: services => services.Replace( - ServiceDescriptor.Scoped(_ => new UnwritableStaging()))); - } - - [Fact] - public async Task AStoreThatCannotHoldTheUploadIsReportedAsASentence() - { - using var browser = new Browser(_app); + private readonly BaGetApplication _app; - using var response = await browser.StageAsync( - "TestData.1.2.3.nupkg", - TestResources.GetResourceStream(TestResources.Package), - GlobalKey); - var html = await response.Content.ReadAsStringAsync(); + public BrowserUploadStorageFailureTests(ITestOutputHelper output) + { + _app = new BaGetApplication( + output, + configOverrides: new Dictionary { { "ApiKey", GlobalKey } }, + configureServices: services => services.Replace( + ServiceDescriptor.Scoped(_ => new UnwritableStaging()))); + } - Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - Assert.Contains("could not store", html); - Assert.DoesNotContain(" at ", html); - Assert.DoesNotContain("the disk is full", html); - } + [Fact] + public async Task AStoreThatCannotHoldTheUploadIsReportedAsASentence() + { + using var browser = new Browser(_app); + + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + GlobalKey); + var html = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.Contains("could not store", html); + Assert.DoesNotContain(" at ", html); + Assert.DoesNotContain("the disk is full", html); + } - public void Dispose() => _app.Dispose(); + public void Dispose() => _app.Dispose(); - private sealed class UnwritableStaging : IPackageStagingService - { - public Task StageAsync(Stream package, string ownerId, CancellationToken cancellationToken = default) - => throw new IOException("the disk is full"); + private sealed class UnwritableStaging : IPackageStagingService + { + public Task StageAsync(Stream package, string ownerId, CancellationToken cancellationToken = default) + => throw new IOException("the disk is full"); - public Task OpenAsync(string token, string ownerId, CancellationToken cancellationToken = default) - => Task.FromResult(null); + public Task OpenAsync(string token, string ownerId, CancellationToken cancellationToken = default) + => Task.FromResult(null); - public Task RemoveAsync(string token, string ownerId, CancellationToken cancellationToken = default) - => Task.FromResult(false); + public Task RemoveAsync(string token, string ownerId, CancellationToken cancellationToken = default) + => Task.FromResult(false); - public Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default) - => Task.FromResult(0); - } + public Task SweepAsync(DateTime stagedBefore, CancellationToken cancellationToken = default) + => Task.FromResult(0); } +} - /// - /// Discarding a staged upload is a write to storage and a loss to its owner, so it is - /// refused on a read-only server exactly as publishing is. - /// - public class BrowserUploadCancelReadOnlyTests : IDisposable - { - private readonly BaGetApplication _app; +/// +/// Discarding a staged upload is a write to storage and a loss to its owner, so it is +/// refused on a read-only server exactly as publishing is. +/// +public class BrowserUploadCancelReadOnlyTests : IDisposable +{ + private readonly BaGetApplication _app; - public BrowserUploadCancelReadOnlyTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "ApiKey", "global-key" }, - { "Accounts:Enabled", "true" }, - { "IsReadOnlyMode", "true" }, - }); - } - - [Fact] - public async Task AReadOnlyServerRefusesToDiscardAStagedUpload() + public BrowserUploadCancelReadOnlyTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary { - using var alice = new Browser(_app); - await alice.RegisterAsync("alice"); - - // Staged through the service: a read-only server refuses the upload itself, and - // the case being pinned is a server switched to read-only while a preview is open. - var aliceId = await WithScopeAsync(async s => - (await s.GetRequiredService>().FindByNameAsync("alice")).Id); + { "ApiKey", "global-key" }, + { "Accounts:Enabled", "true" }, + { "IsReadOnlyMode", "true" }, + }); + } - var staging = _app.Services.GetRequiredService(); - var token = await staging.StageAsync(Package(), aliceId, CancellationToken.None); + [Fact] + public async Task AReadOnlyServerRefusesToDiscardAStagedUpload() + { + using var alice = new Browser(_app); + await alice.RegisterAsync("alice"); - using var response = await alice.CancelAsync(token, tokenPage: BrowserUpload.TokenPage); + // Staged through the service: a read-only server refuses the upload itself, and + // the case being pinned is a server switched to read-only while a preview is open. + var aliceId = await WithScopeAsync(async s => + (await s.GetRequiredService>().FindByNameAsync("alice")).Id); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Contains("read-only", await response.Content.ReadAsStringAsync()); + var staging = _app.Services.GetRequiredService(); + var token = await staging.StageAsync(Package(), aliceId, CancellationToken.None); - // The upload is still there, so nothing in storage was written. - using var kept = await staging.OpenAsync(token, aliceId, CancellationToken.None); - Assert.NotNull(kept); - } + using var response = await alice.CancelAsync(token, tokenPage: BrowserUpload.TokenPage); - private async Task WithScopeAsync(Func> action) - { - using var scope = _app.Services.CreateScope(); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Contains("read-only", await response.Content.ReadAsStringAsync()); - return await action(scope.ServiceProvider); - } + // The upload is still there, so nothing in storage was written. + using var kept = await staging.OpenAsync(token, aliceId, CancellationToken.None); + Assert.NotNull(kept); + } - private static Stream Package() => TestResources.GetResourceStream(TestResources.Package); + private async Task WithScopeAsync(Func> action) + { + using var scope = _app.Services.CreateScope(); - public void Dispose() => _app.Dispose(); + return await action(scope.ServiceProvider); } - /// - /// Abandoned staged uploads are only ever reclaimed by the sweep, and the sweep can only - /// reclaim what the store can enumerate. A store that cannot be swept grows without - /// bound, so every store BaGet ships must be listable. - /// - public class StorageCanBeSweptTests + private static Stream Package() => TestResources.GetResourceStream(TestResources.Package); + + public void Dispose() => _app.Dispose(); +} + +/// +/// Abandoned staged uploads are only ever reclaimed by the sweep, and the sweep can only +/// reclaim what the store can enumerate. A store that cannot be swept grows without +/// bound, so every store BaGet ships must be listable. +/// +public class StorageCanBeSweptTests +{ + [Theory] + [InlineData(typeof(FileStorageService))] + [InlineData(typeof(NullStorageService))] + [InlineData(typeof(BaGet.Azure.BlobStorageService))] + [InlineData(typeof(BaGet.Aws.S3StorageService))] + [InlineData(typeof(BaGet.Gcp.GoogleCloudStorageService))] + [InlineData(typeof(BaGet.Aliyun.AliyunStorageService))] + public void EveryStoreCanListWhatItHolds(Type storage) { - [Theory] - [InlineData(typeof(FileStorageService))] - [InlineData(typeof(NullStorageService))] - [InlineData(typeof(BaGet.Azure.BlobStorageService))] - [InlineData(typeof(BaGet.Aws.S3StorageService))] - [InlineData(typeof(BaGet.Gcp.GoogleCloudStorageService))] - [InlineData(typeof(BaGet.Aliyun.AliyunStorageService))] - public void EveryStoreCanListWhatItHolds(Type storage) - { - Assert.True( - typeof(IListableStorageService).IsAssignableFrom(storage), - $"{storage.Name} cannot be swept: it does not implement {nameof(IListableStorageService)}, " - + "so abandoned staged uploads would accumulate in it forever."); - } + Assert.True( + typeof(IListableStorageService).IsAssignableFrom(storage), + $"{storage.Name} cannot be swept: it does not implement {nameof(IListableStorageService)}, " + + "so abandoned staged uploads would accumulate in it forever."); } } diff --git a/tests/BaGet.Tests/BrowserUploadTests.cs b/tests/BaGet.Tests/BrowserUploadTests.cs index 62440efe8..417271523 100644 --- a/tests/BaGet.Tests/BrowserUploadTests.cs +++ b/tests/BaGet.Tests/BrowserUploadTests.cs @@ -14,592 +14,591 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Shared by the browser upload tests: driving the two steps of the upload page the way a +/// browser drives them. +/// +internal static class BrowserUpload { /// - /// Shared by the browser upload tests: driving the two steps of the upload page the way a - /// browser drives them. + /// A page that always renders a form, and so always yields an antiforgery token. The + /// upload page renders no form in read-only mode, and the token is per session, not + /// per form. /// - internal static class BrowserUpload - { - /// - /// A page that always renders a form, and so always yields an antiforgery token. The - /// upload page renders no form in read-only mode, and the token is per session, not - /// per form. - /// - public const string TokenPage = "packages/Any.Package/1.0.0/report-abuse"; - - public static Task StageAsync( - this Browser browser, - string fileName, - Stream file, - string apiKey = null, - string tokenPage = null) - { - var fields = new Dictionary(); - if (apiKey != null) fields["apiKey"] = apiKey; - - return browser.PostFileAsync( - "upload?handler=Stage", - "package", - fileName, - file, - fields, - tokenPage); - } - - public static Task SubmitAsync( - this Browser browser, - string token, - bool acceptTerms = true, - string apiKey = null, - string tokenPage = null) - { - var fields = new Dictionary { { "token", token } }; - if (acceptTerms) fields["acceptTerms"] = "true"; - if (apiKey != null) fields["apiKey"] = apiKey; - - return browser.PostAsync("upload", fields, "upload?handler=Submit", tokenPage); - } - - public static Task CancelAsync( - this Browser browser, - string token, - string apiKey = null, - string tokenPage = null) - { - var fields = new Dictionary { { "token", token } }; - if (apiKey != null) fields["apiKey"] = apiKey; + public const string TokenPage = "packages/Any.Package/1.0.0/report-abuse"; + + public static Task StageAsync( + this Browser browser, + string fileName, + Stream file, + string apiKey = null, + string tokenPage = null) + { + var fields = new Dictionary(); + if (apiKey != null) fields["apiKey"] = apiKey; + + return browser.PostFileAsync( + "upload?handler=Stage", + "package", + fileName, + file, + fields, + tokenPage); + } - return browser.PostAsync("upload", fields, "upload?handler=Cancel", tokenPage); - } + public static Task SubmitAsync( + this Browser browser, + string token, + bool acceptTerms = true, + string apiKey = null, + string tokenPage = null) + { + var fields = new Dictionary { { "token", token } }; + if (acceptTerms) fields["acceptTerms"] = "true"; + if (apiKey != null) fields["apiKey"] = apiKey; - /// - /// The staging token the preview is carrying, which is the only handle on a staged - /// upload. - /// - public static string StagedToken(string html) - { - var match = Regex.Match(html, "name=\"token\" value=\"([0-9a-f]{32})\""); + return browser.PostAsync("upload", fields, "upload?handler=Submit", tokenPage); + } - Assert.True(match.Success, "The preview did not render a staging token."); + public static Task CancelAsync( + this Browser browser, + string token, + string apiKey = null, + string tokenPage = null) + { + var fields = new Dictionary { { "token", token } }; + if (apiKey != null) fields["apiKey"] = apiKey; - return match.Groups[1].Value; - } + return browser.PostAsync("upload", fields, "upload?handler=Cancel", tokenPage); } /// - /// The browser upload with accounts on: the signed-in session is the identity, and - /// ownership decides what it may publish. + /// The staging token the preview is carrying, which is the only handle on a staged + /// upload. /// - public class BrowserUploadTests : IDisposable + public static string StagedToken(string html) { - private readonly BaGetApplication _app; + var match = Regex.Match(html, "name=\"token\" value=\"([0-9a-f]{32})\""); - public BrowserUploadTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "ApiKey", "global-key" }, - { "Accounts:Enabled", "true" }, - }); - } + Assert.True(match.Success, "The preview did not render a staging token."); - [Fact] - public async Task PublishesAPackageThroughTheTwoSteps() - { - using var alice = await SignInAsync("alice"); + return match.Groups[1].Value; + } +} - var preview = await StageAsync(alice, "TestData.1.2.3.nupkg", TestResources.GetResourceStream(TestResources.Package)); +/// +/// The browser upload with accounts on: the signed-in session is the identity, and +/// ownership decides what it may publish. +/// +public class BrowserUploadTests : IDisposable +{ + private readonly BaGetApplication _app; - // Step one shows what the file contains, and publishes nothing. - Assert.Contains("TestData 1.2.3", preview); - Assert.Contains("Test description", preview); - Assert.Contains("Test author", preview); - Assert.False(await ExistsAsync("TestData", "1.2.3")); + public BrowserUploadTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary + { + { "ApiKey", "global-key" }, + { "Accounts:Enabled", "true" }, + }); + } - var token = BrowserUpload.StagedToken(preview); + [Fact] + public async Task PublishesAPackageThroughTheTwoSteps() + { + using var alice = await SignInAsync("alice"); - using var published = await alice.SubmitAsync(token); - var html = await published.Content.ReadAsStringAsync(); + var preview = await StageAsync(alice, "TestData.1.2.3.nupkg", TestResources.GetResourceStream(TestResources.Package)); - Assert.Equal(HttpStatusCode.OK, published.StatusCode); - Assert.Contains("TestData 1.2.3 was published", html); - Assert.True(await ExistsAsync("TestData", "1.2.3")); + // Step one shows what the file contains, and publishes nothing. + Assert.Contains("TestData 1.2.3", preview); + Assert.Contains("Test description", preview); + Assert.Contains("Test author", preview); + Assert.False(await ExistsAsync("TestData", "1.2.3")); - // The package is served, so the upload went through the same pipeline a push does. - using var download = await alice.GetAsync("v3/package/testdata/1.2.3/testdata.1.2.3.nupkg"); - Assert.Equal(HttpStatusCode.OK, download.StatusCode); + var token = BrowserUpload.StagedToken(preview); - // And the staged copy is gone: the token no longer names anything. - using var again = await alice.SubmitAsync(token); - Assert.Equal(HttpStatusCode.NotFound, again.StatusCode); - Assert.Contains(UploadModel.UnknownTokenMessage, await again.Content.ReadAsStringAsync()); - } + using var published = await alice.SubmitAsync(token); + var html = await published.Content.ReadAsStringAsync(); - [Fact] - public async Task ABrandNewIdMakesTheUploaderItsOwner() - { - using var alice = await SignInAsync("alice"); + Assert.Equal(HttpStatusCode.OK, published.StatusCode); + Assert.Contains("TestData 1.2.3 was published", html); + Assert.True(await ExistsAsync("TestData", "1.2.3")); - await PublishAsync(alice, "Alice.New", "1.0.0"); + // The package is served, so the upload went through the same pipeline a push does. + using var download = await alice.GetAsync("v3/package/testdata/1.2.3/testdata.1.2.3.nupkg"); + Assert.Equal(HttpStatusCode.OK, download.StatusCode); - Assert.Equal(new[] { "alice" }, await OwnersAsync("Alice.New")); - } - - [Fact] - public async Task AnIdOwnedByAnotherUserIsRefused() - { - using var alice = await SignInAsync("alice"); - using var bob = await SignInAsync("bob"); + // And the staged copy is gone: the token no longer names anything. + using var again = await alice.SubmitAsync(token); + Assert.Equal(HttpStatusCode.NotFound, again.StatusCode); + Assert.Contains(UploadModel.UnknownTokenMessage, await again.Content.ReadAsStringAsync()); + } - await PublishAsync(alice, "Alice.Package", "1.0.0"); + [Fact] + public async Task ABrandNewIdMakesTheUploaderItsOwner() + { + using var alice = await SignInAsync("alice"); - using var response = await bob.StageAsync("Alice.Package.2.0.0.nupkg", TestPackages.Build("Alice.Package", "2.0.0")); + await PublishAsync(alice, "Alice.New", "1.0.0"); - Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); - Assert.Contains("You may not publish", await response.Content.ReadAsStringAsync()); - Assert.False(await ExistsAsync("Alice.Package", "2.0.0")); - } + Assert.Equal(new[] { "alice" }, await OwnersAsync("Alice.New")); + } - [Fact] - public async Task AnIdClaimedWhileThePreviewWasOpenIsRefusedAtSubmission() - { - using var alice = await SignInAsync("alice"); - using var bob = await SignInAsync("bob"); + [Fact] + public async Task AnIdOwnedByAnotherUserIsRefused() + { + using var alice = await SignInAsync("alice"); + using var bob = await SignInAsync("bob"); - // Nobody owns the ID when Alice stages, so staging is allowed. - var token = BrowserUpload.StagedToken( - await StageAsync(alice, "Race.1.0.0.nupkg", TestPackages.Build("Race", "1.0.0"))); + await PublishAsync(alice, "Alice.Package", "1.0.0"); - // Bob claims it while the preview is on screen. - await PublishAsync(bob, "Race", "0.9.0"); + using var response = await bob.StageAsync("Alice.Package.2.0.0.nupkg", TestPackages.Build("Alice.Package", "2.0.0")); - using var response = await alice.SubmitAsync(token); + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Contains("You may not publish", await response.Content.ReadAsStringAsync()); + Assert.False(await ExistsAsync("Alice.Package", "2.0.0")); + } - Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); - Assert.False(await ExistsAsync("Race", "1.0.0")); - Assert.Equal(new[] { "bob" }, await OwnersAsync("Race")); - } + [Fact] + public async Task AnIdClaimedWhileThePreviewWasOpenIsRefusedAtSubmission() + { + using var alice = await SignInAsync("alice"); + using var bob = await SignInAsync("bob"); - [Fact] - public async Task AnotherUsersTokenIsUnknownAndLeavesTheirUploadAlone() - { - using var alice = await SignInAsync("alice"); - using var bob = await SignInAsync("bob"); + // Nobody owns the ID when Alice stages, so staging is allowed. + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Race.1.0.0.nupkg", TestPackages.Build("Race", "1.0.0"))); - var token = BrowserUpload.StagedToken( - await StageAsync(alice, "Alice.1.0.0.nupkg", TestPackages.Build("Alice.Shared", "1.0.0"))); + // Bob claims it while the preview is on screen. + await PublishAsync(bob, "Race", "0.9.0"); - using var stolen = await bob.SubmitAsync(token); + using var response = await alice.SubmitAsync(token); - Assert.Equal(HttpStatusCode.NotFound, stolen.StatusCode); - Assert.Contains(UploadModel.UnknownTokenMessage, await stolen.Content.ReadAsStringAsync()); - Assert.False(await ExistsAsync("Alice.Shared", "1.0.0")); + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.False(await ExistsAsync("Race", "1.0.0")); + Assert.Equal(new[] { "bob" }, await OwnersAsync("Race")); + } - // Alice's own upload is untouched, so Bob's attempt did not consume it. - using var mine = await alice.SubmitAsync(token); + [Fact] + public async Task AnotherUsersTokenIsUnknownAndLeavesTheirUploadAlone() + { + using var alice = await SignInAsync("alice"); + using var bob = await SignInAsync("bob"); - Assert.Equal(HttpStatusCode.OK, mine.StatusCode); - Assert.True(await ExistsAsync("Alice.Shared", "1.0.0")); - } + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Alice.1.0.0.nupkg", TestPackages.Build("Alice.Shared", "1.0.0"))); - [Fact] - public async Task CancellingMakesTheTokenUnknown() - { - using var alice = await SignInAsync("alice"); + using var stolen = await bob.SubmitAsync(token); - var token = BrowserUpload.StagedToken( - await StageAsync(alice, "Cancelled.1.0.0.nupkg", TestPackages.Build("Cancelled", "1.0.0"))); + Assert.Equal(HttpStatusCode.NotFound, stolen.StatusCode); + Assert.Contains(UploadModel.UnknownTokenMessage, await stolen.Content.ReadAsStringAsync()); + Assert.False(await ExistsAsync("Alice.Shared", "1.0.0")); - using var cancelled = await alice.CancelAsync(token); + // Alice's own upload is untouched, so Bob's attempt did not consume it. + using var mine = await alice.SubmitAsync(token); - Assert.Equal(HttpStatusCode.OK, cancelled.StatusCode); - Assert.Contains("The upload was discarded", await cancelled.Content.ReadAsStringAsync()); + Assert.Equal(HttpStatusCode.OK, mine.StatusCode); + Assert.True(await ExistsAsync("Alice.Shared", "1.0.0")); + } - using var reused = await alice.SubmitAsync(token); + [Fact] + public async Task CancellingMakesTheTokenUnknown() + { + using var alice = await SignInAsync("alice"); - Assert.Equal(HttpStatusCode.NotFound, reused.StatusCode); - Assert.Contains(UploadModel.UnknownTokenMessage, await reused.Content.ReadAsStringAsync()); - Assert.False(await ExistsAsync("Cancelled", "1.0.0")); - } + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Cancelled.1.0.0.nupkg", TestPackages.Build("Cancelled", "1.0.0"))); - [Fact] - public async Task TheSameVersionTwiceIsRefusedWithAMessage() - { - using var alice = await SignInAsync("alice"); + using var cancelled = await alice.CancelAsync(token); - await PublishAsync(alice, "Twice", "1.0.0"); + Assert.Equal(HttpStatusCode.OK, cancelled.StatusCode); + Assert.Contains("The upload was discarded", await cancelled.Content.ReadAsStringAsync()); - var token = BrowserUpload.StagedToken( - await StageAsync(alice, "Twice.1.0.0.nupkg", TestPackages.Build("Twice", "1.0.0"))); + using var reused = await alice.SubmitAsync(token); - using var response = await alice.SubmitAsync(token); - var html = await response.Content.ReadAsStringAsync(); + Assert.Equal(HttpStatusCode.NotFound, reused.StatusCode); + Assert.Contains(UploadModel.UnknownTokenMessage, await reused.Content.ReadAsStringAsync()); + Assert.False(await ExistsAsync("Cancelled", "1.0.0")); + } - Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); - Assert.Contains("Twice 1.0.0 is already on this server", html); + [Fact] + public async Task TheSameVersionTwiceIsRefusedWithAMessage() + { + using var alice = await SignInAsync("alice"); - // A readable sentence, not a stack trace. - Assert.DoesNotContain("BaGet.Core.PackageIndexingService", html); - Assert.DoesNotContain(" at ", html); - } + await PublishAsync(alice, "Twice", "1.0.0"); - [Fact] - public async Task TheTermsMustBeAcceptedAndTheUploadSurvivesRefusing() - { - using var alice = await SignInAsync("alice"); + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Twice.1.0.0.nupkg", TestPackages.Build("Twice", "1.0.0"))); - var token = BrowserUpload.StagedToken( - await StageAsync(alice, "Terms.1.0.0.nupkg", TestPackages.Build("Terms", "1.0.0"))); + using var response = await alice.SubmitAsync(token); + var html = await response.Content.ReadAsStringAsync(); - using var refused = await alice.SubmitAsync(token, acceptTerms: false); + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + Assert.Contains("Twice 1.0.0 is already on this server", html); - Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode); - Assert.Contains(UploadModel.TermsMessage, await refused.Content.ReadAsStringAsync()); - Assert.False(await ExistsAsync("Terms", "1.0.0")); + // A readable sentence, not a stack trace. + Assert.DoesNotContain("BaGet.Core.PackageIndexingService", html); + Assert.DoesNotContain(" at ", html); + } - // The preview is still there, so ticking the box is all that is needed. - using var accepted = await alice.SubmitAsync(token); + [Fact] + public async Task TheTermsMustBeAcceptedAndTheUploadSurvivesRefusing() + { + using var alice = await SignInAsync("alice"); - Assert.Equal(HttpStatusCode.OK, accepted.StatusCode); - Assert.True(await ExistsAsync("Terms", "1.0.0")); - } + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Terms.1.0.0.nupkg", TestPackages.Build("Terms", "1.0.0"))); - [Fact] - public async Task SymbolsArePublishedForAVersionThatExists() - { - using var alice = await SignInAsync("alice"); + using var refused = await alice.SubmitAsync(token, acceptTerms: false); - var packageToken = BrowserUpload.StagedToken( - await StageAsync(alice, "TestData.1.2.3.nupkg", TestResources.GetResourceStream(TestResources.Package))); - using (var published = await alice.SubmitAsync(packageToken)) - { - Assert.Equal(HttpStatusCode.OK, published.StatusCode); - } + Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode); + Assert.Contains(UploadModel.TermsMessage, await refused.Content.ReadAsStringAsync()); + Assert.False(await ExistsAsync("Terms", "1.0.0")); - var preview = await StageAsync( - alice, - "TestData.1.2.3.snupkg", - TestResources.GetResourceStream(TestResources.SymbolPackage)); + // The preview is still there, so ticking the box is all that is needed. + using var accepted = await alice.SubmitAsync(token); - // Symbols carry no metadata, so the preview reports the PDBs it found. - Assert.Contains("TestData.pdb", preview); + Assert.Equal(HttpStatusCode.OK, accepted.StatusCode); + Assert.True(await ExistsAsync("Terms", "1.0.0")); + } - using var response = await alice.SubmitAsync(BrowserUpload.StagedToken(preview)); + [Fact] + public async Task SymbolsArePublishedForAVersionThatExists() + { + using var alice = await SignInAsync("alice"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("symbols for TestData 1.2.3 were published", await response.Content.ReadAsStringAsync()); + var packageToken = BrowserUpload.StagedToken( + await StageAsync(alice, "TestData.1.2.3.nupkg", TestResources.GetResourceStream(TestResources.Package))); + using (var published = await alice.SubmitAsync(packageToken)) + { + Assert.Equal(HttpStatusCode.OK, published.StatusCode); } - [Fact] - public async Task SymbolsForAVersionThatDoesNotExistAreRefusedAndClaimNothing() - { - using var alice = await SignInAsync("alice"); + var preview = await StageAsync( + alice, + "TestData.1.2.3.snupkg", + TestResources.GetResourceStream(TestResources.SymbolPackage)); - var preview = await StageAsync( - alice, - "TestData.1.2.3.snupkg", - TestResources.GetResourceStream(TestResources.SymbolPackage)); + // Symbols carry no metadata, so the preview reports the PDBs it found. + Assert.Contains("TestData.pdb", preview); - // Said at step one, rather than letting the upload be confirmed and then fail. - Assert.Contains("Push TestData 1.2.3 first", preview); + using var response = await alice.SubmitAsync(BrowserUpload.StagedToken(preview)); - using var response = await alice.SubmitAsync(BrowserUpload.StagedToken(preview)); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("symbols for TestData 1.2.3 were published", await response.Content.ReadAsStringAsync()); + } - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - Assert.Contains( - "Symbols can only be uploaded for a package version already on this server", - await response.Content.ReadAsStringAsync()); + [Fact] + public async Task SymbolsForAVersionThatDoesNotExistAreRefusedAndClaimNothing() + { + using var alice = await SignInAsync("alice"); - // A symbol upload is never a first upload: it creates no package and no owner. - Assert.False(await ExistsAsync("TestData", "1.2.3")); - Assert.Empty(await OwnersAsync("TestData")); - } + var preview = await StageAsync( + alice, + "TestData.1.2.3.snupkg", + TestResources.GetResourceStream(TestResources.SymbolPackage)); - [Fact] - public async Task AnotherUsersTokenCannotDiscardTheirUpload() - { - using var alice = await SignInAsync("alice"); - using var bob = await SignInAsync("bob"); + // Said at step one, rather than letting the upload be confirmed and then fail. + Assert.Contains("Push TestData 1.2.3 first", preview); - var token = BrowserUpload.StagedToken( - await StageAsync(alice, "Alice.1.0.0.nupkg", TestPackages.Build("Alice.Discard", "1.0.0"))); + using var response = await alice.SubmitAsync(BrowserUpload.StagedToken(preview)); - using (var stolen = await bob.CancelAsync(token)) - { - // Indistinguishable from a token that never existed, as submitting is. - Assert.Equal(HttpStatusCode.NotFound, stolen.StatusCode); - Assert.Contains(UploadModel.UnknownTokenMessage, await stolen.Content.ReadAsStringAsync()); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Contains( + "Symbols can only be uploaded for a package version already on this server", + await response.Content.ReadAsStringAsync()); - // Alice's upload is untouched, so Bob could not make her upload the file again. - using var mine = await alice.SubmitAsync(token); + // A symbol upload is never a first upload: it creates no package and no owner. + Assert.False(await ExistsAsync("TestData", "1.2.3")); + Assert.Empty(await OwnersAsync("TestData")); + } - Assert.Equal(HttpStatusCode.OK, mine.StatusCode); - Assert.True(await ExistsAsync("Alice.Discard", "1.0.0")); - } + [Fact] + public async Task AnotherUsersTokenCannotDiscardTheirUpload() + { + using var alice = await SignInAsync("alice"); + using var bob = await SignInAsync("bob"); - [Fact] - public async Task AnAnonymousVisitorCannotDiscardAStagedUpload() + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Alice.1.0.0.nupkg", TestPackages.Build("Alice.Discard", "1.0.0"))); + + using (var stolen = await bob.CancelAsync(token)) { - using var alice = await SignInAsync("alice"); - using var anonymous = new Browser(_app); + // Indistinguishable from a token that never existed, as submitting is. + Assert.Equal(HttpStatusCode.NotFound, stolen.StatusCode); + Assert.Contains(UploadModel.UnknownTokenMessage, await stolen.Content.ReadAsStringAsync()); + } - var token = BrowserUpload.StagedToken( - await StageAsync(alice, "Alice.1.0.0.nupkg", TestPackages.Build("Alice.Anonymous", "1.0.0"))); + // Alice's upload is untouched, so Bob could not make her upload the file again. + using var mine = await alice.SubmitAsync(token); - using (var attempt = await anonymous.PostAsync( - "upload", - new Dictionary { { "token", token } }, - "upload?handler=Cancel", - BrowserUpload.TokenPage)) - { - Assert.Equal(HttpStatusCode.Unauthorized, attempt.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, mine.StatusCode); + Assert.True(await ExistsAsync("Alice.Discard", "1.0.0")); + } - using var mine = await alice.SubmitAsync(token); + [Fact] + public async Task AnAnonymousVisitorCannotDiscardAStagedUpload() + { + using var alice = await SignInAsync("alice"); + using var anonymous = new Browser(_app); - Assert.Equal(HttpStatusCode.OK, mine.StatusCode); - Assert.True(await ExistsAsync("Alice.Anonymous", "1.0.0")); - } + var token = BrowserUpload.StagedToken( + await StageAsync(alice, "Alice.1.0.0.nupkg", TestPackages.Build("Alice.Anonymous", "1.0.0"))); - [Fact] - public async Task AFileNamedSnupkgThatIsNotASymbolPackageIsRefused() + using (var attempt = await anonymous.PostAsync( + "upload", + new Dictionary { { "token", token } }, + "upload?handler=Cancel", + BrowserUpload.TokenPage)) { - using var alice = await SignInAsync("alice"); - - // The content decides the pipeline, so a symbols file name over package content - // must not be published as a package under that ID - the symbol endpoint would - // read the very same bytes as symbols. - using var response = await alice.StageAsync( - "NotSymbols.1.0.0.snupkg", - TestPackages.Build("NotSymbols", "1.0.0")); - var html = await response.Content.ReadAsStringAsync(); - - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.Contains("SymbolsPackage", html); - Assert.False(await ExistsAsync("NotSymbols", "1.0.0")); + Assert.Equal(HttpStatusCode.Unauthorized, attempt.StatusCode); } - [Fact] - public async Task AnAnonymousVisitorIsAskedToSignIn() - { - using var anonymous = new Browser(_app); + using var mine = await alice.SubmitAsync(token); - var html = await anonymous.GetPageAsync("upload"); + Assert.Equal(HttpStatusCode.OK, mine.StatusCode); + Assert.True(await ExistsAsync("Alice.Anonymous", "1.0.0")); + } - // Anonymous visitors are sent to sign in rather than shown a form that could only - // fail, and the push instructions stay. - Assert.Contains("account/login", html); - Assert.DoesNotContain("name=\"package\"", html); - Assert.Contains("dotnet nuget push", html); - } + [Fact] + public async Task AFileNamedSnupkgThatIsNotASymbolPackageIsRefused() + { + using var alice = await SignInAsync("alice"); + + // The content decides the pipeline, so a symbols file name over package content + // must not be published as a package under that ID - the symbol endpoint would + // read the very same bytes as symbols. + using var response = await alice.StageAsync( + "NotSymbols.1.0.0.snupkg", + TestPackages.Build("NotSymbols", "1.0.0")); + var html = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Contains("SymbolsPackage", html); + Assert.False(await ExistsAsync("NotSymbols", "1.0.0")); + } - private async Task SignInAsync(string userName) - { - var browser = new Browser(_app); - await browser.RegisterAsync(userName); + [Fact] + public async Task AnAnonymousVisitorIsAskedToSignIn() + { + using var anonymous = new Browser(_app); - return browser; - } + var html = await anonymous.GetPageAsync("upload"); - private static async Task StageAsync(Browser browser, string fileName, Stream file) - { - using var response = await browser.StageAsync(fileName, file); - var html = await response.Content.ReadAsStringAsync(); + // Anonymous visitors are sent to sign in rather than shown a form that could only + // fail, and the push instructions stay. + Assert.Contains("account/login", html); + Assert.DoesNotContain("name=\"package\"", html); + Assert.Contains("dotnet nuget push", html); + } - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + private async Task SignInAsync(string userName) + { + var browser = new Browser(_app); + await browser.RegisterAsync(userName); - return html; - } + return browser; + } - private static async Task PublishAsync(Browser browser, string id, string version) - { - var token = BrowserUpload.StagedToken( - await StageAsync(browser, $"{id}.{version}.nupkg", TestPackages.Build(id, version))); + private static async Task StageAsync(Browser browser, string fileName, Stream file) + { + using var response = await browser.StageAsync(fileName, file); + var html = await response.Content.ReadAsStringAsync(); - using var response = await browser.SubmitAsync(token); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + return html; + } - private async Task ExistsAsync(string id, string version) - { - using var scope = _app.Services.CreateScope(); - var packages = scope.ServiceProvider.GetRequiredService(); + private static async Task PublishAsync(Browser browser, string id, string version) + { + var token = BrowserUpload.StagedToken( + await StageAsync(browser, $"{id}.{version}.nupkg", TestPackages.Build(id, version))); - return await packages.ExistsAsync(id, NuGet.Versioning.NuGetVersion.Parse(version), CancellationToken.None); - } + using var response = await browser.SubmitAsync(token); - private async Task> OwnersAsync(string id) - { - using var scope = _app.Services.CreateScope(); - var ownership = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - return (await ownership.GetOwnersAsync(id, CancellationToken.None)) - .Select(o => o.OwnerName) - .ToList(); - } + private async Task ExistsAsync(string id, string version) + { + using var scope = _app.Services.CreateScope(); + var packages = scope.ServiceProvider.GetRequiredService(); - public void Dispose() => _app.Dispose(); + return await packages.ExistsAsync(id, NuGet.Versioning.NuGetVersion.Parse(version), CancellationToken.None); } - /// - /// The browser upload with accounts off: there is no user to own an upload, so the pusher - /// proves itself with the same API key the push endpoint requires. The page must not 404 - /// here - it is not an account page. - /// - public class BrowserUploadWithoutAccountsTests : IDisposable + private async Task> OwnersAsync(string id) { - private const string GlobalKey = "global-key"; + using var scope = _app.Services.CreateScope(); + var ownership = scope.ServiceProvider.GetRequiredService(); - private readonly BaGetApplication _app; + return (await ownership.GetOwnersAsync(id, CancellationToken.None)) + .Select(o => o.OwnerName) + .ToList(); + } - public BrowserUploadWithoutAccountsTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "ApiKey", GlobalKey }, - }); - } + public void Dispose() => _app.Dispose(); +} - [Fact] - public async Task ThePageOffersTheFormAndNeverAnswersNotFound() +/// +/// The browser upload with accounts off: there is no user to own an upload, so the pusher +/// proves itself with the same API key the push endpoint requires. The page must not 404 +/// here - it is not an account page. +/// +public class BrowserUploadWithoutAccountsTests : IDisposable +{ + private const string GlobalKey = "global-key"; + + private readonly BaGetApplication _app; + + public BrowserUploadWithoutAccountsTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary { - using var browser = new Browser(_app); + { "ApiKey", GlobalKey }, + }); + } - using var response = await browser.GetAsync("upload"); - var html = await response.Content.ReadAsStringAsync(); + [Fact] + public async Task ThePageOffersTheFormAndNeverAnswersNotFound() + { + using var browser = new Browser(_app); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("name=\"package\"", html); - Assert.Contains("name=\"apiKey\"", html); - } + using var response = await browser.GetAsync("upload"); + var html = await response.Content.ReadAsStringAsync(); - [Fact] - public async Task TheRightApiKeyPublishes() - { - using var browser = new Browser(_app); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("name=\"package\"", html); + Assert.Contains("name=\"apiKey\"", html); + } - using var staged = await browser.StageAsync( - "TestData.1.2.3.nupkg", - TestResources.GetResourceStream(TestResources.Package), - GlobalKey); - var preview = await staged.Content.ReadAsStringAsync(); + [Fact] + public async Task TheRightApiKeyPublishes() + { + using var browser = new Browser(_app); - Assert.Equal(HttpStatusCode.OK, staged.StatusCode); + using var staged = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + GlobalKey); + var preview = await staged.Content.ReadAsStringAsync(); - using var published = await browser.SubmitAsync(BrowserUpload.StagedToken(preview), apiKey: GlobalKey); + Assert.Equal(HttpStatusCode.OK, staged.StatusCode); - Assert.Equal(HttpStatusCode.OK, published.StatusCode); - Assert.Contains("TestData 1.2.3 was published", await published.Content.ReadAsStringAsync()); - } + using var published = await browser.SubmitAsync(BrowserUpload.StagedToken(preview), apiKey: GlobalKey); - [Fact] - public async Task TheWrongApiKeyIsRefusedWithoutStagingAnything() - { - using var browser = new Browser(_app); - - using var response = await browser.StageAsync( - "TestData.1.2.3.nupkg", - TestResources.GetResourceStream(TestResources.Package), - "not-the-key"); - var html = await response.Content.ReadAsStringAsync(); - - // 401, and not the 404 an account page would answer with accounts disabled. - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Contains(UploadModel.ApiKeyRejectedMessage, html); - Assert.DoesNotMatch("name=\"token\" value=\"[0-9a-f]{32}\"", html); - } + Assert.Equal(HttpStatusCode.OK, published.StatusCode); + Assert.Contains("TestData 1.2.3 was published", await published.Content.ReadAsStringAsync()); + } - [Fact] - public async Task TheApiKeyIsNeverWrittenIntoThePage() - { - using var browser = new Browser(_app); + [Fact] + public async Task TheWrongApiKeyIsRefusedWithoutStagingAnything() + { + using var browser = new Browser(_app); + + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + "not-the-key"); + var html = await response.Content.ReadAsStringAsync(); + + // 401, and not the 404 an account page would answer with accounts disabled. + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Contains(UploadModel.ApiKeyRejectedMessage, html); + Assert.DoesNotMatch("name=\"token\" value=\"[0-9a-f]{32}\"", html); + } - using var staged = await browser.StageAsync( - "TestData.1.2.3.nupkg", - TestResources.GetResourceStream(TestResources.Package), - GlobalKey); - var html = await staged.Content.ReadAsStringAsync(); + [Fact] + public async Task TheApiKeyIsNeverWrittenIntoThePage() + { + using var browser = new Browser(_app); - // Asserted first: a refusal's body carries no API key either, so without this the - // test would stay green against an upload page that never previewed anything. - Assert.Equal(HttpStatusCode.OK, staged.StatusCode); - BrowserUpload.StagedToken(html); + using var staged = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + GlobalKey); + var html = await staged.Content.ReadAsStringAsync(); - // The preview asks for the key again rather than carrying it in a hidden field. - Assert.DoesNotContain(GlobalKey, html); - } + // Asserted first: a refusal's body carries no API key either, so without this the + // test would stay green against an upload page that never previewed anything. + Assert.Equal(HttpStatusCode.OK, staged.StatusCode); + BrowserUpload.StagedToken(html); - public void Dispose() => _app.Dispose(); + // The preview asks for the key again rather than carrying it in a hidden field. + Assert.DoesNotContain(GlobalKey, html); } - /// - /// Read-only mode refuses both modes of the page, as the push endpoint does. - /// - public class BrowserUploadReadOnlyTests - { - private readonly ITestOutputHelper _output; + public void Dispose() => _app.Dispose(); +} - public BrowserUploadReadOnlyTests(ITestOutputHelper output) - { - _output = output; - } +/// +/// Read-only mode refuses both modes of the page, as the push endpoint does. +/// +public class BrowserUploadReadOnlyTests +{ + private readonly ITestOutputHelper _output; - [Fact] - public async Task TheApiKeyModeIsRefused() - { - using var app = Application(accounts: false); - using var browser = new Browser(app); + public BrowserUploadReadOnlyTests(ITestOutputHelper output) + { + _output = output; + } - using var response = await browser.StageAsync( - "TestData.1.2.3.nupkg", - TestResources.GetResourceStream(TestResources.Package), - "global-key", - BrowserUpload.TokenPage); + [Fact] + public async Task TheApiKeyModeIsRefused() + { + using var app = Application(accounts: false); + using var browser = new Browser(app); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Contains(UploadModel.ReadOnlyMessage, await response.Content.ReadAsStringAsync()); - } + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + "global-key", + BrowserUpload.TokenPage); - [Fact] - public async Task ASignedInSessionIsRefused() - { - using var app = Application(accounts: true); - using var browser = new Browser(app); - await browser.RegisterAsync("alice"); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Contains(UploadModel.ReadOnlyMessage, await response.Content.ReadAsStringAsync()); + } - using var response = await browser.StageAsync( - "TestData.1.2.3.nupkg", - TestResources.GetResourceStream(TestResources.Package), - tokenPage: BrowserUpload.TokenPage); + [Fact] + public async Task ASignedInSessionIsRefused() + { + using var app = Application(accounts: true); + using var browser = new Browser(app); + await browser.RegisterAsync("alice"); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Contains(UploadModel.ReadOnlyMessage, await response.Content.ReadAsStringAsync()); - } + using var response = await browser.StageAsync( + "TestData.1.2.3.nupkg", + TestResources.GetResourceStream(TestResources.Package), + tokenPage: BrowserUpload.TokenPage); - [Fact] - public async Task ThePushInstructionsAreNotOfferedWhilePushingIsRefused() - { - using var app = Application(accounts: false); - using var browser = new Browser(app); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Contains(UploadModel.ReadOnlyMessage, await response.Content.ReadAsStringAsync()); + } - var html = await browser.GetPageAsync("upload"); + [Fact] + public async Task ThePushInstructionsAreNotOfferedWhilePushingIsRefused() + { + using var app = Application(accounts: false); + using var browser = new Browser(app); - // The page must not refuse an upload and then hand out commands that answer 401. - Assert.Contains("upload-read-only", html); - Assert.DoesNotContain("You can push packages using the service index", html); - Assert.DoesNotContain("nuget push -Source", html); - } + var html = await browser.GetPageAsync("upload"); - private BaGetApplication Application(bool accounts) - => new BaGetApplication(_output, configOverrides: new Dictionary - { - { "ApiKey", "global-key" }, - { "IsReadOnlyMode", "true" }, - { "Accounts:Enabled", accounts ? "true" : "false" }, - }); + // The page must not refuse an upload and then hand out commands that answer 401. + Assert.Contains("upload-read-only", html); + Assert.DoesNotContain("You can push packages using the service index", html); + Assert.DoesNotContain("nuget push -Source", html); } -} + + private BaGetApplication Application(bool accounts) + => new BaGetApplication(_output, configOverrides: new Dictionary + { + { "ApiKey", "global-key" }, + { "IsReadOnlyMode", "true" }, + { "Accounts:Enabled", accounts ? "true" : "false" }, + }); +} \ No newline at end of file diff --git a/tests/BaGet.Tests/CatalogIntegrationTests.cs b/tests/BaGet.Tests/CatalogIntegrationTests.cs index 5e9dffb05..d6581ec29 100644 --- a/tests/BaGet.Tests/CatalogIntegrationTests.cs +++ b/tests/BaGet.Tests/CatalogIntegrationTests.cs @@ -17,201 +17,200 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// The catalog, read back both raw and through BaGet.Protocol's own catalog processor, +/// which is how a mirror consumes it. +/// +public class CatalogIntegrationTests : IDisposable { - /// - /// The catalog, read back both raw and through BaGet.Protocol's own catalog processor, - /// which is how a mirror consumes it. - /// - public class CatalogIntegrationTests : IDisposable - { - private readonly BaGetApplication _app; - private readonly HttpClient _client; - private readonly Stream _packageStream; + private readonly BaGetApplication _app; + private readonly HttpClient _client; + private readonly Stream _packageStream; - public CatalogIntegrationTests(ITestOutputHelper output) + public CatalogIntegrationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "PackageDeletionBehavior", "HardDelete" }, - }); - _client = _app.CreateClient(); - _packageStream = TestResources.GetResourceStream(TestResources.Package); - } + { "PackageDeletionBehavior", "HardDelete" }, + }); + _client = _app.CreateClient(); + _packageStream = TestResources.GetResourceStream(TestResources.Package); + } - [Fact] - public async Task TheServiceIndexAdvertisesTheCatalog() - { - var index = await new NuGetClientFactory(_client, "http://localhost/v3/index.json") - .CreateServiceIndexClient() - .GetAsync(); + [Fact] + public async Task TheServiceIndexAdvertisesTheCatalog() + { + var index = await new NuGetClientFactory(_client, "http://localhost/v3/index.json") + .CreateServiceIndexClient() + .GetAsync(); - Assert.Equal( - "http://localhost/v3/catalog/index.json", - index.Resources.Single(r => r.Type == "Catalog/3.0.0").ResourceUrl); - } + Assert.Equal( + "http://localhost/v3/catalog/index.json", + index.Resources.Single(r => r.Type == "Catalog/3.0.0").ResourceUrl); + } - [Fact] - public async Task AnEmptyCatalogHasNoPages() - { - using var index = await GetJsonAsync("v3/catalog/index.json"); + [Fact] + public async Task AnEmptyCatalogHasNoPages() + { + using var index = await GetJsonAsync("v3/catalog/index.json"); - Assert.Equal(0, index.RootElement.GetProperty("count").GetInt32()); - Assert.Empty(index.RootElement.GetProperty("items").EnumerateArray()); - } + Assert.Equal(0, index.RootElement.GetProperty("count").GetInt32()); + Assert.Empty(index.RootElement.GetProperty("items").EnumerateArray()); + } - [Fact] - public async Task APushAppendsADetailsLeaf() - { - await _app.AddPackageAsync(_packageStream); - - var leaves = await ProcessCatalogAsync(); - - var leaf = Assert.IsType(Assert.Single(leaves)); - Assert.Equal("TestData", leaf.PackageId); - Assert.Equal("1.2.3", leaf.PackageVersion); - Assert.True(leaf.Listed); - Assert.Equal("SHA512", leaf.PackageHashAlgorithm); - Assert.False(string.IsNullOrEmpty(leaf.PackageHash)); - Assert.True(leaf.PackageSize > 0); - Assert.StartsWith("http://localhost/v3/catalog/data/", leaf.CatalogLeafUrl); - } + [Fact] + public async Task APushAppendsADetailsLeaf() + { + await _app.AddPackageAsync(_packageStream); + + var leaves = await ProcessCatalogAsync(); + + var leaf = Assert.IsType(Assert.Single(leaves)); + Assert.Equal("TestData", leaf.PackageId); + Assert.Equal("1.2.3", leaf.PackageVersion); + Assert.True(leaf.Listed); + Assert.Equal("SHA512", leaf.PackageHashAlgorithm); + Assert.False(string.IsNullOrEmpty(leaf.PackageHash)); + Assert.True(leaf.PackageSize > 0); + Assert.StartsWith("http://localhost/v3/catalog/data/", leaf.CatalogLeafUrl); + } + + [Fact] + public async Task ADeleteAppendsADeleteLeafAfterTheDetails() + { + await _app.AddPackageAsync(_packageStream); - [Fact] - public async Task ADeleteAppendsADeleteLeafAfterTheDetails() + using (var delete = await _client.DeleteAsync("api/v2/package/TestData/1.2.3")) { - await _app.AddPackageAsync(_packageStream); + Assert.Equal(HttpStatusCode.NoContent, delete.StatusCode); + } - using (var delete = await _client.DeleteAsync("api/v2/package/TestData/1.2.3")) - { - Assert.Equal(HttpStatusCode.NoContent, delete.StatusCode); - } + var leaves = await ProcessCatalogAsync(); - var leaves = await ProcessCatalogAsync(); + Assert.Collection( + leaves, + l => Assert.IsType(l), + l => Assert.Equal("TestData", Assert.IsType(l).PackageId)); + } - Assert.Collection( - leaves, - l => Assert.IsType(l), - l => Assert.Equal("TestData", Assert.IsType(l).PackageId)); + [Fact] + public async Task CommitTimestampsStrictlyIncreaseEvenWhenTheClockDoesNot() + { + // The test host's clock is frozen, which is the worst case for a cursor. + await _app.AddPackageAsync(_packageStream); + using (var relist = await _client.PostAsync("api/v2/package/TestData/1.2.3", content: null)) + { + Assert.Equal(HttpStatusCode.OK, relist.StatusCode); } - [Fact] - public async Task CommitTimestampsStrictlyIncreaseEvenWhenTheClockDoesNot() - { - // The test host's clock is frozen, which is the worst case for a cursor. - await _app.AddPackageAsync(_packageStream); - using (var relist = await _client.PostAsync("api/v2/package/TestData/1.2.3", content: null)) - { - Assert.Equal(HttpStatusCode.OK, relist.StatusCode); - } + using var index = await GetJsonAsync("v3/catalog/index.json"); + using var page = await GetJsonAsync(index.RootElement.GetProperty("items")[0].GetProperty("@id").GetString()); - using var index = await GetJsonAsync("v3/catalog/index.json"); - using var page = await GetJsonAsync(index.RootElement.GetProperty("items")[0].GetProperty("@id").GetString()); + var timestamps = page.RootElement.GetProperty("items") + .EnumerateArray() + .Select(i => i.GetProperty("commitTimeStamp").GetDateTimeOffset()) + .ToList(); - var timestamps = page.RootElement.GetProperty("items") - .EnumerateArray() - .Select(i => i.GetProperty("commitTimeStamp").GetDateTimeOffset()) - .ToList(); + Assert.Equal(2, timestamps.Count); + Assert.True(timestamps[1] > timestamps[0]); + } - Assert.Equal(2, timestamps.Count); - Assert.True(timestamps[1] > timestamps[0]); + [Fact] + public async Task RebuildBackfillsAPackageWithNoEntry() + { + await _app.AddPackageAsync(_packageStream); + + using (var scope = _app.Services.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + context.CatalogLeafs.RemoveRange(context.CatalogLeafs); + await context.SaveChangesAsync(CancellationToken.None); } - [Fact] - public async Task RebuildBackfillsAPackageWithNoEntry() + (int Added, int Deleted) result; + using (var scope = _app.Services.CreateScope()) { - await _app.AddPackageAsync(_packageStream); + result = await scope.ServiceProvider.GetRequiredService().RebuildAsync(CancellationToken.None); + } - using (var scope = _app.Services.CreateScope()) - { - var context = scope.ServiceProvider.GetRequiredService(); - context.CatalogLeafs.RemoveRange(context.CatalogLeafs); - await context.SaveChangesAsync(CancellationToken.None); - } + Assert.Equal((1, 0), result); + Assert.IsType(Assert.Single(await ProcessCatalogAsync())); + } - (int Added, int Deleted) result; - using (var scope = _app.Services.CreateScope()) - { - result = await scope.ServiceProvider.GetRequiredService().RebuildAsync(CancellationToken.None); - } + [Fact] + public async Task RebuildIsANoOpWhenTheCatalogIsComplete() + { + await _app.AddPackageAsync(_packageStream); - Assert.Equal((1, 0), result); - Assert.IsType(Assert.Single(await ProcessCatalogAsync())); - } + using var scope = _app.Services.CreateScope(); + var result = await scope.ServiceProvider.GetRequiredService().RebuildAsync(CancellationToken.None); - [Fact] - public async Task RebuildIsANoOpWhenTheCatalogIsComplete() - { - await _app.AddPackageAsync(_packageStream); + Assert.Equal((0, 0), result); + } - using var scope = _app.Services.CreateScope(); - var result = await scope.ServiceProvider.GetRequiredService().RebuildAsync(CancellationToken.None); + [Theory] + [InlineData("v3/catalog/page0.json")] + [InlineData("v3/catalog/data/not-a-commit.json")] + [InlineData("v3/catalog/data/00000000-0000-0000-0000-000000000000.json")] + public async Task AMissingDocumentIsNotFound(string url) + { + using var response = await _client.GetAsync(url); - Assert.Equal((0, 0), result); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - [Theory] - [InlineData("v3/catalog/page0.json")] - [InlineData("v3/catalog/data/not-a-commit.json")] - [InlineData("v3/catalog/data/00000000-0000-0000-0000-000000000000.json")] - public async Task AMissingDocumentIsNotFound(string url) - { - using var response = await _client.GetAsync(url); + private async Task> ProcessCatalogAsync() + { + var factory = new NuGetClientFactory(_client, "http://localhost/v3/index.json"); + var processor = new RecordingLeafProcessor(); + + var catalog = new CatalogProcessor( + new NullCursor(), + factory.CreateCatalogClient(), + processor, + new CatalogProcessorOptions + { + MinCommitTimestamp = DateTimeOffset.MinValue, + MaxCommitTimestamp = DateTimeOffset.MaxValue, + }, + NullLogger.Instance); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.True(await catalog.ProcessAsync()); - private async Task> ProcessCatalogAsync() - { - var factory = new NuGetClientFactory(_client, "http://localhost/v3/index.json"); - var processor = new RecordingLeafProcessor(); - - var catalog = new CatalogProcessor( - new NullCursor(), - factory.CreateCatalogClient(), - processor, - new CatalogProcessorOptions - { - MinCommitTimestamp = DateTimeOffset.MinValue, - MaxCommitTimestamp = DateTimeOffset.MaxValue, - }, - NullLogger.Instance); - - Assert.True(await catalog.ProcessAsync()); - - return processor.Leaves; - } + return processor.Leaves; + } - private async Task GetJsonAsync(string url) - { - using var response = await _client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + private async Task GetJsonAsync(string url) + { + using var response = await _client.GetAsync(url); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); - return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - } + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + } - public void Dispose() + public void Dispose() + { + _app.Dispose(); + _client.Dispose(); + _packageStream.Dispose(); + } + + private class RecordingLeafProcessor : ICatalogLeafProcessor + { + public List Leaves { get; } = new List(); + + public Task ProcessPackageDetailsAsync(PackageDetailsCatalogLeaf leaf, CancellationToken cancellationToken = default) { - _app.Dispose(); - _client.Dispose(); - _packageStream.Dispose(); + Leaves.Add(leaf); + return Task.FromResult(true); } - private class RecordingLeafProcessor : ICatalogLeafProcessor + public Task ProcessPackageDeleteAsync(PackageDeleteCatalogLeaf leaf, CancellationToken cancellationToken = default) { - public List Leaves { get; } = new List(); - - public Task ProcessPackageDetailsAsync(PackageDetailsCatalogLeaf leaf, CancellationToken cancellationToken = default) - { - Leaves.Add(leaf); - return Task.FromResult(true); - } - - public Task ProcessPackageDeleteAsync(PackageDeleteCatalogLeaf leaf, CancellationToken cancellationToken = default) - { - Leaves.Add(leaf); - return Task.FromResult(true); - } + Leaves.Add(leaf); + return Task.FromResult(true); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/CatalogWriterTests.cs b/tests/BaGet.Tests/CatalogWriterTests.cs index c0af219b4..585afd119 100644 --- a/tests/BaGet.Tests/CatalogWriterTests.cs +++ b/tests/BaGet.Tests/CatalogWriterTests.cs @@ -2,50 +2,49 @@ using BaGet.Catalog; using Xunit; -namespace BaGet.Tests +namespace BaGet.Tests; + +public class CatalogWriterTests { - public class CatalogWriterTests + private static readonly DateTime Now = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + [Fact] + public void TheFirstCommitIsNow() + { + Assert.Equal(Now, CatalogWriter.NextTimestamp(Now, last: null)); + } + + [Fact] + public void TruncatesToMilliseconds() + { + // Every provider stores a millisecond exactly; not every one stores a tick. + var next = CatalogWriter.NextTimestamp(Now.AddTicks(12345), last: null); + + Assert.Equal(Now.AddMilliseconds(1), next); + Assert.Equal(DateTimeKind.Utc, next.Kind); + } + + [Fact] + public void IsLaterThanTheLastCommitWhenTheClockHasNotMoved() + { + Assert.Equal(Now.AddMilliseconds(1), CatalogWriter.NextTimestamp(Now, last: Now)); + } + + [Fact] + public void IsLaterThanTheLastCommitWhenTheClockWentBack() + { + var last = Now.AddMinutes(5); + + Assert.Equal(last.AddMilliseconds(1), CatalogWriter.NextTimestamp(Now, last)); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(1, 1)] + [InlineData(500, 1)] + [InlineData(501, 2)] + public void PageCountRoundsUp(int entries, int pages) { - private static readonly DateTime Now = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); - - [Fact] - public void TheFirstCommitIsNow() - { - Assert.Equal(Now, CatalogWriter.NextTimestamp(Now, last: null)); - } - - [Fact] - public void TruncatesToMilliseconds() - { - // Every provider stores a millisecond exactly; not every one stores a tick. - var next = CatalogWriter.NextTimestamp(Now.AddTicks(12345), last: null); - - Assert.Equal(Now.AddMilliseconds(1), next); - Assert.Equal(DateTimeKind.Utc, next.Kind); - } - - [Fact] - public void IsLaterThanTheLastCommitWhenTheClockHasNotMoved() - { - Assert.Equal(Now.AddMilliseconds(1), CatalogWriter.NextTimestamp(Now, last: Now)); - } - - [Fact] - public void IsLaterThanTheLastCommitWhenTheClockWentBack() - { - var last = Now.AddMinutes(5); - - Assert.Equal(last.AddMilliseconds(1), CatalogWriter.NextTimestamp(Now, last)); - } - - [Theory] - [InlineData(0, 0)] - [InlineData(1, 1)] - [InlineData(500, 1)] - [InlineData(501, 2)] - public void PageCountRoundsUp(int entries, int pages) - { - Assert.Equal(pages, CatalogReader.PageCount(entries)); - } + Assert.Equal(pages, CatalogReader.PageCount(entries)); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/DatabaseSearchServiceTests.cs b/tests/BaGet.Tests/DatabaseSearchServiceTests.cs index 86702f571..ef299d842 100644 --- a/tests/BaGet.Tests/DatabaseSearchServiceTests.cs +++ b/tests/BaGet.Tests/DatabaseSearchServiceTests.cs @@ -11,355 +11,354 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Tests against a real SQLite database, so that the +/// queries under test are the ones a running BaGet would execute. +/// +public class DatabaseSearchServiceTests : IDisposable { - /// - /// Tests against a real SQLite database, so that the - /// queries under test are the ones a running BaGet would execute. - /// - public class DatabaseSearchServiceTests : IDisposable + private readonly SqliteConnection _connection; + private readonly SqliteContext _context; + private readonly DatabaseSearchService _target; + private readonly CancellationToken _cancellationToken = CancellationToken.None; + + public DatabaseSearchServiceTests() + { + // An in-memory SQLite database lives as long as its connection, so the connection + // is held open for the lifetime of the test. + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + + var options = new DbContextOptionsBuilder() + .UseSqlite(_connection) + .Options; + + _context = new SqliteContext(options); + _context.Database.Migrate(); + + _target = new DatabaseSearchService( + _context, + new FrameworkCompatibilityService(), + new SearchResponseBuilder(Mock.Of())); + } + + public class SearchAsync : DatabaseSearchServiceTests { - private readonly SqliteConnection _connection; - private readonly SqliteContext _context; - private readonly DatabaseSearchService _target; - private readonly CancellationToken _cancellationToken = CancellationToken.None; + [Fact] + public async Task TotalHitsCountsEveryMatchWhenThereIsNoPaging() + { + await AddPackagesAsync("Package.A", "Package.B", "Package.C"); + + var response = await _target.SearchAsync(Request(skip: 0, take: 20), _cancellationToken); + + Assert.Equal(3, response.Data.Count); + Assert.Equal(3, response.TotalHits); + } + + [Fact] + public async Task TotalHitsDisregardsSkipAndTake() + { + await AddPackagesAsync(PackageIds(10)); + + var firstPage = await _target.SearchAsync(Request(skip: 0, take: 3), _cancellationToken); + var secondPage = await _target.SearchAsync(Request(skip: 3, take: 3), _cancellationToken); + var lastPage = await _target.SearchAsync(Request(skip: 9, take: 3), _cancellationToken); + + Assert.Equal(3, firstPage.Data.Count); + Assert.Equal(3, secondPage.Data.Count); + Assert.Single(lastPage.Data); + + // The total is the number of matches, not the size of the page returned. + Assert.Equal(10, firstPage.TotalHits); + Assert.Equal(10, secondPage.TotalHits); + Assert.Equal(10, lastPage.TotalHits); + } + + [Fact] + public async Task TotalHitsIsStillTheTotalWhenSkippingPastTheEnd() + { + await AddPackagesAsync(PackageIds(5)); + + var response = await _target.SearchAsync(Request(skip: 100, take: 20), _cancellationToken); + + Assert.Empty(response.Data); + Assert.Equal(5, response.TotalHits); + } + + [Fact] + public async Task TotalHitsIsZeroWhenNothingMatches() + { + await AddPackagesAsync("Package.A", "Package.B"); + + var response = await _target.SearchAsync( + Request(skip: 0, take: 20, query: "no.such.package"), + _cancellationToken); + + Assert.Empty(response.Data); + Assert.Equal(0, response.TotalHits); + } + + [Fact] + public async Task TotalHitsIsZeroWhenTheDatabaseIsEmpty() + { + var response = await _target.SearchAsync(Request(skip: 0, take: 20), _cancellationToken); + + Assert.Empty(response.Data); + Assert.Equal(0, response.TotalHits); + } + + [Fact] + public async Task TotalHitsCountsDistinctPackageIdsAndNotRows() + { + // Three rows for one package and one row for another: two matches, not four. + await AddPackageAsync("Package.A", "1.0.0"); + await AddPackageAsync("Package.A", "2.0.0"); + await AddPackageAsync("Package.A", "3.0.0"); + await AddPackageAsync("Package.B", "1.0.0"); + + var response = await _target.SearchAsync(Request(skip: 0, take: 20), _cancellationToken); + + Assert.Equal(2, response.Data.Count); + Assert.Equal(2, response.TotalHits); + } + + [Fact] + public async Task TotalHitsAppliesTheSearchFilters() + { + await AddPackageAsync("Package.Listed", "1.0.0"); + await AddPackageAsync("Package.Unlisted", "1.0.0", listed: false); + await AddPackageAsync("Package.Prerelease", "1.0.0-beta"); + + var excluded = await _target.SearchAsync( + Request(skip: 0, take: 1, includePrerelease: false), + _cancellationToken); + var included = await _target.SearchAsync( + Request(skip: 0, take: 1, includePrerelease: true), + _cancellationToken); + + // The unlisted package never matches; the prerelease one matches only when asked for. + Assert.Equal(1, excluded.TotalHits); + Assert.Equal(2, included.TotalHits); + } + } + + public class AutocompleteAsync : DatabaseSearchServiceTests + { + [Fact] + public async Task TotalHitsCountsEveryMatchWhenThereIsNoPaging() + { + await AddPackagesAsync("Package.A", "Package.B", "Package.C"); - public DatabaseSearchServiceTests() + var response = await _target.AutocompleteAsync( + new AutocompleteRequest { Skip = 0, Take = 20 }, + _cancellationToken); + + Assert.Equal(3, response.Data.Count); + Assert.Equal(3, response.TotalHits); + } + + [Fact] + public async Task TotalHitsDisregardsSkipAndTake() { - // An in-memory SQLite database lives as long as its connection, so the connection - // is held open for the lifetime of the test. - _connection = new SqliteConnection("Data Source=:memory:"); - _connection.Open(); - - var options = new DbContextOptionsBuilder() - .UseSqlite(_connection) - .Options; - - _context = new SqliteContext(options); - _context.Database.Migrate(); - - _target = new DatabaseSearchService( - _context, - new FrameworkCompatibilityService(), - new SearchResponseBuilder(Mock.Of())); + await AddPackagesAsync(PackageIds(10)); + + var response = await _target.AutocompleteAsync( + new AutocompleteRequest { Skip = 2, Take = 3 }, + _cancellationToken); + + Assert.Equal(3, response.Data.Count); + Assert.Equal(10, response.TotalHits); } - public class SearchAsync : DatabaseSearchServiceTests + [Fact] + public async Task TotalHitsIsStillTheTotalWhenSkippingPastTheEnd() { - [Fact] - public async Task TotalHitsCountsEveryMatchWhenThereIsNoPaging() - { - await AddPackagesAsync("Package.A", "Package.B", "Package.C"); - - var response = await _target.SearchAsync(Request(skip: 0, take: 20), _cancellationToken); - - Assert.Equal(3, response.Data.Count); - Assert.Equal(3, response.TotalHits); - } - - [Fact] - public async Task TotalHitsDisregardsSkipAndTake() - { - await AddPackagesAsync(PackageIds(10)); - - var firstPage = await _target.SearchAsync(Request(skip: 0, take: 3), _cancellationToken); - var secondPage = await _target.SearchAsync(Request(skip: 3, take: 3), _cancellationToken); - var lastPage = await _target.SearchAsync(Request(skip: 9, take: 3), _cancellationToken); - - Assert.Equal(3, firstPage.Data.Count); - Assert.Equal(3, secondPage.Data.Count); - Assert.Single(lastPage.Data); - - // The total is the number of matches, not the size of the page returned. - Assert.Equal(10, firstPage.TotalHits); - Assert.Equal(10, secondPage.TotalHits); - Assert.Equal(10, lastPage.TotalHits); - } - - [Fact] - public async Task TotalHitsIsStillTheTotalWhenSkippingPastTheEnd() - { - await AddPackagesAsync(PackageIds(5)); - - var response = await _target.SearchAsync(Request(skip: 100, take: 20), _cancellationToken); - - Assert.Empty(response.Data); - Assert.Equal(5, response.TotalHits); - } - - [Fact] - public async Task TotalHitsIsZeroWhenNothingMatches() - { - await AddPackagesAsync("Package.A", "Package.B"); - - var response = await _target.SearchAsync( - Request(skip: 0, take: 20, query: "no.such.package"), - _cancellationToken); - - Assert.Empty(response.Data); - Assert.Equal(0, response.TotalHits); - } - - [Fact] - public async Task TotalHitsIsZeroWhenTheDatabaseIsEmpty() - { - var response = await _target.SearchAsync(Request(skip: 0, take: 20), _cancellationToken); - - Assert.Empty(response.Data); - Assert.Equal(0, response.TotalHits); - } - - [Fact] - public async Task TotalHitsCountsDistinctPackageIdsAndNotRows() - { - // Three rows for one package and one row for another: two matches, not four. - await AddPackageAsync("Package.A", "1.0.0"); - await AddPackageAsync("Package.A", "2.0.0"); - await AddPackageAsync("Package.A", "3.0.0"); - await AddPackageAsync("Package.B", "1.0.0"); - - var response = await _target.SearchAsync(Request(skip: 0, take: 20), _cancellationToken); - - Assert.Equal(2, response.Data.Count); - Assert.Equal(2, response.TotalHits); - } - - [Fact] - public async Task TotalHitsAppliesTheSearchFilters() - { - await AddPackageAsync("Package.Listed", "1.0.0"); - await AddPackageAsync("Package.Unlisted", "1.0.0", listed: false); - await AddPackageAsync("Package.Prerelease", "1.0.0-beta"); - - var excluded = await _target.SearchAsync( - Request(skip: 0, take: 1, includePrerelease: false), - _cancellationToken); - var included = await _target.SearchAsync( - Request(skip: 0, take: 1, includePrerelease: true), - _cancellationToken); - - // The unlisted package never matches; the prerelease one matches only when asked for. - Assert.Equal(1, excluded.TotalHits); - Assert.Equal(2, included.TotalHits); - } + await AddPackagesAsync(PackageIds(5)); + + var response = await _target.AutocompleteAsync( + new AutocompleteRequest { Skip = 100, Take = 20 }, + _cancellationToken); + + Assert.Empty(response.Data); + Assert.Equal(5, response.TotalHits); } - public class AutocompleteAsync : DatabaseSearchServiceTests + [Fact] + public async Task TotalHitsIsZeroWhenNothingMatches() { - [Fact] - public async Task TotalHitsCountsEveryMatchWhenThereIsNoPaging() - { - await AddPackagesAsync("Package.A", "Package.B", "Package.C"); - - var response = await _target.AutocompleteAsync( - new AutocompleteRequest { Skip = 0, Take = 20 }, - _cancellationToken); - - Assert.Equal(3, response.Data.Count); - Assert.Equal(3, response.TotalHits); - } - - [Fact] - public async Task TotalHitsDisregardsSkipAndTake() - { - await AddPackagesAsync(PackageIds(10)); - - var response = await _target.AutocompleteAsync( - new AutocompleteRequest { Skip = 2, Take = 3 }, - _cancellationToken); - - Assert.Equal(3, response.Data.Count); - Assert.Equal(10, response.TotalHits); - } - - [Fact] - public async Task TotalHitsIsStillTheTotalWhenSkippingPastTheEnd() - { - await AddPackagesAsync(PackageIds(5)); - - var response = await _target.AutocompleteAsync( - new AutocompleteRequest { Skip = 100, Take = 20 }, - _cancellationToken); - - Assert.Empty(response.Data); - Assert.Equal(5, response.TotalHits); - } - - [Fact] - public async Task TotalHitsIsZeroWhenNothingMatches() - { - await AddPackagesAsync("Package.A", "Package.B"); - - var response = await _target.AutocompleteAsync( - new AutocompleteRequest { Skip = 0, Take = 20, Query = "no.such.package" }, - _cancellationToken); - - Assert.Empty(response.Data); - Assert.Equal(0, response.TotalHits); - } - - [Fact] - public async Task TotalHitsCountsDistinctPackageIdsAndNotRows() - { - await AddPackageAsync("Package.A", "1.0.0"); - await AddPackageAsync("Package.A", "2.0.0"); - await AddPackageAsync("Package.B", "1.0.0"); - - var response = await _target.AutocompleteAsync( - new AutocompleteRequest { Skip = 0, Take = 20 }, - _cancellationToken); - - Assert.Equal(2, response.Data.Count); - Assert.Equal(2, response.TotalHits); - } - - [Fact] - public async Task OrdersPackageIdsByTotalDownloads() - { - // Guards the fix for #771. Ordering before a "Distinct" over a narrower - // projection is dropped, which left the ids in insertion order. - await AddPackageAsync("Package.Unpopular", "1.0.0", downloads: 1); - await AddPackageAsync("Package.Unpopular", "2.0.0", downloads: 2); - await AddPackageAsync("Package.Popular", "1.0.0", downloads: 500); - await AddPackageAsync("Package.Popular", "2.0.0", downloads: 500); - await AddPackageAsync("Package.Middling", "1.0.0", downloads: 50); - - var response = await _target.AutocompleteAsync( - new AutocompleteRequest { Skip = 0, Take = 20 }, - _cancellationToken); - - Assert.Equal( - new[] { "Package.Popular", "Package.Middling", "Package.Unpopular" }, - response.Data); - } - - [Fact] - public async Task ReturnsEachPackageIdOnce() - { - await AddPackageAsync("Package.A", "1.0.0", downloads: 5); - await AddPackageAsync("Package.A", "2.0.0", downloads: 5); - await AddPackageAsync("Package.A", "3.0.0", downloads: 5); - - var response = await _target.AutocompleteAsync( - new AutocompleteRequest { Skip = 0, Take = 20 }, - _cancellationToken); - - Assert.Equal(new[] { "Package.A" }, response.Data); - } - - [Fact] - public async Task PagesOverDistinctPackageIds() - { - await AddPackageAsync("Package.First", "1.0.0", downloads: 300); - await AddPackageAsync("Package.First", "2.0.0", downloads: 300); - await AddPackageAsync("Package.Second", "1.0.0", downloads: 200); - await AddPackageAsync("Package.Third", "1.0.0", downloads: 100); - - var response = await _target.AutocompleteAsync( - new AutocompleteRequest { Skip = 1, Take = 1 }, - _cancellationToken); - - Assert.Equal(new[] { "Package.Second" }, response.Data); - } + await AddPackagesAsync("Package.A", "Package.B"); + + var response = await _target.AutocompleteAsync( + new AutocompleteRequest { Skip = 0, Take = 20, Query = "no.such.package" }, + _cancellationToken); + + Assert.Empty(response.Data); + Assert.Equal(0, response.TotalHits); } - public class ListPackageVersionsAsync : DatabaseSearchServiceTests + [Fact] + public async Task TotalHitsCountsDistinctPackageIdsAndNotRows() { - [Fact] - public async Task TotalHitsCountsTheVersionsReturned() - { - await AddPackageAsync("Package.A", "1.0.0"); - await AddPackageAsync("Package.A", "2.0.0"); - await AddPackageAsync("Package.B", "1.0.0"); - - var response = await _target.ListPackageVersionsAsync( - new VersionsRequest { PackageId = "Package.A" }, - _cancellationToken); - - Assert.Equal(2, response.Data.Count); - Assert.Equal(2, response.TotalHits); - } - - [Fact] - public async Task TotalHitsIsZeroWhenThePackageDoesNotExist() - { - await AddPackageAsync("Package.A", "1.0.0"); - - var response = await _target.ListPackageVersionsAsync( - new VersionsRequest { PackageId = "No.Such.Package" }, - _cancellationToken); - - Assert.Empty(response.Data); - Assert.Equal(0, response.TotalHits); - } + await AddPackageAsync("Package.A", "1.0.0"); + await AddPackageAsync("Package.A", "2.0.0"); + await AddPackageAsync("Package.B", "1.0.0"); + + var response = await _target.AutocompleteAsync( + new AutocompleteRequest { Skip = 0, Take = 20 }, + _cancellationToken); + + Assert.Equal(2, response.Data.Count); + Assert.Equal(2, response.TotalHits); } - private static SearchRequest Request( - int skip, - int take, - string query = null, - bool includePrerelease = true, - bool includeSemVer2 = true) + [Fact] + public async Task OrdersPackageIdsByTotalDownloads() { - return new SearchRequest - { - Skip = skip, - Take = take, - Query = query, - IncludePrerelease = includePrerelease, - IncludeSemVer2 = includeSemVer2, - }; + // Guards the fix for #771. Ordering before a "Distinct" over a narrower + // projection is dropped, which left the ids in insertion order. + await AddPackageAsync("Package.Unpopular", "1.0.0", downloads: 1); + await AddPackageAsync("Package.Unpopular", "2.0.0", downloads: 2); + await AddPackageAsync("Package.Popular", "1.0.0", downloads: 500); + await AddPackageAsync("Package.Popular", "2.0.0", downloads: 500); + await AddPackageAsync("Package.Middling", "1.0.0", downloads: 50); + + var response = await _target.AutocompleteAsync( + new AutocompleteRequest { Skip = 0, Take = 20 }, + _cancellationToken); + + Assert.Equal( + new[] { "Package.Popular", "Package.Middling", "Package.Unpopular" }, + response.Data); } - private static string[] PackageIds(int count) + [Fact] + public async Task ReturnsEachPackageIdOnce() { - return Enumerable - .Range(0, count) - .Select(i => $"Package.{i:00}") - .ToArray(); + await AddPackageAsync("Package.A", "1.0.0", downloads: 5); + await AddPackageAsync("Package.A", "2.0.0", downloads: 5); + await AddPackageAsync("Package.A", "3.0.0", downloads: 5); + + var response = await _target.AutocompleteAsync( + new AutocompleteRequest { Skip = 0, Take = 20 }, + _cancellationToken); + + Assert.Equal(new[] { "Package.A" }, response.Data); } - private async Task AddPackagesAsync(params string[] packageIds) + [Fact] + public async Task PagesOverDistinctPackageIds() { - foreach (var packageId in packageIds) - { - await AddPackageAsync(packageId, "1.0.0"); - } + await AddPackageAsync("Package.First", "1.0.0", downloads: 300); + await AddPackageAsync("Package.First", "2.0.0", downloads: 300); + await AddPackageAsync("Package.Second", "1.0.0", downloads: 200); + await AddPackageAsync("Package.Third", "1.0.0", downloads: 100); + + var response = await _target.AutocompleteAsync( + new AutocompleteRequest { Skip = 1, Take = 1 }, + _cancellationToken); + + Assert.Equal(new[] { "Package.Second" }, response.Data); } + } - private async Task AddPackageAsync( - string packageId, - string version, - bool listed = true, - long downloads = 0) + public class ListPackageVersionsAsync : DatabaseSearchServiceTests + { + [Fact] + public async Task TotalHitsCountsTheVersionsReturned() { - var parsedVersion = NuGetVersion.Parse(version); - - _context.Packages.Add(new Package - { - Id = packageId, - Version = parsedVersion, - Authors = Array.Empty(), - Description = "Description", - Listed = listed, - Downloads = downloads, - IsPrerelease = parsedVersion.IsPrerelease, - SemVerLevel = SemVerLevel.Unknown, - Published = DateTime.UtcNow, - Summary = "Summary", - Tags = Array.Empty(), - Dependencies = new List(), - PackageTypes = new List(), - TargetFrameworks = new List(), - }); - - await _context.SaveChangesAsync(_cancellationToken); + await AddPackageAsync("Package.A", "1.0.0"); + await AddPackageAsync("Package.A", "2.0.0"); + await AddPackageAsync("Package.B", "1.0.0"); + + var response = await _target.ListPackageVersionsAsync( + new VersionsRequest { PackageId = "Package.A" }, + _cancellationToken); + + Assert.Equal(2, response.Data.Count); + Assert.Equal(2, response.TotalHits); } - public void Dispose() + [Fact] + public async Task TotalHitsIsZeroWhenThePackageDoesNotExist() { - _context.Dispose(); - _connection.Dispose(); + await AddPackageAsync("Package.A", "1.0.0"); + + var response = await _target.ListPackageVersionsAsync( + new VersionsRequest { PackageId = "No.Such.Package" }, + _cancellationToken); + + Assert.Empty(response.Data); + Assert.Equal(0, response.TotalHits); } } -} + + private static SearchRequest Request( + int skip, + int take, + string query = null, + bool includePrerelease = true, + bool includeSemVer2 = true) + { + return new SearchRequest + { + Skip = skip, + Take = take, + Query = query, + IncludePrerelease = includePrerelease, + IncludeSemVer2 = includeSemVer2, + }; + } + + private static string[] PackageIds(int count) + { + return Enumerable + .Range(0, count) + .Select(i => $"Package.{i:00}") + .ToArray(); + } + + private async Task AddPackagesAsync(params string[] packageIds) + { + foreach (var packageId in packageIds) + { + await AddPackageAsync(packageId, "1.0.0"); + } + } + + private async Task AddPackageAsync( + string packageId, + string version, + bool listed = true, + long downloads = 0) + { + var parsedVersion = NuGetVersion.Parse(version); + + _context.Packages.Add(new Package + { + Id = packageId, + Version = parsedVersion, + Authors = Array.Empty(), + Description = "Description", + Listed = listed, + Downloads = downloads, + IsPrerelease = parsedVersion.IsPrerelease, + SemVerLevel = SemVerLevel.Unknown, + Published = DateTime.UtcNow, + Summary = "Summary", + Tags = Array.Empty(), + Dependencies = new List(), + PackageTypes = new List(), + TargetFrameworks = new List(), + }); + + await _context.SaveChangesAsync(_cancellationToken); + } + + public void Dispose() + { + _context.Dispose(); + _connection.Dispose(); + } +} \ No newline at end of file diff --git a/tests/BaGet.Tests/HostIntegrationTests.cs b/tests/BaGet.Tests/HostIntegrationTests.cs index 84cbe7259..8e118ebbf 100644 --- a/tests/BaGet.Tests/HostIntegrationTests.cs +++ b/tests/BaGet.Tests/HostIntegrationTests.cs @@ -8,73 +8,72 @@ using Microsoft.Extensions.Hosting; using Xunit; -namespace BaGet.Tests +namespace BaGet.Tests; + +public class HostIntegrationTests { - public class HostIntegrationTests - { - private readonly string DatabaseTypeKey = "Database:Type"; - private readonly string ConnectionStringKey = "Database:ConnectionString"; + private readonly string DatabaseTypeKey = "Database:Type"; + private readonly string ConnectionStringKey = "Database:ConnectionString"; - [Fact] - public void ThrowsIfDatabaseTypeInvalid() + [Fact] + public void ThrowsIfDatabaseTypeInvalid() + { + using var host = BuildHost(new Dictionary { - using var host = BuildHost(new Dictionary - { - { DatabaseTypeKey, "InvalidType" } - }); - using var scope = host.Services.CreateScope(); + { DatabaseTypeKey, "InvalidType" } + }); + using var scope = host.Services.CreateScope(); - Assert.Throws( - () => scope.ServiceProvider.GetRequiredService()); - } + Assert.Throws( + () => scope.ServiceProvider.GetRequiredService()); + } - [Fact] - public void ReturnsDatabaseContext() + [Fact] + public void ReturnsDatabaseContext() + { + using var host = BuildHost(new Dictionary { - using var host = BuildHost(new Dictionary - { - { DatabaseTypeKey, "Sqlite" }, - { ConnectionStringKey, "..." } - }); - using var scope = host.Services.CreateScope(); + { DatabaseTypeKey, "Sqlite" }, + { ConnectionStringKey, "..." } + }); + using var scope = host.Services.CreateScope(); - Assert.NotNull(scope.ServiceProvider.GetRequiredService()); - } + Assert.NotNull(scope.ServiceProvider.GetRequiredService()); + } - [Fact] - public void ReturnsSqliteContext() + [Fact] + public void ReturnsSqliteContext() + { + using var host = BuildHost(new Dictionary { - using var host = BuildHost(new Dictionary - { - { DatabaseTypeKey, "Sqlite" }, - { ConnectionStringKey, "..." } - }); - using var scope = host.Services.CreateScope(); + { DatabaseTypeKey, "Sqlite" }, + { ConnectionStringKey, "..." } + }); + using var scope = host.Services.CreateScope(); - Assert.NotNull(scope.ServiceProvider.GetRequiredService()); - } + Assert.NotNull(scope.ServiceProvider.GetRequiredService()); + } - [Fact] - public void DefaultsToSqlite() - { - using var host = BuildHost(); - using var scope = host.Services.CreateScope(); + [Fact] + public void DefaultsToSqlite() + { + using var host = BuildHost(); + using var scope = host.Services.CreateScope(); - var context = scope.ServiceProvider.GetRequiredService(); + var context = scope.ServiceProvider.GetRequiredService(); - Assert.IsType(context); - } + Assert.IsType(context); + } - private IHost BuildHost(Dictionary configs = null) - { - // WebApplication.CreateBuilder reads the command line as a configuration source, - // which is how these settings reach the host now that there is no host builder to - // append a provider to. - var args = (configs ?? new Dictionary()) - .Select(setting => $"--{setting.Key}={setting.Value}") - .ToArray(); + private IHost BuildHost(Dictionary configs = null) + { + // WebApplication.CreateBuilder reads the command line as a configuration source, + // which is how these settings reach the host now that there is no host builder to + // append a provider to. + var args = (configs ?? new Dictionary()) + .Select(setting => $"--{setting.Key}={setting.Value}") + .ToArray(); - return Program.BuildApplication(args); - } + return Program.BuildApplication(args); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/MirrorIntegrationTests.cs b/tests/BaGet.Tests/MirrorIntegrationTests.cs index 8f6141772..7e0288ff0 100644 --- a/tests/BaGet.Tests/MirrorIntegrationTests.cs +++ b/tests/BaGet.Tests/MirrorIntegrationTests.cs @@ -6,36 +6,36 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +public class MirrorIntegrationTests : IDisposable { - public class MirrorIntegrationTests : IDisposable - { - private readonly BaGetApplication _upstream; - private readonly BaGetApplication _downstream; - private readonly HttpClient _downstreamClient; - private readonly Stream _packageStream; + private readonly BaGetApplication _upstream; + private readonly BaGetApplication _downstream; + private readonly HttpClient _downstreamClient; + private readonly Stream _packageStream; - public MirrorIntegrationTests(ITestOutputHelper output) - { - _upstream = new BaGetApplication(output); - _downstream = new BaGetApplication(output, _upstream.CreateClient()); + public MirrorIntegrationTests(ITestOutputHelper output) + { + _upstream = new BaGetApplication(output); + _downstream = new BaGetApplication(output, _upstream.CreateClient()); - _downstreamClient = _downstream.CreateClient(); - _packageStream = TestResources.GetResourceStream(TestResources.Package); - } + _downstreamClient = _downstream.CreateClient(); + _packageStream = TestResources.GetResourceStream(TestResources.Package); + } - [Fact] - public async Task SearchExcludesUpstream() - { - await _upstream.AddPackageAsync(_packageStream); + [Fact] + public async Task SearchExcludesUpstream() + { + await _upstream.AddPackageAsync(_packageStream); - using var downstreamResponse = await _downstreamClient.GetAsync("v3/search"); - var downstreamContent = await downstreamResponse.Content.ReadAsStreamAsync(); - var downstreamJson = downstreamContent.ToPrettifiedJson(); + using var downstreamResponse = await _downstreamClient.GetAsync("v3/search"); + var downstreamContent = await downstreamResponse.Content.ReadAsStreamAsync(); + var downstreamJson = downstreamContent.ToPrettifiedJson(); - // The downstream package source should not have the package. - Assert.Equal(HttpStatusCode.OK, downstreamResponse.StatusCode); - Assert.Equal(@"{ + // The downstream package source should not have the package. + Assert.Equal(HttpStatusCode.OK, downstreamResponse.StatusCode); + Assert.Equal(@"{ ""@context"": { ""@vocab"": ""http://schema.nuget.org/schema#"", ""@base"": ""http://localhost/v3/registration"" @@ -43,52 +43,52 @@ public async Task SearchExcludesUpstream() ""totalHits"": 0, ""data"": [] }", downstreamJson); - } + } - [Fact] - public async Task VersionListIncludesUpstream() - { - await _upstream.AddPackageAsync(_packageStream); + [Fact] + public async Task VersionListIncludesUpstream() + { + await _upstream.AddPackageAsync(_packageStream); - var response = await _downstreamClient.GetAsync("v3/package/TestData/index.json"); - var content = await response.Content.ReadAsStringAsync(); + var response = await _downstreamClient.GetAsync("v3/package/TestData/index.json"); + var content = await response.Content.ReadAsStringAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{""versions"":[""1.2.3""]}", content); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{""versions"":[""1.2.3""]}", content); + } - [Fact] - public async Task PackageDownloadIncludesUpstream() - { - await _upstream.AddPackageAsync(_packageStream); + [Fact] + public async Task PackageDownloadIncludesUpstream() + { + await _upstream.AddPackageAsync(_packageStream); - using var response = await _downstreamClient.GetAsync("v3/package/TestData/1.2.3/TestData.1.2.3.nupkg"); + using var response = await _downstreamClient.GetAsync("v3/package/TestData/1.2.3/TestData.1.2.3.nupkg"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - [Fact] - public async Task NuspecDownloadIncludesUpstream() - { - await _upstream.AddPackageAsync(_packageStream); + [Fact] + public async Task NuspecDownloadIncludesUpstream() + { + await _upstream.AddPackageAsync(_packageStream); - using var response = await _downstreamClient.GetAsync( - "v3/package/TestData/1.2.3/TestData.1.2.3.nuspec"); + using var response = await _downstreamClient.GetAsync( + "v3/package/TestData/1.2.3/TestData.1.2.3.nuspec"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - [Fact] - public async Task PackageMetadataIncludesUpstream() - { - await _upstream.AddPackageAsync(_packageStream); + [Fact] + public async Task PackageMetadataIncludesUpstream() + { + await _upstream.AddPackageAsync(_packageStream); - using var response = await _downstreamClient.GetAsync("v3/registration/TestData/index.json"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + using var response = await _downstreamClient.GetAsync("v3/registration/TestData/index.json"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@id"": ""http://localhost/v3/registration/testdata/index.json"", ""@type"": [ ""catalog:CatalogRoot"", @@ -140,19 +140,19 @@ public async Task PackageMetadataIncludesUpstream() ], ""totalDownloads"": 0 }", json); - } + } - [Fact] - public async Task PackageMetadataLeafIncludesUpstream() - { - await _upstream.AddPackageAsync(_packageStream); + [Fact] + public async Task PackageMetadataLeafIncludesUpstream() + { + await _upstream.AddPackageAsync(_packageStream); - using var response = await _downstreamClient.GetAsync("v3/registration/TestData/1.2.3.json"); - var content = await response.Content.ReadAsStreamAsync(); - var json = content.ToPrettifiedJson(); + using var response = await _downstreamClient.GetAsync("v3/registration/TestData/1.2.3.json"); + var content = await response.Content.ReadAsStreamAsync(); + var json = content.ToPrettifiedJson(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(@"{ + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(@"{ ""@id"": ""http://localhost/v3/registration/testdata/1.2.3.json"", ""@type"": [ ""Package"", @@ -163,12 +163,11 @@ public async Task PackageMetadataLeafIncludesUpstream() ""published"": ""2020-01-01T00:00:00Z"", ""registration"": ""http://localhost/v3/registration/testdata/index.json"" }", json); - } + } - public void Dispose() - { - _upstream.Dispose(); - _downstream.Dispose(); - } + public void Dispose() + { + _upstream.Dispose(); + _downstream.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/NuGetClientIntegrationTests.cs b/tests/BaGet.Tests/NuGetClientIntegrationTests.cs index 1140af67d..63953114e 100644 --- a/tests/BaGet.Tests/NuGetClientIntegrationTests.cs +++ b/tests/BaGet.Tests/NuGetClientIntegrationTests.cs @@ -11,256 +11,255 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Uses the official NuGet client to interact with the BaGet test host. +/// +public class NuGetClientIntegrationTests : IDisposable { - /// - /// Uses the official NuGet client to interact with the BaGet test host. - /// - public class NuGetClientIntegrationTests : IDisposable + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + private readonly Stream _packageStream; + + private readonly SourceRepository _repository; + private readonly SourceCacheContext _cache; + private readonly NuGet.Common.ILogger _logger; + private readonly CancellationToken _cancellationToken; + + public NuGetClientIntegrationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output); + _client = _app.CreateDefaultClient(); + _packageStream = TestResources.GetResourceStream(TestResources.Package); + + var sourceUri = new Uri(_app.Server.BaseAddress, "v3/index.json"); + var packageSource = new PackageSource(sourceUri.AbsoluteUri); + var providers = new List>(); + + providers.Add(new Lazy(() => new HttpSourceResourceProviderTestHost(_client))); + providers.AddRange(Repository.Provider.GetCoreV3()); + + _repository = new SourceRepository(packageSource, providers); + _cache = new SourceCacheContext { NoCache = true, MaxAge = new DateTimeOffset(), DirectDownload = true }; + _logger = NuGet.Common.NullLogger.Instance; + _cancellationToken = CancellationToken.None; + } + + [Fact] + public async Task ValidIndex() + { + var index = await _repository.GetResourceAsync(); + + Assert.Equal(17, index.Entries.Count); + + Assert.NotEmpty(index.GetServiceEntries("PackageBaseAddress/3.0.0")); + Assert.NotEmpty(index.GetServiceEntries("PackagePublish/2.0.0")); + Assert.NotEmpty(index.GetServiceEntries("RegistrationsBaseUrl")); + Assert.NotEmpty(index.GetServiceEntries("SearchAutocompleteService")); + Assert.NotEmpty(index.GetServiceEntries("SearchQueryService")); + Assert.NotEmpty(index.GetServiceEntries("SymbolPackagePublish/4.9.0")); + Assert.NotEmpty(index.GetServiceEntries("PackageDetailsUriTemplate/5.1.0")); + Assert.NotEmpty(index.GetServiceEntries("ReportAbuseUriTemplate/3.0.0-rc")); + } + + [Fact] + public async Task SearchReturnsResults() + { + await _app.AddPackageAsync(_packageStream); + + var resource = await _repository.GetResourceAsync(); + var searchFilter = new SearchFilter(includePrerelease: true); + + var results = await resource.SearchAsync( + "", + searchFilter, + skip: 0, + take: 20, + _logger, + _cancellationToken); + + var result = Assert.Single(results); + + Assert.Equal("TestData", result.Identity.Id); + Assert.Equal("1.2.3", result.Identity.Version.ToNormalizedString()); + Assert.Equal("Test description", result.Description); + Assert.Equal("Test author", result.Authors); + Assert.Equal(0, result.DownloadCount); + + var versions = await result.GetVersionsAsync(); + var version = Assert.Single(versions); + + Assert.Equal("1.2.3", version.Version.ToNormalizedString()); + Assert.Equal(0, version.DownloadCount); + } + + [Fact] + public async Task SearchReturnsEmpty() + { + var resource = await _repository.GetResourceAsync(); + var searchFilter = new SearchFilter(includePrerelease: true); + + var results = await resource.SearchAsync( + "PackageDoesNotExist", + searchFilter, + skip: 0, + take: 20, + _logger, + _cancellationToken); + + Assert.Empty(results); + } + + [Fact] + public async Task AutocompleteReturnsResults() + { + await _app.AddPackageAsync(_packageStream); + + var resource = await _repository.GetResourceAsync(); + var results = await resource.IdStartsWith( + "", + includePrerelease: true, + _logger, + _cancellationToken); + + var result = Assert.Single(results); + + Assert.Equal("TestData", result); + } + + [Fact] + public async Task AutocompleteReturnsEmpty() + { + var resource = await _repository.GetResourceAsync(); + var results = await resource.IdStartsWith( + "PackageDoesNotExist", + includePrerelease: true, + _logger, + _cancellationToken); + + Assert.Empty(results); + } + + [Fact] + public async Task VersionListReturnsResults() + { + await _app.AddPackageAsync(_packageStream); + + var resource = await _repository.GetResourceAsync(); + var versions = await resource.GetAllVersionsAsync( + "TestData", + _cache, + _logger, + _cancellationToken); + + var version = Assert.Single(versions); + + Assert.Equal("1.2.3", version.ToNormalizedString()); + } + + [Fact] + public async Task VersionListReturnsEmpty() + { + var resource = await _repository.GetResourceAsync(); + var versions = await resource.GetAllVersionsAsync( + "PackageDoesNotExist", + _cache, + _logger, + _cancellationToken); + + Assert.Empty(versions); + } + + [Theory] + [InlineData("TestData", "1.0.0", false)] + [InlineData("TestData", "1.2.3", true)] + [InlineData("PackageDoesNotExists", "1.0.0", false)] + public async Task PackageExistsWorks(string packageId, string packageVersion, bool exists) + { + await _app.AddPackageAsync(_packageStream); + + var version = NuGetVersion.Parse(packageVersion); + var resource = await _repository.GetResourceAsync(); + var result = await resource.DoesPackageExistAsync( + packageId, + version, + _cache, + _logger, + _cancellationToken); + + Assert.Equal(exists, result); + } + + [Theory] + [InlineData("TestData", "1.0.0", false)] + [InlineData("TestData", "1.2.3", true)] + [InlineData("PackageDoesNotExists", "1.0.0", false)] + public async Task PackageDownloadWorks(string packageId, string packageVersion, bool exists) + { + await _app.AddPackageAsync(_packageStream); + + using var packageStream = new MemoryStream(); + + var version = NuGetVersion.Parse(packageVersion); + var resource = await _repository.GetResourceAsync(); + var result = await resource.CopyNupkgToStreamAsync( + packageId, + version, + packageStream, + _cache, + _logger, + _cancellationToken); + + packageStream.Position = 0; + + Assert.Equal(exists, result); + Assert.Equal(exists, packageStream.Length > 0); + } + + [Fact] + public async Task PackageMetadataReturnsOk() + { + await _app.AddPackageAsync(_packageStream); + + var resource = await _repository.GetResourceAsync(); + var packages = await resource.GetMetadataAsync( + "TestData", + includePrerelease: true, + includeUnlisted: true, + _cache, + _logger, + _cancellationToken); + + var package = Assert.Single(packages); + + Assert.Equal("TestData", package.Identity.Id); + Assert.Equal("1.2.3", package.Identity.Version.ToNormalizedString()); + Assert.Equal("Test description", package.Description); + Assert.Equal("Test author", package.Authors); + Assert.True(package.IsListed); + } + + [Fact] + public async Task PackageMetadataReturnsEmty() + { + var resource = await _repository.GetResourceAsync(); + var packages = await resource.GetMetadataAsync( + "PackageDoesNotExist", + includePrerelease: true, + includeUnlisted: true, + _cache, + _logger, + _cancellationToken); + + Assert.Empty(packages); + } + + public void Dispose() { - private readonly BaGetApplication _app; - private readonly HttpClient _client; - - private readonly Stream _packageStream; - - private readonly SourceRepository _repository; - private readonly SourceCacheContext _cache; - private readonly NuGet.Common.ILogger _logger; - private readonly CancellationToken _cancellationToken; - - public NuGetClientIntegrationTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); - _client = _app.CreateDefaultClient(); - _packageStream = TestResources.GetResourceStream(TestResources.Package); - - var sourceUri = new Uri(_app.Server.BaseAddress, "v3/index.json"); - var packageSource = new PackageSource(sourceUri.AbsoluteUri); - var providers = new List>(); - - providers.Add(new Lazy(() => new HttpSourceResourceProviderTestHost(_client))); - providers.AddRange(Repository.Provider.GetCoreV3()); - - _repository = new SourceRepository(packageSource, providers); - _cache = new SourceCacheContext { NoCache = true, MaxAge = new DateTimeOffset(), DirectDownload = true }; - _logger = NuGet.Common.NullLogger.Instance; - _cancellationToken = CancellationToken.None; - } - - [Fact] - public async Task ValidIndex() - { - var index = await _repository.GetResourceAsync(); - - Assert.Equal(17, index.Entries.Count); - - Assert.NotEmpty(index.GetServiceEntries("PackageBaseAddress/3.0.0")); - Assert.NotEmpty(index.GetServiceEntries("PackagePublish/2.0.0")); - Assert.NotEmpty(index.GetServiceEntries("RegistrationsBaseUrl")); - Assert.NotEmpty(index.GetServiceEntries("SearchAutocompleteService")); - Assert.NotEmpty(index.GetServiceEntries("SearchQueryService")); - Assert.NotEmpty(index.GetServiceEntries("SymbolPackagePublish/4.9.0")); - Assert.NotEmpty(index.GetServiceEntries("PackageDetailsUriTemplate/5.1.0")); - Assert.NotEmpty(index.GetServiceEntries("ReportAbuseUriTemplate/3.0.0-rc")); - } - - [Fact] - public async Task SearchReturnsResults() - { - await _app.AddPackageAsync(_packageStream); - - var resource = await _repository.GetResourceAsync(); - var searchFilter = new SearchFilter(includePrerelease: true); - - var results = await resource.SearchAsync( - "", - searchFilter, - skip: 0, - take: 20, - _logger, - _cancellationToken); - - var result = Assert.Single(results); - - Assert.Equal("TestData", result.Identity.Id); - Assert.Equal("1.2.3", result.Identity.Version.ToNormalizedString()); - Assert.Equal("Test description", result.Description); - Assert.Equal("Test author", result.Authors); - Assert.Equal(0, result.DownloadCount); - - var versions = await result.GetVersionsAsync(); - var version = Assert.Single(versions); - - Assert.Equal("1.2.3", version.Version.ToNormalizedString()); - Assert.Equal(0, version.DownloadCount); - } - - [Fact] - public async Task SearchReturnsEmpty() - { - var resource = await _repository.GetResourceAsync(); - var searchFilter = new SearchFilter(includePrerelease: true); - - var results = await resource.SearchAsync( - "PackageDoesNotExist", - searchFilter, - skip: 0, - take: 20, - _logger, - _cancellationToken); - - Assert.Empty(results); - } - - [Fact] - public async Task AutocompleteReturnsResults() - { - await _app.AddPackageAsync(_packageStream); - - var resource = await _repository.GetResourceAsync(); - var results = await resource.IdStartsWith( - "", - includePrerelease: true, - _logger, - _cancellationToken); - - var result = Assert.Single(results); - - Assert.Equal("TestData", result); - } - - [Fact] - public async Task AutocompleteReturnsEmpty() - { - var resource = await _repository.GetResourceAsync(); - var results = await resource.IdStartsWith( - "PackageDoesNotExist", - includePrerelease: true, - _logger, - _cancellationToken); - - Assert.Empty(results); - } - - [Fact] - public async Task VersionListReturnsResults() - { - await _app.AddPackageAsync(_packageStream); - - var resource = await _repository.GetResourceAsync(); - var versions = await resource.GetAllVersionsAsync( - "TestData", - _cache, - _logger, - _cancellationToken); - - var version = Assert.Single(versions); - - Assert.Equal("1.2.3", version.ToNormalizedString()); - } - - [Fact] - public async Task VersionListReturnsEmpty() - { - var resource = await _repository.GetResourceAsync(); - var versions = await resource.GetAllVersionsAsync( - "PackageDoesNotExist", - _cache, - _logger, - _cancellationToken); - - Assert.Empty(versions); - } - - [Theory] - [InlineData("TestData", "1.0.0", false)] - [InlineData("TestData", "1.2.3", true)] - [InlineData("PackageDoesNotExists", "1.0.0", false)] - public async Task PackageExistsWorks(string packageId, string packageVersion, bool exists) - { - await _app.AddPackageAsync(_packageStream); - - var version = NuGetVersion.Parse(packageVersion); - var resource = await _repository.GetResourceAsync(); - var result = await resource.DoesPackageExistAsync( - packageId, - version, - _cache, - _logger, - _cancellationToken); - - Assert.Equal(exists, result); - } - - [Theory] - [InlineData("TestData", "1.0.0", false)] - [InlineData("TestData", "1.2.3", true)] - [InlineData("PackageDoesNotExists", "1.0.0", false)] - public async Task PackageDownloadWorks(string packageId, string packageVersion, bool exists) - { - await _app.AddPackageAsync(_packageStream); - - using var packageStream = new MemoryStream(); - - var version = NuGetVersion.Parse(packageVersion); - var resource = await _repository.GetResourceAsync(); - var result = await resource.CopyNupkgToStreamAsync( - packageId, - version, - packageStream, - _cache, - _logger, - _cancellationToken); - - packageStream.Position = 0; - - Assert.Equal(exists, result); - Assert.Equal(exists, packageStream.Length > 0); - } - - [Fact] - public async Task PackageMetadataReturnsOk() - { - await _app.AddPackageAsync(_packageStream); - - var resource = await _repository.GetResourceAsync(); - var packages = await resource.GetMetadataAsync( - "TestData", - includePrerelease: true, - includeUnlisted: true, - _cache, - _logger, - _cancellationToken); - - var package = Assert.Single(packages); - - Assert.Equal("TestData", package.Identity.Id); - Assert.Equal("1.2.3", package.Identity.Version.ToNormalizedString()); - Assert.Equal("Test description", package.Description); - Assert.Equal("Test author", package.Authors); - Assert.True(package.IsListed); - } - - [Fact] - public async Task PackageMetadataReturnsEmty() - { - var resource = await _repository.GetResourceAsync(); - var packages = await resource.GetMetadataAsync( - "PackageDoesNotExist", - includePrerelease: true, - includeUnlisted: true, - _cache, - _logger, - _cancellationToken); - - Assert.Empty(packages); - } - - public void Dispose() - { - _app.Dispose(); - _client.Dispose(); - _cache.Dispose(); - } + _app.Dispose(); + _client.Dispose(); + _cache.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/NuGetV2ClientIntegrationTests.cs b/tests/BaGet.Tests/NuGetV2ClientIntegrationTests.cs index ee37e4725..4eb7d8a99 100644 --- a/tests/BaGet.Tests/NuGetV2ClientIntegrationTests.cs +++ b/tests/BaGet.Tests/NuGetV2ClientIntegrationTests.cs @@ -12,126 +12,125 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Drives NuGet's own client against the BaGet test host with a V2 source address. +/// The core provider list contains both the V2 and V3 resource providers and picks by +/// the shape of the source, so pointing it at "api/v2" exercises the V2 providers - +/// the same code path "nuget list" and older Install-Package use. This is the evidence +/// that the hand-written OData feed is shaped the way a real client expects, rather +/// than merely being well-formed XML. +/// +public class NuGetV2ClientIntegrationTests : IDisposable { - /// - /// Drives NuGet's own client against the BaGet test host with a V2 source address. - /// The core provider list contains both the V2 and V3 resource providers and picks by - /// the shape of the source, so pointing it at "api/v2" exercises the V2 providers - - /// the same code path "nuget list" and older Install-Package use. This is the evidence - /// that the hand-written OData feed is shaped the way a real client expects, rather - /// than merely being well-formed XML. - /// - public class NuGetV2ClientIntegrationTests : IDisposable + private readonly BaGetApplication _app; + private readonly HttpClient _client; + private readonly Stream _packageStream; + + private readonly SourceRepository _repository; + private readonly SourceCacheContext _cache; + private readonly NuGet.Common.ILogger _logger; + private readonly CancellationToken _cancellationToken; + + public NuGetV2ClientIntegrationTests(ITestOutputHelper output) { - private readonly BaGetApplication _app; - private readonly HttpClient _client; - private readonly Stream _packageStream; + _app = new BaGetApplication(output); + _client = _app.CreateDefaultClient(); + _packageStream = TestResources.GetResourceStream(TestResources.Package); - private readonly SourceRepository _repository; - private readonly SourceCacheContext _cache; - private readonly NuGet.Common.ILogger _logger; - private readonly CancellationToken _cancellationToken; + // A V2 source is the feed root, not a service index. + var sourceUri = new Uri(_app.Server.BaseAddress, "api/v2"); + var packageSource = new PackageSource(sourceUri.AbsoluteUri); - public NuGetV2ClientIntegrationTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); - _client = _app.CreateDefaultClient(); - _packageStream = TestResources.GetResourceStream(TestResources.Package); - - // A V2 source is the feed root, not a service index. - var sourceUri = new Uri(_app.Server.BaseAddress, "api/v2"); - var packageSource = new PackageSource(sourceUri.AbsoluteUri); - - var providers = new List> - { - new Lazy(() => new HttpSourceResourceProviderTestHost(_client)), - }; - providers.AddRange(Repository.Provider.GetCoreV3()); - - _repository = new SourceRepository(packageSource, providers); - _cache = new SourceCacheContext { NoCache = true, MaxAge = new DateTimeOffset(), DirectDownload = true }; - _logger = NuGet.Common.NullLogger.Instance; - _cancellationToken = CancellationToken.None; - } - - [Fact] - public async Task TheClientListsEveryVersionOfAPackage() + var providers = new List> { - await _app.AddPackageAsync(_packageStream); + new Lazy(() => new HttpSourceResourceProviderTestHost(_client)), + }; + providers.AddRange(Repository.Provider.GetCoreV3()); + + _repository = new SourceRepository(packageSource, providers); + _cache = new SourceCacheContext { NoCache = true, MaxAge = new DateTimeOffset(), DirectDownload = true }; + _logger = NuGet.Common.NullLogger.Instance; + _cancellationToken = CancellationToken.None; + } - var resource = await _repository.GetResourceAsync(_cancellationToken); - var versions = await resource.GetAllVersionsAsync( - "TestData", _cache, _logger, _cancellationToken); + [Fact] + public async Task TheClientListsEveryVersionOfAPackage() + { + await _app.AddPackageAsync(_packageStream); - Assert.Equal(new[] { "1.2.3" }, versions.Select(v => v.ToNormalizedString())); - } + var resource = await _repository.GetResourceAsync(_cancellationToken); + var versions = await resource.GetAllVersionsAsync( + "TestData", _cache, _logger, _cancellationToken); - [Fact] - public async Task TheClientFindsNoVersionsForAnUnknownPackage() - { - var resource = await _repository.GetResourceAsync(_cancellationToken); - var versions = await resource.GetAllVersionsAsync( - "No.Such.Package", _cache, _logger, _cancellationToken); - - Assert.Empty(versions); - } + Assert.Equal(new[] { "1.2.3" }, versions.Select(v => v.ToNormalizedString())); + } - [Fact] - public async Task TheClientReadsADependencyGroup() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task TheClientFindsNoVersionsForAnUnknownPackage() + { + var resource = await _repository.GetResourceAsync(_cancellationToken); + var versions = await resource.GetAllVersionsAsync( + "No.Such.Package", _cache, _logger, _cancellationToken); - var resource = await _repository.GetResourceAsync(_cancellationToken); - var info = await resource.GetDependencyInfoAsync( - "TestData", NuGetVersion.Parse("1.2.3"), _cache, _logger, _cancellationToken); + Assert.Empty(versions); + } - Assert.NotNull(info); - Assert.Equal("TestData", info.PackageIdentity.Id); - } + [Fact] + public async Task TheClientReadsADependencyGroup() + { + await _app.AddPackageAsync(_packageStream); - [Fact] - public async Task TheClientDownloadsThePackage() - { - await _app.AddPackageAsync(_packageStream); + var resource = await _repository.GetResourceAsync(_cancellationToken); + var info = await resource.GetDependencyInfoAsync( + "TestData", NuGetVersion.Parse("1.2.3"), _cache, _logger, _cancellationToken); - var resource = await _repository.GetResourceAsync(_cancellationToken); + Assert.NotNull(info); + Assert.Equal("TestData", info.PackageIdentity.Id); + } - using var downloaded = new MemoryStream(); - var copied = await resource.CopyNupkgToStreamAsync( - "TestData", - NuGetVersion.Parse("1.2.3"), - downloaded, - _cache, - _logger, - _cancellationToken); + [Fact] + public async Task TheClientDownloadsThePackage() + { + await _app.AddPackageAsync(_packageStream); - Assert.True(copied); - Assert.NotEqual(0, downloaded.Length); - } + var resource = await _repository.GetResourceAsync(_cancellationToken); - [Fact] - public async Task TheClientSearches() - { - await _app.AddPackageAsync(_packageStream); + using var downloaded = new MemoryStream(); + var copied = await resource.CopyNupkgToStreamAsync( + "TestData", + NuGetVersion.Parse("1.2.3"), + downloaded, + _cache, + _logger, + _cancellationToken); - var resource = await _repository.GetResourceAsync(_cancellationToken); - var results = await resource.SearchAsync( - "TestData", - new SearchFilter(includePrerelease: false), - skip: 0, - take: 20, - log: _logger, - cancellationToken: _cancellationToken); + Assert.True(copied); + Assert.NotEqual(0, downloaded.Length); + } - Assert.Contains("TestData", results.Select(r => r.Identity.Id)); - } + [Fact] + public async Task TheClientSearches() + { + await _app.AddPackageAsync(_packageStream); + + var resource = await _repository.GetResourceAsync(_cancellationToken); + var results = await resource.SearchAsync( + "TestData", + new SearchFilter(includePrerelease: false), + skip: 0, + take: 20, + log: _logger, + cancellationToken: _cancellationToken); + + Assert.Contains("TestData", results.Select(r => r.Identity.Id)); + } - public void Dispose() - { - _packageStream?.Dispose(); - _client?.Dispose(); - _app?.Dispose(); - } + public void Dispose() + { + _packageStream?.Dispose(); + _client?.Dispose(); + _app?.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/PackageManagementPageTests.cs b/tests/BaGet.Tests/PackageManagementPageTests.cs index 96f4e1ed6..b051aa87e 100644 --- a/tests/BaGet.Tests/PackageManagementPageTests.cs +++ b/tests/BaGet.Tests/PackageManagementPageTests.cs @@ -12,440 +12,439 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// The pages an owner manages their own packages from: the "my packages" list and the +/// delete the configures. +/// +public abstract class PackageManagementPageTestBase : IDisposable { - /// - /// The pages an owner manages their own packages from: the "my packages" list and the - /// delete the configures. - /// - public abstract class PackageManagementPageTestBase : IDisposable + protected readonly BaGetApplication App; + protected readonly HttpClient Client; + // Browser is internal to the test assembly, so these cannot be protected. + internal readonly Browser Alice; + internal readonly Browser Bob; + + protected PackageManagementPageTestBase( + ITestOutputHelper output, + string deletionBehavior = null, + bool readOnly = false) { - protected readonly BaGetApplication App; - protected readonly HttpClient Client; - // Browser is internal to the test assembly, so these cannot be protected. - internal readonly Browser Alice; - internal readonly Browser Bob; - - protected PackageManagementPageTestBase( - ITestOutputHelper output, - string deletionBehavior = null, - bool readOnly = false) + var overrides = new Dictionary { - var overrides = new Dictionary - { - { "ApiKey", "global-key" }, - { "Accounts:Enabled", "true" }, - }; - - if (deletionBehavior != null) - { - overrides["PackageDeletionBehavior"] = deletionBehavior; - } - - if (readOnly) - { - overrides["IsReadOnlyMode"] = "true"; - } - - App = new BaGetApplication(output, configOverrides: overrides); - Client = App.CreateClient(); - Alice = new Browser(App); - Bob = new Browser(App); - } + { "ApiKey", "global-key" }, + { "Accounts:Enabled", "true" }, + }; - /// - /// Push as the user would, so the package is really theirs: the first push of an ID - /// is what makes its pusher an owner. - /// - protected async Task PushAsAsync(string userName, string packageId, string version = "1.0.0") + if (deletionBehavior != null) { - var key = await WithScopeAsync(async s => - { - var user = await s.GetRequiredService>().FindByNameAsync(userName); - - return await s.GetRequiredService().CreateAsync( - user.Id, "test", new[] { ApiKeyScopes.Push }, "*", expires: null, CancellationToken.None); - }); - - using var package = TestPackages.Build(packageId, version); - using var request = TestPackages.PushRequest(package, key); - using var response = await Client.SendAsync(request); - - Assert.Equal(HttpStatusCode.Created, response.StatusCode); + overrides["PackageDeletionBehavior"] = deletionBehavior; } - /// - /// Index a package and record its owner directly, for a server that would refuse the - /// push itself. - /// - protected async Task SeedOwnedPackageAsync(string userName, string packageId, string version = "1.0.0") + if (readOnly) { - using (var package = TestPackages.Build(packageId, version)) - { - await App.AddPackageAsync(package); - } - - var result = await WithScopeAsync(s => s.GetRequiredService() - .AddOwnerAsync(packageId, userName, CancellationToken.None)); - - Assert.Equal(OwnerChangeResult.Success, result); + overrides["IsReadOnlyMode"] = "true"; } - protected Task FindAsync(string id, string version) - => WithScopeAsync(s => s.GetRequiredService() - .FindOrNullAsync(id, NuGetVersion.Parse(version), includeUnlisted: true, CancellationToken.None)); + App = new BaGetApplication(output, configOverrides: overrides); + Client = App.CreateClient(); + Alice = new Browser(App); + Bob = new Browser(App); + } - protected async Task WithScopeAsync(Func> action) + /// + /// Push as the user would, so the package is really theirs: the first push of an ID + /// is what makes its pusher an owner. + /// + protected async Task PushAsAsync(string userName, string packageId, string version = "1.0.0") + { + var key = await WithScopeAsync(async s => { - using var scope = App.Services.CreateScope(); + var user = await s.GetRequiredService>().FindByNameAsync(userName); - return await action(scope.ServiceProvider); - } + return await s.GetRequiredService().CreateAsync( + user.Id, "test", new[] { ApiKeyScopes.Push }, "*", expires: null, CancellationToken.None); + }); - public void Dispose() - { - Alice.Dispose(); - Bob.Dispose(); - Client.Dispose(); - App.Dispose(); - } + using var package = TestPackages.Build(packageId, version); + using var request = TestPackages.PushRequest(package, key); + using var response = await Client.SendAsync(request); + + Assert.Equal(HttpStatusCode.Created, response.StatusCode); } /// - /// The default server: deletion unlists. + /// Index a package and record its owner directly, for a server that would refuse the + /// push itself. /// - public class PackageManagementPageTests : PackageManagementPageTestBase + protected async Task SeedOwnedPackageAsync(string userName, string packageId, string version = "1.0.0") { - public PackageManagementPageTests(ITestOutputHelper output) - : base(output, deletionBehavior: null) + using (var package = TestPackages.Build(packageId, version)) { + await App.AddPackageAsync(package); } - [Fact] - public async Task MyPackagesListsOnlyTheIdsTheUserOwns() - { - await Alice.RegisterAsync("alice"); - await Bob.RegisterAsync("bob"); - await PushAsAsync("alice", "Alice.Package"); - await PushAsAsync("bob", "Bob.Package"); + var result = await WithScopeAsync(s => s.GetRequiredService() + .AddOwnerAsync(packageId, userName, CancellationToken.None)); - var html = await Alice.GetPageAsync("account/packages"); + Assert.Equal(OwnerChangeResult.Success, result); + } - Assert.Contains("Alice.Package", html); - Assert.DoesNotContain("Bob.Package", html); - } + protected Task FindAsync(string id, string version) + => WithScopeAsync(s => s.GetRequiredService() + .FindOrNullAsync(id, NuGetVersion.Parse(version), includeUnlisted: true, CancellationToken.None)); - [Fact] - public async Task MyPackagesShowsTheLatestVersionWithItsCountAndDownloads() - { - await Alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package", "1.0.0"); - await PushAsAsync("alice", "Alice.Package", "2.1.0"); - - var html = await Alice.GetPageAsync("account/packages"); - - // The highest version, not the first pushed, with both versions counted. - Assert.Contains("2.1.0", html); - Assert.Contains("2", html); - // Nothing has been downloaded yet, and the count is the sum over the versions. - Assert.Contains("0", html); - // The management page for the ID, and a way to add another version to it. - Assert.Contains("/packages/Alice.Package/manage", html); - Assert.Contains("Upload new version", html); - } + protected async Task WithScopeAsync(Func> action) + { + using var scope = App.Services.CreateScope(); - [Fact] - public async Task MyPackagesIsEmptyForAUserWhoOwnsNothing() - { - await Alice.RegisterAsync("alice"); + return await action(scope.ServiceProvider); + } - Assert.Contains("my-packages-empty", await Alice.GetPageAsync("account/packages")); - } + public void Dispose() + { + Alice.Dispose(); + Bob.Dispose(); + Client.Dispose(); + App.Dispose(); + } +} - [Fact] - public async Task MyPackagesNeedsASignedInUser() - { - using var response = await Bob.GetAsync("account/packages"); +/// +/// The default server: deletion unlists. +/// +public class PackageManagementPageTests : PackageManagementPageTestBase +{ + public PackageManagementPageTests(ITestOutputHelper output) + : base(output, deletionBehavior: null) + { + } - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Contains("/account/login", response.Headers.Location.ToString()); - } + [Fact] + public async Task MyPackagesListsOnlyTheIdsTheUserOwns() + { + await Alice.RegisterAsync("alice"); + await Bob.RegisterAsync("bob"); + await PushAsAsync("alice", "Alice.Package"); + await PushAsAsync("bob", "Bob.Package"); - [Fact] - public async Task TheDeleteButtonSaysUnlistWhenTheServerUnlists() - { - await Alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); + var html = await Alice.GetPageAsync("account/packages"); - var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); + Assert.Contains("Alice.Package", html); + Assert.DoesNotContain("Bob.Package", html); + } - Assert.Contains("Unlist this version", html); - Assert.DoesNotContain("Delete this version permanently", html); - } + [Fact] + public async Task MyPackagesShowsTheLatestVersionWithItsCountAndDownloads() + { + await Alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package", "1.0.0"); + await PushAsAsync("alice", "Alice.Package", "2.1.0"); + + var html = await Alice.GetPageAsync("account/packages"); + + // The highest version, not the first pushed, with both versions counted. + Assert.Contains("2.1.0", html); + Assert.Contains("2", html); + // Nothing has been downloaded yet, and the count is the sum over the versions. + Assert.Contains("0", html); + // The management page for the ID, and a way to add another version to it. + Assert.Contains("/packages/Alice.Package/manage", html); + Assert.Contains("Upload new version", html); + } - [Fact] - public async Task DeletingUnlistsAndKeepsTheVersionRestorable() - { - await Alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); + [Fact] + public async Task MyPackagesIsEmptyForAUserWhoOwnsNothing() + { + await Alice.RegisterAsync("alice"); - using var response = await Alice.PostAsync("packages/Alice.Package/manage", new Dictionary - { - { "version", "1.0.0" }, - }, action: "packages/Alice.Package/manage?handler=Delete"); + Assert.Contains("my-packages-empty", await Alice.GetPageAsync("account/packages")); + } - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("is unlisted", await response.Content.ReadAsStringAsync()); + [Fact] + public async Task MyPackagesNeedsASignedInUser() + { + using var response = await Bob.GetAsync("account/packages"); - // The row and the file both stay: the version is undiscoverable, not gone. - var package = await FindAsync("Alice.Package", "1.0.0"); - Assert.NotNull(package); - Assert.False(package.Listed); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/account/login", response.Headers.Location.ToString()); + } - using var download = await Client.GetAsync("v3/package/alice.package/1.0.0/alice.package.1.0.0.nupkg"); - Assert.Equal(HttpStatusCode.OK, download.StatusCode); - } + [Fact] + public async Task TheDeleteButtonSaysUnlistWhenTheServerUnlists() + { + await Alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); - [Fact] - public async Task TheManagePageLinksToUploadingANewVersion() - { - await Alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); + var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); - var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); + Assert.Contains("Unlist this version", html); + Assert.DoesNotContain("Delete this version permanently", html); + } - Assert.Contains("manage-upload", html); - Assert.Contains("Upload new version", html); - // The ID travels to the upload page, which reads it as a hint only. - Assert.Contains("id=Alice.Package", html); - } + [Fact] + public async Task DeletingUnlistsAndKeepsTheVersionRestorable() + { + await Alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); - [Fact] - public async Task MyPackagesListsIdsOwnedThroughAnOrganization() + using var response = await Alice.PostAsync("packages/Alice.Package/manage", new Dictionary { - await Alice.RegisterAsync("alice"); + { "version", "1.0.0" }, + }, action: "packages/Alice.Package/manage?handler=Delete"); - var aliceId = await WithScopeAsync(async s => - (await s.GetRequiredService>().FindByNameAsync("alice")).Id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("is unlisted", await response.Content.ReadAsStringAsync()); - await WithScopeAsync(async s => - { - var ownership = s.GetRequiredService(); + // The row and the file both stay: the version is undiscoverable, not gone. + var package = await FindAsync("Alice.Package", "1.0.0"); + Assert.NotNull(package); + Assert.False(package.Listed); - Assert.True(await ownership.CreateOrganizationAsync("acme", aliceId, CancellationToken.None)); + using var download = await Client.GetAsync("v3/package/alice.package/1.0.0/alice.package.1.0.0.nupkg"); + Assert.Equal(HttpStatusCode.OK, download.StatusCode); + } - return true; - }); + [Fact] + public async Task TheManagePageLinksToUploadingANewVersion() + { + await Alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); - using (var package = TestPackages.Build("Acme.Package", "1.0.0")) - { - await App.AddPackageAsync(package); - } + var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); - Assert.Equal( - OwnerChangeResult.Success, - await WithScopeAsync(s => s.GetRequiredService() - .AddOwnerAsync("Acme.Package", "acme", CancellationToken.None))); + Assert.Contains("manage-upload", html); + Assert.Contains("Upload new version", html); + // The ID travels to the upload page, which reads it as a hint only. + Assert.Contains("id=Alice.Package", html); + } - var html = await Alice.GetPageAsync("account/packages"); + [Fact] + public async Task MyPackagesListsIdsOwnedThroughAnOrganization() + { + await Alice.RegisterAsync("alice"); - // The organization owns the ID, not Alice: the list unions her own name with - // every organization she belongs to, which is the non-obvious half of the query. - Assert.Contains("Acme.Package", html); - } + var aliceId = await WithScopeAsync(async s => + (await s.GetRequiredService>().FindByNameAsync("alice")).Id); - [Fact] - public async Task UploadingANewVersionArrivesWithTheIdAsAHint() + await WithScopeAsync(async s => { - await Alice.RegisterAsync("alice"); + var ownership = s.GetRequiredService(); - var html = await Alice.GetPageAsync("Upload?id=Alice.Package"); + Assert.True(await ownership.CreateOrganizationAsync("acme", aliceId, CancellationToken.None)); - Assert.Contains("upload-for-id", html); - Assert.Contains("Alice.Package", html); - } - } + return true; + }); - /// - /// A server configured to hard delete: deletion removes the rows and the files. - /// - public class PackageHardDeletePageTests : PackageManagementPageTestBase - { - public PackageHardDeletePageTests(ITestOutputHelper output) - : base(output, deletionBehavior: "HardDelete") + using (var package = TestPackages.Build("Acme.Package", "1.0.0")) { + await App.AddPackageAsync(package); } - [Fact] - public async Task TheDeleteButtonSaysDeleteWhenTheServerHardDeletes() - { - await Alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); + Assert.Equal( + OwnerChangeResult.Success, + await WithScopeAsync(s => s.GetRequiredService() + .AddOwnerAsync("Acme.Package", "acme", CancellationToken.None))); - var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); + var html = await Alice.GetPageAsync("account/packages"); - Assert.Contains("Delete this version permanently", html); - Assert.DoesNotContain("Unlist this version", html); - } + // The organization owns the ID, not Alice: the list unions her own name with + // every organization she belongs to, which is the non-obvious half of the query. + Assert.Contains("Acme.Package", html); + } - [Fact] - public async Task DeletingRemovesTheVersionAndItsFiles() - { - await Alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); + [Fact] + public async Task UploadingANewVersionArrivesWithTheIdAsAHint() + { + await Alice.RegisterAsync("alice"); - using var response = await Alice.PostAsync("packages/Alice.Package/manage", new Dictionary - { - { "version", "1.0.0" }, - }, action: "packages/Alice.Package/manage?handler=Delete"); + var html = await Alice.GetPageAsync("Upload?id=Alice.Package"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("is deleted", await response.Content.ReadAsStringAsync()); + Assert.Contains("upload-for-id", html); + Assert.Contains("Alice.Package", html); + } +} - Assert.Null(await FindAsync("Alice.Package", "1.0.0")); +/// +/// A server configured to hard delete: deletion removes the rows and the files. +/// +public class PackageHardDeletePageTests : PackageManagementPageTestBase +{ + public PackageHardDeletePageTests(ITestOutputHelper output) + : base(output, deletionBehavior: "HardDelete") + { + } - using var download = await Client.GetAsync("v3/package/alice.package/1.0.0/alice.package.1.0.0.nupkg"); - Assert.Equal(HttpStatusCode.NotFound, download.StatusCode); - } + [Fact] + public async Task TheDeleteButtonSaysDeleteWhenTheServerHardDeletes() + { + await Alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); - [Fact] - public async Task DeletingAVersionThatIsNotThereSaysSo() + var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); + + Assert.Contains("Delete this version permanently", html); + Assert.DoesNotContain("Unlist this version", html); + } + + [Fact] + public async Task DeletingRemovesTheVersionAndItsFiles() + { + await Alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); + + using var response = await Alice.PostAsync("packages/Alice.Package/manage", new Dictionary { - await Alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); + { "version", "1.0.0" }, + }, action: "packages/Alice.Package/manage?handler=Delete"); - using var response = await Alice.PostAsync("packages/Alice.Package/manage", new Dictionary - { - { "version", "9.9.9" }, - }, action: "packages/Alice.Package/manage?handler=Delete"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("is deleted", await response.Content.ReadAsStringAsync()); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("was not in the database", await response.Content.ReadAsStringAsync()); + Assert.Null(await FindAsync("Alice.Package", "1.0.0")); - // The version that is there is untouched. - Assert.NotNull(await FindAsync("Alice.Package", "1.0.0")); - } + using var download = await Client.GetAsync("v3/package/alice.package/1.0.0/alice.package.1.0.0.nupkg"); + Assert.Equal(HttpStatusCode.NotFound, download.StatusCode); } - /// - /// A read-only server refuses a deletion, as the DELETE endpoint does. - /// - public class PackageDeleteReadOnlyTests : PackageManagementPageTestBase + [Fact] + public async Task DeletingAVersionThatIsNotThereSaysSo() { - public PackageDeleteReadOnlyTests(ITestOutputHelper output) - : base(output, deletionBehavior: "HardDelete", readOnly: true) - { - } + await Alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); - [Fact] - public async Task AReadOnlyServerRefusesToDelete() + using var response = await Alice.PostAsync("packages/Alice.Package/manage", new Dictionary { - await Alice.RegisterAsync("alice"); + { "version", "9.9.9" }, + }, action: "packages/Alice.Package/manage?handler=Delete"); - // Seeded rather than pushed: a read-only server refuses the push too. - await SeedOwnedPackageAsync("alice", "Alice.Package"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("was not in the database", await response.Content.ReadAsStringAsync()); - using var response = await Alice.PostAsync("packages/Alice.Package/manage", new Dictionary - { - { "version", "1.0.0" }, - }, action: "packages/Alice.Package/manage?handler=Delete"); + // The version that is there is untouched. + Assert.NotNull(await FindAsync("Alice.Package", "1.0.0")); + } +} - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); - Assert.NotNull(await FindAsync("Alice.Package", "1.0.0")); - } +/// +/// A read-only server refuses a deletion, as the DELETE endpoint does. +/// +public class PackageDeleteReadOnlyTests : PackageManagementPageTestBase +{ + public PackageDeleteReadOnlyTests(ITestOutputHelper output) + : base(output, deletionBehavior: "HardDelete", readOnly: true) + { + } - [Fact] - public async Task AReadOnlyServerRefusesToUnlist() - { - await Alice.RegisterAsync("alice"); - await SeedOwnedPackageAsync("alice", "Alice.Package"); + [Fact] + public async Task AReadOnlyServerRefusesToDelete() + { + await Alice.RegisterAsync("alice"); - using var response = await PostAsync("Unlist", new Dictionary - { - { "version", "1.0.0" }, - }); + // Seeded rather than pushed: a read-only server refuses the push too. + await SeedOwnedPackageAsync("alice", "Alice.Package"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + using var response = await Alice.PostAsync("packages/Alice.Package/manage", new Dictionary + { + { "version", "1.0.0" }, + }, action: "packages/Alice.Package/manage?handler=Delete"); - // Unlisting is the very operation the Delete button is said to perform, so a - // server that refuses one must refuse the other. - Assert.True((await FindAsync("Alice.Package", "1.0.0")).Listed); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + Assert.NotNull(await FindAsync("Alice.Package", "1.0.0")); + } - [Fact] - public async Task AReadOnlyServerRefusesToRelist() + [Fact] + public async Task AReadOnlyServerRefusesToUnlist() + { + await Alice.RegisterAsync("alice"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); + + using var response = await PostAsync("Unlist", new Dictionary { - await Alice.RegisterAsync("alice"); - await SeedOwnedPackageAsync("alice", "Alice.Package"); + { "version", "1.0.0" }, + }); - await WithScopeAsync(s => s.GetRequiredService() - .UnlistPackageAsync("Alice.Package", NuGetVersion.Parse("1.0.0"), CancellationToken.None)); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); - using var response = await PostAsync("Relist", new Dictionary - { - { "version", "1.0.0" }, - }); + // Unlisting is the very operation the Delete button is said to perform, so a + // server that refuses one must refuse the other. + Assert.True((await FindAsync("Alice.Package", "1.0.0")).Listed); + } - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); - Assert.False((await FindAsync("Alice.Package", "1.0.0")).Listed); - } + [Fact] + public async Task AReadOnlyServerRefusesToRelist() + { + await Alice.RegisterAsync("alice"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); - [Fact] - public async Task AReadOnlyServerRefusesToDeprecate() - { - await Alice.RegisterAsync("alice"); - await SeedOwnedPackageAsync("alice", "Alice.Package"); - - using var response = await PostAsync("Deprecate", new Dictionary - { - { "version", "1.0.0" }, - { "reasons", PackageDeprecation.KnownReasons[0] }, - }); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); - Assert.Null((await FindAsync("Alice.Package", "1.0.0")).Deprecation); - } + await WithScopeAsync(s => s.GetRequiredService() + .UnlistPackageAsync("Alice.Package", NuGetVersion.Parse("1.0.0"), CancellationToken.None)); - [Fact] - public async Task AReadOnlyServerRefusesToChangeTheOwners() + using var response = await PostAsync("Relist", new Dictionary { - await Alice.RegisterAsync("alice"); - await Bob.RegisterAsync("bob"); - await SeedOwnedPackageAsync("alice", "Alice.Package"); + { "version", "1.0.0" }, + }); - using var response = await PostAsync("AddOwner", new Dictionary - { - { "ownerName", "bob" }, - }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + Assert.False((await FindAsync("Alice.Package", "1.0.0")).Listed); + } - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + [Fact] + public async Task AReadOnlyServerRefusesToDeprecate() + { + await Alice.RegisterAsync("alice"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); - var owners = await WithScopeAsync(s => s.GetRequiredService() - .GetOwnersAsync("Alice.Package", CancellationToken.None)); + using var response = await PostAsync("Deprecate", new Dictionary + { + { "version", "1.0.0" }, + { "reasons", PackageDeprecation.KnownReasons[0] }, + }); - Assert.Equal("alice", Assert.Single(owners).OwnerName); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); + Assert.Null((await FindAsync("Alice.Package", "1.0.0")).Deprecation); + } + + [Fact] + public async Task AReadOnlyServerRefusesToChangeTheOwners() + { + await Alice.RegisterAsync("alice"); + await Bob.RegisterAsync("bob"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); - [Fact] - public async Task AReadOnlyManagePageSaysSo() + using var response = await PostAsync("AddOwner", new Dictionary { - await Alice.RegisterAsync("alice"); - await SeedOwnedPackageAsync("alice", "Alice.Package"); + { "ownerName", "bob" }, + }); - var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("read-only mode", await response.Content.ReadAsStringAsync()); - Assert.Contains("manage-read-only", html); - } + var owners = await WithScopeAsync(s => s.GetRequiredService() + .GetOwnersAsync("Alice.Package", CancellationToken.None)); - private Task PostAsync(string handler, Dictionary fields) - => Alice.PostAsync( - "packages/Alice.Package/manage", - fields, - action: $"packages/Alice.Package/manage?handler={handler}"); + Assert.Equal("alice", Assert.Single(owners).OwnerName); } + + [Fact] + public async Task AReadOnlyManagePageSaysSo() + { + await Alice.RegisterAsync("alice"); + await SeedOwnedPackageAsync("alice", "Alice.Package"); + + var html = await Alice.GetPageAsync("packages/Alice.Package/manage"); + + Assert.Contains("manage-read-only", html); + } + + private Task PostAsync(string handler, Dictionary fields) + => Alice.PostAsync( + "packages/Alice.Package/manage", + fields, + action: $"packages/Alice.Package/manage?handler={handler}"); } diff --git a/tests/BaGet.Tests/PackageMetadataAdminTests.cs b/tests/BaGet.Tests/PackageMetadataAdminTests.cs index 53195fbec..abd1cc2a8 100644 --- a/tests/BaGet.Tests/PackageMetadataAdminTests.cs +++ b/tests/BaGet.Tests/PackageMetadataAdminTests.cs @@ -9,205 +9,204 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Deprecation and vulnerability metadata: set through the admin endpoints, then read +/// back through registration and the VulnerabilityInfo resource. +/// +public class PackageMetadataAdminTests : IDisposable { - /// - /// Deprecation and vulnerability metadata: set through the admin endpoints, then read - /// back through registration and the VulnerabilityInfo resource. - /// - public class PackageMetadataAdminTests : IDisposable - { - private const string ApiKey = "secret"; + private const string ApiKey = "secret"; - private readonly BaGetApplication _app; - private readonly HttpClient _client; - private readonly Stream _packageStream; + private readonly BaGetApplication _app; + private readonly HttpClient _client; + private readonly Stream _packageStream; - public PackageMetadataAdminTests(ITestOutputHelper output) + public PackageMetadataAdminTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "ApiKey", ApiKey }, - }); - _client = _app.CreateClient(); - _packageStream = TestResources.GetResourceStream(TestResources.Package); - } + { "ApiKey", ApiKey }, + }); + _client = _app.CreateClient(); + _packageStream = TestResources.GetResourceStream(TestResources.Package); + } - [Fact] - public async Task ADeprecationAppearsInRegistration() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task ADeprecationAppearsInRegistration() + { + await _app.AddPackageAsync(_packageStream); - using var put = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation", - @"{""reasons"":[""Legacy""],""message"":""Use Other"",""alternatePackageId"":""Other""}"); - Assert.Equal(HttpStatusCode.NoContent, put.StatusCode); + using var put = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation", + @"{""reasons"":[""Legacy""],""message"":""Use Other"",""alternatePackageId"":""Other""}"); + Assert.Equal(HttpStatusCode.NoContent, put.StatusCode); - var entry = await CatalogEntryAsync(); - var deprecation = entry.GetProperty("deprecation"); + var entry = await CatalogEntryAsync(); + var deprecation = entry.GetProperty("deprecation"); - Assert.Equal("Legacy", deprecation.GetProperty("reasons")[0].GetString()); - Assert.Equal("Use Other", deprecation.GetProperty("message").GetString()); - Assert.Equal("Other", deprecation.GetProperty("alternatePackage").GetProperty("id").GetString()); - Assert.Equal("*", deprecation.GetProperty("alternatePackage").GetProperty("range").GetString()); - } + Assert.Equal("Legacy", deprecation.GetProperty("reasons")[0].GetString()); + Assert.Equal("Use Other", deprecation.GetProperty("message").GetString()); + Assert.Equal("Other", deprecation.GetProperty("alternatePackage").GetProperty("id").GetString()); + Assert.Equal("*", deprecation.GetProperty("alternatePackage").GetProperty("range").GetString()); + } - [Fact] - public async Task RemovingTheDeprecationClearsIt() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task RemovingTheDeprecationClearsIt() + { + await _app.AddPackageAsync(_packageStream); - (await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation", @"{""reasons"":[""Other""]}")).Dispose(); - using var delete = await SendAsync(HttpMethod.Delete, "v3/package/TestData/1.2.3/deprecation"); + (await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation", @"{""reasons"":[""Other""]}")).Dispose(); + using var delete = await SendAsync(HttpMethod.Delete, "v3/package/TestData/1.2.3/deprecation"); - Assert.Equal(HttpStatusCode.NoContent, delete.StatusCode); - Assert.False((await CatalogEntryAsync()).TryGetProperty("deprecation", out _)); - } + Assert.Equal(HttpStatusCode.NoContent, delete.StatusCode); + Assert.False((await CatalogEntryAsync()).TryGetProperty("deprecation", out _)); + } - [Fact] - public async Task AnUnknownReasonIsRejected() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AnUnknownReasonIsRejected() + { + await _app.AddPackageAsync(_packageStream); - using var put = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation", @"{""reasons"":[""Bored""]}"); + using var put = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation", @"{""reasons"":[""Bored""]}"); - Assert.Equal(HttpStatusCode.BadRequest, put.StatusCode); - } + Assert.Equal(HttpStatusCode.BadRequest, put.StatusCode); + } - [Fact] - public async Task AMissingPackageIsNotFound() - { - using var put = await SendAsync(HttpMethod.Put, "v3/package/No.Such/1.0.0/deprecation", @"{""reasons"":[""Legacy""]}"); + [Fact] + public async Task AMissingPackageIsNotFound() + { + using var put = await SendAsync(HttpMethod.Put, "v3/package/No.Such/1.0.0/deprecation", @"{""reasons"":[""Legacy""]}"); - Assert.Equal(HttpStatusCode.NotFound, put.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, put.StatusCode); + } - [Fact] - public async Task AWrongApiKeyIsUnauthorized() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AWrongApiKeyIsUnauthorized() + { + await _app.AddPackageAsync(_packageStream); - using var request = new HttpRequestMessage(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation") - { - Content = new StringContent(@"{""reasons"":[""Legacy""]}", Encoding.UTF8, "application/json"), - }; - request.Headers.Add("X-NuGet-ApiKey", "wrong"); + using var request = new HttpRequestMessage(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation") + { + Content = new StringContent(@"{""reasons"":[""Legacy""]}", Encoding.UTF8, "application/json"), + }; + request.Headers.Add("X-NuGet-ApiKey", "wrong"); - using var response = await _client.SendAsync(request); + using var response = await _client.SendAsync(request); - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } - [Fact] - public async Task VulnerabilitiesAppearInRegistrationAndTheVulnerabilityPage() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task VulnerabilitiesAppearInRegistrationAndTheVulnerabilityPage() + { + await _app.AddPackageAsync(_packageStream); - using var put = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", - @"[{""advisoryUrl"":""https://example.test/advisory/1"",""severity"":2}]"); - Assert.Equal(HttpStatusCode.NoContent, put.StatusCode); + using var put = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", + @"[{""advisoryUrl"":""https://example.test/advisory/1"",""severity"":2}]"); + Assert.Equal(HttpStatusCode.NoContent, put.StatusCode); - var vulnerability = (await CatalogEntryAsync()).GetProperty("vulnerabilities")[0]; - Assert.Equal("https://example.test/advisory/1", vulnerability.GetProperty("advisoryUrl").GetString()); - Assert.Equal("2", vulnerability.GetProperty("severity").GetString()); + var vulnerability = (await CatalogEntryAsync()).GetProperty("vulnerabilities")[0]; + Assert.Equal("https://example.test/advisory/1", vulnerability.GetProperty("advisoryUrl").GetString()); + Assert.Equal("2", vulnerability.GetProperty("severity").GetString()); - using var index = await GetJsonAsync("v3/vulnerabilities/index.json"); - var pageUrl = index.RootElement[0].GetProperty("@id").GetString(); - Assert.Equal("base", index.RootElement[0].GetProperty("@name").GetString()); + using var index = await GetJsonAsync("v3/vulnerabilities/index.json"); + var pageUrl = index.RootElement[0].GetProperty("@id").GetString(); + Assert.Equal("base", index.RootElement[0].GetProperty("@name").GetString()); - using var page = await GetJsonAsync(pageUrl); - var item = page.RootElement.GetProperty("testdata")[0]; - Assert.Equal(2, item.GetProperty("severity").GetInt32()); - Assert.Equal("https://example.test/advisory/1", item.GetProperty("url").GetString()); - Assert.Equal("[1.2.3]", item.GetProperty("versions").GetString()); - } + using var page = await GetJsonAsync(pageUrl); + var item = page.RootElement.GetProperty("testdata")[0]; + Assert.Equal(2, item.GetProperty("severity").GetInt32()); + Assert.Equal("https://example.test/advisory/1", item.GetProperty("url").GetString()); + Assert.Equal("[1.2.3]", item.GetProperty("versions").GetString()); + } - [Fact] - public async Task AnEmptyListClearsTheVulnerabilities() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AnEmptyListClearsTheVulnerabilities() + { + await _app.AddPackageAsync(_packageStream); - (await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", - @"[{""advisoryUrl"":""https://example.test/a"",""severity"":1}]")).Dispose(); - using var clear = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", "[]"); + (await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", + @"[{""advisoryUrl"":""https://example.test/a"",""severity"":1}]")).Dispose(); + using var clear = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", "[]"); - Assert.Equal(HttpStatusCode.NoContent, clear.StatusCode); - Assert.False((await CatalogEntryAsync()).TryGetProperty("vulnerabilities", out _)); + Assert.Equal(HttpStatusCode.NoContent, clear.StatusCode); + Assert.False((await CatalogEntryAsync()).TryGetProperty("vulnerabilities", out _)); - using var page = await GetJsonAsync("v3/vulnerabilities/base.json"); - Assert.Empty(page.RootElement.EnumerateObject()); - } + using var page = await GetJsonAsync("v3/vulnerabilities/base.json"); + Assert.Empty(page.RootElement.EnumerateObject()); + } - [Fact] - public async Task AnOutOfRangeSeverityIsRejected() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AnOutOfRangeSeverityIsRejected() + { + await _app.AddPackageAsync(_packageStream); - using var put = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", - @"[{""advisoryUrl"":""https://example.test/a"",""severity"":4}]"); + using var put = await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", + @"[{""advisoryUrl"":""https://example.test/a"",""severity"":4}]"); - Assert.Equal(HttpStatusCode.BadRequest, put.StatusCode); - } + Assert.Equal(HttpStatusCode.BadRequest, put.StatusCode); + } - [Fact] - public async Task SearchCarriesTheLatestVersionsMetadata() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task SearchCarriesTheLatestVersionsMetadata() + { + await _app.AddPackageAsync(_packageStream); - (await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation", @"{""reasons"":[""CriticalBugs""]}")).Dispose(); - (await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", - @"[{""advisoryUrl"":""https://example.test/a"",""severity"":3}]")).Dispose(); + (await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/deprecation", @"{""reasons"":[""CriticalBugs""]}")).Dispose(); + (await SendAsync(HttpMethod.Put, "v3/package/TestData/1.2.3/vulnerabilities", + @"[{""advisoryUrl"":""https://example.test/a"",""severity"":3}]")).Dispose(); - using var search = await GetJsonAsync("v3/search"); - var result = search.RootElement.GetProperty("data")[0]; + using var search = await GetJsonAsync("v3/search"); + var result = search.RootElement.GetProperty("data")[0]; - Assert.Equal("CriticalBugs", result.GetProperty("deprecation").GetProperty("reasons")[0].GetString()); - Assert.Equal("3", result.GetProperty("vulnerabilities")[0].GetProperty("severity").GetString()); - } + Assert.Equal("CriticalBugs", result.GetProperty("deprecation").GetProperty("reasons")[0].GetString()); + Assert.Equal("3", result.GetProperty("vulnerabilities")[0].GetProperty("severity").GetString()); + } - [Fact] - public async Task AnUnknownVulnerabilityPageIsNotFound() - { - using var response = await _client.GetAsync("v3/vulnerabilities/other.json"); + [Fact] + public async Task AnUnknownVulnerabilityPageIsNotFound() + { + using var response = await _client.GetAsync("v3/vulnerabilities/other.json"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - private async Task SendAsync(HttpMethod method, string url, string body = null) + private async Task SendAsync(HttpMethod method, string url, string body = null) + { + var request = new HttpRequestMessage(method, url); + request.Headers.Add("X-NuGet-ApiKey", ApiKey); + if (body != null) { - var request = new HttpRequestMessage(method, url); - request.Headers.Add("X-NuGet-ApiKey", ApiKey); - if (body != null) - { - request.Content = new StringContent(body, Encoding.UTF8, "application/json"); - } - - return await _client.SendAsync(request); + request.Content = new StringContent(body, Encoding.UTF8, "application/json"); } - private async Task GetJsonAsync(string url) - { - using var response = await _client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return await _client.SendAsync(request); + } - return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - } + private async Task GetJsonAsync(string url) + { + using var response = await _client.GetAsync(url); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); - private async Task CatalogEntryAsync() - { - using var index = await GetJsonAsync("v3/registration/testdata/index.json"); + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + } - return index.RootElement - .GetProperty("items")[0] - .GetProperty("items")[0] - .GetProperty("catalogEntry") - .Clone(); - } + private async Task CatalogEntryAsync() + { + using var index = await GetJsonAsync("v3/registration/testdata/index.json"); - public void Dispose() - { - _app.Dispose(); - _client.Dispose(); - _packageStream.Dispose(); - } + return index.RootElement + .GetProperty("items")[0] + .GetProperty("items")[0] + .GetProperty("catalogEntry") + .Clone(); + } + + public void Dispose() + { + _app.Dispose(); + _client.Dispose(); + _packageStream.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/PathBaseIntegrationTests.cs b/tests/BaGet.Tests/PathBaseIntegrationTests.cs index 5c33bbb50..3c172d102 100644 --- a/tests/BaGet.Tests/PathBaseIntegrationTests.cs +++ b/tests/BaGet.Tests/PathBaseIntegrationTests.cs @@ -6,123 +6,122 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// A reverse proxy may either forward the path base to BaGet, or strip it before +/// forwarding. The URLs BaGet advertises must include the configured path base +/// either way, otherwise clients are sent to addresses that bypass the proxy. +/// +public class PathBaseIntegrationTests : IDisposable { - /// - /// A reverse proxy may either forward the path base to BaGet, or strip it before - /// forwarding. The URLs BaGet advertises must include the configured path base - /// either way, otherwise clients are sent to addresses that bypass the proxy. - /// - public class PathBaseIntegrationTests : IDisposable + private readonly ITestOutputHelper _output; + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public PathBaseIntegrationTests(ITestOutputHelper output) { - private readonly ITestOutputHelper _output; - private readonly BaGetApplication _app; - private readonly HttpClient _client; + _output = output; + _app = new BaGetApplication( + output, + configOverrides: new Dictionary + { + { "PathBase", "/nuget" }, + }); - public PathBaseIntegrationTests(ITestOutputHelper output) - { - _output = output; - _app = new BaGetApplication( - output, - configOverrides: new Dictionary - { - { "PathBase", "/nuget" }, - }); - - _client = _app.CreateDefaultClient(); - } + _client = _app.CreateDefaultClient(); + } - [Fact] - public async Task ServiceIndexUsesPathBaseWhenTheProxyStripsIt() - { - // The proxy rewrote "/nuget/v3/index.json" to "/v3/index.json". - using var response = await _client.GetAsync("v3/index.json"); + [Fact] + public async Task ServiceIndexUsesPathBaseWhenTheProxyStripsIt() + { + // The proxy rewrote "/nuget/v3/index.json" to "/v3/index.json". + using var response = await _client.GetAsync("v3/index.json"); - response.EnsureSuccessStatusCode(); - var content = JObject.Parse(await response.Content.ReadAsStringAsync()); + response.EnsureSuccessStatusCode(); + var content = JObject.Parse(await response.Content.ReadAsStringAsync()); - foreach (var resource in content["resources"]) - { - var id = resource["@id"].Value(); - Assert.StartsWith("http://localhost/nuget/", id); - } + foreach (var resource in content["resources"]) + { + var id = resource["@id"].Value(); + Assert.StartsWith("http://localhost/nuget/", id); } + } - [Fact] - public async Task ServiceIndexUsesPathBaseWhenTheProxyForwardsIt() - { - // The proxy forwarded the path base untouched. - using var response = await _client.GetAsync("nuget/v3/index.json"); + [Fact] + public async Task ServiceIndexUsesPathBaseWhenTheProxyForwardsIt() + { + // The proxy forwarded the path base untouched. + using var response = await _client.GetAsync("nuget/v3/index.json"); - response.EnsureSuccessStatusCode(); - var content = JObject.Parse(await response.Content.ReadAsStringAsync()); + response.EnsureSuccessStatusCode(); + var content = JObject.Parse(await response.Content.ReadAsStringAsync()); - foreach (var resource in content["resources"]) - { - var id = resource["@id"].Value(); - Assert.StartsWith("http://localhost/nuget/", id); - } + foreach (var resource in content["resources"]) + { + var id = resource["@id"].Value(); + Assert.StartsWith("http://localhost/nuget/", id); } + } - [Fact] - public async Task ADotPathBaseMeansTheRoot() - { - // appsettings.json ships "PathBase": ".", which is not a usable PathString. - using var app = new BaGetApplication( - _output, - configOverrides: new Dictionary { { "PathBase", "." } }); - using var client = app.CreateDefaultClient(); - - using var response = await client.GetAsync("v3/index.json"); + [Fact] + public async Task ADotPathBaseMeansTheRoot() + { + // appsettings.json ships "PathBase": ".", which is not a usable PathString. + using var app = new BaGetApplication( + _output, + configOverrides: new Dictionary { { "PathBase", "." } }); + using var client = app.CreateDefaultClient(); - response.EnsureSuccessStatusCode(); - var content = JObject.Parse(await response.Content.ReadAsStringAsync()); + using var response = await client.GetAsync("v3/index.json"); - foreach (var resource in content["resources"]) - { - Assert.StartsWith("http://localhost/", resource["@id"].Value()); - } - } + response.EnsureSuccessStatusCode(); + var content = JObject.Parse(await response.Content.ReadAsStringAsync()); - [Fact] - public async Task APathBaseMissingItsLeadingSlashStillApplies() + foreach (var resource in content["resources"]) { - using var app = new BaGetApplication( - _output, - configOverrides: new Dictionary { { "PathBase", "nuget" } }); - using var client = app.CreateDefaultClient(); + Assert.StartsWith("http://localhost/", resource["@id"].Value()); + } + } - using var response = await client.GetAsync("v3/index.json"); + [Fact] + public async Task APathBaseMissingItsLeadingSlashStillApplies() + { + using var app = new BaGetApplication( + _output, + configOverrides: new Dictionary { { "PathBase", "nuget" } }); + using var client = app.CreateDefaultClient(); - response.EnsureSuccessStatusCode(); - var content = JObject.Parse(await response.Content.ReadAsStringAsync()); + using var response = await client.GetAsync("v3/index.json"); - foreach (var resource in content["resources"]) - { - Assert.StartsWith("http://localhost/nuget/", resource["@id"].Value()); - } - } + response.EnsureSuccessStatusCode(); + var content = JObject.Parse(await response.Content.ReadAsStringAsync()); - [Theory] - [InlineData(null, "")] - [InlineData("", "")] - [InlineData(" ", "")] - [InlineData(".", "")] - [InlineData("/", "")] - [InlineData("/nuget", "/nuget")] - [InlineData("nuget", "/nuget")] - [InlineData("/nuget/", "/nuget")] - [InlineData("/nuget/feed", "/nuget/feed")] - public void NormalizePathBaseMapsConfiguredValues(string configured, string expected) + foreach (var resource in content["resources"]) { - Assert.Equal(expected, BaGet.Program.NormalizePathBase(configured).Value ?? ""); + Assert.StartsWith("http://localhost/nuget/", resource["@id"].Value()); } + } - public void Dispose() - { - _client?.Dispose(); - _app?.Dispose(); - } + [Theory] + [InlineData(null, "")] + [InlineData("", "")] + [InlineData(" ", "")] + [InlineData(".", "")] + [InlineData("/", "")] + [InlineData("/nuget", "/nuget")] + [InlineData("nuget", "/nuget")] + [InlineData("/nuget/", "/nuget")] + [InlineData("/nuget/feed", "/nuget/feed")] + public void NormalizePathBaseMapsConfiguredValues(string configured, string expected) + { + Assert.Equal(expected, BaGet.Program.NormalizePathBase(configured).Value ?? ""); + } + + public void Dispose() + { + _client?.Dispose(); + _app?.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/ReportAbusePageTests.cs b/tests/BaGet.Tests/ReportAbusePageTests.cs index 2c5e49625..709a765a2 100644 --- a/tests/BaGet.Tests/ReportAbusePageTests.cs +++ b/tests/BaGet.Tests/ReportAbusePageTests.cs @@ -5,67 +5,66 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// The service index advertises a ReportAbuseUriTemplate, so the address a client +/// expands that template into has to resolve to a page rather than a 404. +/// +public class ReportAbusePageTests : IDisposable { - /// - /// The service index advertises a ReportAbuseUriTemplate, so the address a client - /// expands that template into has to resolve to a page rather than a 404. - /// - public class ReportAbusePageTests : IDisposable - { - private readonly BaGetApplication _app; - private readonly HttpClient _client; + private readonly BaGetApplication _app; + private readonly HttpClient _client; - public ReportAbusePageTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); - _client = _app.CreateDefaultClient(); - } + public ReportAbusePageTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output); + _client = _app.CreateDefaultClient(); + } - [Fact] - public async Task TheExpandedTemplateResolves() - { - using var response = await _client.GetAsync("packages/TestData/1.2.3/report-abuse"); + [Fact] + public async Task TheExpandedTemplateResolves() + { + using var response = await _client.GetAsync("packages/TestData/1.2.3/report-abuse"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - [Fact] - public async Task ThePageNamesThePackage() - { - using var response = await _client.GetAsync("packages/TestData/1.2.3/report-abuse"); + [Fact] + public async Task ThePageNamesThePackage() + { + using var response = await _client.GetAsync("packages/TestData/1.2.3/report-abuse"); - var content = await response.Content.ReadAsStringAsync(); - Assert.Contains("TestData", content); - Assert.Contains("1.2.3", content); - } + var content = await response.Content.ReadAsStringAsync(); + Assert.Contains("TestData", content); + Assert.Contains("1.2.3", content); + } - [Fact] - public async Task ItResolvesForAPackageThatDoesNotExist() - { - // A client expands the template from whatever it is looking at, so the page - // must not depend on the package being present. - using var response = await _client.GetAsync("packages/No.Such.Package/9.9.9/report-abuse"); + [Fact] + public async Task ItResolvesForAPackageThatDoesNotExist() + { + // A client expands the template from whatever it is looking at, so the page + // must not depend on the package being present. + using var response = await _client.GetAsync("packages/No.Such.Package/9.9.9/report-abuse"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } - [Fact] - public async Task TheVersionLessUrlIsNotTheReportAbusePage() - { - // The package page owns "/packages/{id}/{version?}", so a three segment URL - // is read as that page with "report-abuse" as the version, not as this page. - // The template always supplies a version, so nothing expands to it. - using var response = await _client.GetAsync("packages/TestData/report-abuse"); + [Fact] + public async Task TheVersionLessUrlIsNotTheReportAbusePage() + { + // The package page owns "/packages/{id}/{version?}", so a three segment URL + // is read as that page with "report-abuse" as the version, not as this page. + // The template always supplies a version, so nothing expands to it. + using var response = await _client.GetAsync("packages/TestData/report-abuse"); - var content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("Report abuse", content); - } + var content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Report abuse", content); + } - public void Dispose() - { - _client?.Dispose(); - _app?.Dispose(); - } + public void Dispose() + { + _client?.Dispose(); + _app?.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/SessionPrincipalTests.cs b/tests/BaGet.Tests/SessionPrincipalTests.cs index bedc56bb2..dccd72571 100644 --- a/tests/BaGet.Tests/SessionPrincipalTests.cs +++ b/tests/BaGet.Tests/SessionPrincipalTests.cs @@ -13,155 +13,154 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// A signed-in browser session carries every scope, so the UI can do what the user's own +/// API key could - and no more: ownership still decides which IDs it may touch. +/// +public class SessionPrincipalTests : IDisposable { - /// - /// A signed-in browser session carries every scope, so the UI can do what the user's own - /// API key could - and no more: ownership still decides which IDs it may touch. - /// - public class SessionPrincipalTests : IDisposable - { - private const string GlobalKey = "global-key"; + private const string GlobalKey = "global-key"; - private readonly BaGetApplication _app; - private readonly HttpClient _client; + private readonly BaGetApplication _app; + private readonly HttpClient _client; - public SessionPrincipalTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "ApiKey", GlobalKey }, - { "Accounts:Enabled", "true" }, - }); - _client = _app.CreateClient(); - } - - [Fact] - public async Task ASessionCarriesEveryScopeButIsNotTheSuperuser() + public SessionPrincipalTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary { - var alice = await CreateUserAsync("alice"); + { "ApiKey", GlobalKey }, + { "Accounts:Enabled", "true" }, + }); + _client = _app.CreateClient(); + } - var principal = await SessionPrincipalAsync(alice); + [Fact] + public async Task ASessionCarriesEveryScopeButIsNotTheSuperuser() + { + var alice = await CreateUserAsync("alice"); - Assert.Equal(alice.Id, principal.UserId); - Assert.Equal("alice", principal.UserName); - Assert.False(principal.IsSuperuser); - Assert.Equal(ApiKeyScopes.All.OrderBy(s => s), principal.Scopes.OrderBy(s => s)); - Assert.True(principal.MatchesPackage("Anything.At.All")); - } + var principal = await SessionPrincipalAsync(alice); - [Fact] - public void AnAnonymousSessionHasNoPrincipal() - { - using var scope = _app.Services.CreateScope(); - var factory = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(alice.Id, principal.UserId); + Assert.Equal("alice", principal.UserName); + Assert.False(principal.IsSuperuser); + Assert.Equal(ApiKeyScopes.All.OrderBy(s => s), principal.Scopes.OrderBy(s => s)); + Assert.True(principal.MatchesPackage("Anything.At.All")); + } - Assert.Null(factory.Create(new ClaimsPrincipal(new ClaimsIdentity()))); - Assert.Null(factory.Create(null)); - } + [Fact] + public void AnAnonymousSessionHasNoPrincipal() + { + using var scope = _app.Services.CreateScope(); + var factory = scope.ServiceProvider.GetRequiredService(); - [Fact] - public async Task ASessionCanPushANewIdAndItsOwnPackages() - { - var alice = await CreateUserAsync("alice"); - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + Assert.Null(factory.Create(new ClaimsPrincipal(new ClaimsIdentity()))); + Assert.Null(factory.Create(null)); + } - var principal = await SessionPrincipalAsync(alice); + [Fact] + public async Task ASessionCanPushANewIdAndItsOwnPackages() + { + var alice = await CreateUserAsync("alice"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - Assert.True(await AuthorizeAsync(principal, PackageAction.Push, "Brand.New.Id")); - Assert.True(await AuthorizeAsync(principal, PackageAction.Push, "Alice.Package")); - Assert.True(await AuthorizeAsync(principal, PackageAction.Manage, "Alice.Package")); - } + var principal = await SessionPrincipalAsync(alice); - [Fact] - public async Task ASessionCannotPushAnIdOwnedByAnotherUser() - { - var alice = await CreateUserAsync("alice"); - var bob = await CreateUserAsync("bob"); - await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); + Assert.True(await AuthorizeAsync(principal, PackageAction.Push, "Brand.New.Id")); + Assert.True(await AuthorizeAsync(principal, PackageAction.Push, "Alice.Package")); + Assert.True(await AuthorizeAsync(principal, PackageAction.Manage, "Alice.Package")); + } - var principal = await SessionPrincipalAsync(bob); + [Fact] + public async Task ASessionCannotPushAnIdOwnedByAnotherUser() + { + var alice = await CreateUserAsync("alice"); + var bob = await CreateUserAsync("bob"); + await PushAsync("Alice.Package", "1.0.0", await CreateKeyAsync(alice, ApiKeyScopes.Push)); - // Bob's session is as privileged as any of his keys, which is to say: not on - // Alice's package. - Assert.False(await AuthorizeAsync(principal, PackageAction.Push, "Alice.Package")); - Assert.False(await AuthorizeAsync(principal, PackageAction.Manage, "Alice.Package")); + var principal = await SessionPrincipalAsync(bob); - // The same session on his own ID, so the refusal above is ownership and not an - // unusable principal. - Assert.True(await AuthorizeAsync(principal, PackageAction.Push, "Bob.Package")); - } + // Bob's session is as privileged as any of his keys, which is to say: not on + // Alice's package. + Assert.False(await AuthorizeAsync(principal, PackageAction.Push, "Alice.Package")); + Assert.False(await AuthorizeAsync(principal, PackageAction.Manage, "Alice.Package")); - [Fact] - public async Task ASessionCannotPushAnIdThatPredatesAccounts() - { - await PushAsync("Legacy.Package", "1.0.0", GlobalKey); - var alice = await CreateUserAsync("alice"); + // The same session on his own ID, so the refusal above is ownership and not an + // unusable principal. + Assert.True(await AuthorizeAsync(principal, PackageAction.Push, "Bob.Package")); + } - Assert.False(await AuthorizeAsync(await SessionPrincipalAsync(alice), PackageAction.Push, "Legacy.Package")); - } + [Fact] + public async Task ASessionCannotPushAnIdThatPredatesAccounts() + { + await PushAsync("Legacy.Package", "1.0.0", GlobalKey); + var alice = await CreateUserAsync("alice"); - private async Task SessionPrincipalAsync(BaGetUser user) - { - using var scope = _app.Services.CreateScope(); + Assert.False(await AuthorizeAsync(await SessionPrincipalAsync(alice), PackageAction.Push, "Legacy.Package")); + } - // The claims the sign-in cookie would carry, built the way sign-in builds them. - var claims = await scope.ServiceProvider - .GetRequiredService>() - .CreateAsync(user); + private async Task SessionPrincipalAsync(BaGetUser user) + { + using var scope = _app.Services.CreateScope(); - var principal = scope.ServiceProvider - .GetRequiredService() - .Create(claims); + // The claims the sign-in cookie would carry, built the way sign-in builds them. + var claims = await scope.ServiceProvider + .GetRequiredService>() + .CreateAsync(user); - Assert.NotNull(principal); + var principal = scope.ServiceProvider + .GetRequiredService() + .Create(claims); - return principal; - } + Assert.NotNull(principal); - private async Task AuthorizeAsync(BaGetPrincipal principal, PackageAction action, string packageId) - { - using var scope = _app.Services.CreateScope(); - var authorization = scope.ServiceProvider.GetRequiredService(); + return principal; + } - return await authorization.AuthorizeAsync(principal, action, packageId, CancellationToken.None); - } + private async Task AuthorizeAsync(BaGetPrincipal principal, PackageAction action, string packageId) + { + using var scope = _app.Services.CreateScope(); + var authorization = scope.ServiceProvider.GetRequiredService(); - private async Task PushAsync(string id, string version, string apiKey) - { - using var package = TestPackages.Build(id, version); - using var request = TestPackages.PushRequest(package, apiKey); - using var response = await _client.SendAsync(request); + return await authorization.AuthorizeAsync(principal, action, packageId, CancellationToken.None); + } - Assert.Equal(HttpStatusCode.Created, response.StatusCode); + private async Task PushAsync(string id, string version, string apiKey) + { + using var package = TestPackages.Build(id, version); + using var request = TestPackages.PushRequest(package, apiKey); + using var response = await _client.SendAsync(request); - return response.StatusCode; - } + Assert.Equal(HttpStatusCode.Created, response.StatusCode); - private async Task CreateUserAsync(string name) - { - using var scope = _app.Services.CreateScope(); - var users = scope.ServiceProvider.GetRequiredService>(); - var user = new BaGetUser { UserName = name }; + return response.StatusCode; + } - var result = await users.CreateAsync(user, "Passw0rd!"); - Assert.True(result.Succeeded, string.Join(" ", result.Errors.Select(e => e.Description))); + private async Task CreateUserAsync(string name) + { + using var scope = _app.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + var user = new BaGetUser { UserName = name }; - return user; - } + var result = await users.CreateAsync(user, "Passw0rd!"); + Assert.True(result.Succeeded, string.Join(" ", result.Errors.Select(e => e.Description))); - private async Task CreateKeyAsync(BaGetUser user, string scopeName) - { - using var scope = _app.Services.CreateScope(); - var keys = scope.ServiceProvider.GetRequiredService(); + return user; + } - return await keys.CreateAsync(user.Id, "test", new[] { scopeName }, "*", null, CancellationToken.None); - } + private async Task CreateKeyAsync(BaGetUser user, string scopeName) + { + using var scope = _app.Services.CreateScope(); + var keys = scope.ServiceProvider.GetRequiredService(); - public void Dispose() - { - _app.Dispose(); - _client.Dispose(); - } + return await keys.CreateAsync(user.Id, "test", new[] { scopeName }, "*", null, CancellationToken.None); + } + + public void Dispose() + { + _app.Dispose(); + _client.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/StagingIntegrationTests.cs b/tests/BaGet.Tests/StagingIntegrationTests.cs index 8d74e16b9..d45cef04b 100644 --- a/tests/BaGet.Tests/StagingIntegrationTests.cs +++ b/tests/BaGet.Tests/StagingIntegrationTests.cs @@ -10,68 +10,67 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Staging on the real host, with accounts off: the mode that authenticates with a +/// pasted API key stages files too, so the service must resolve there as well. +/// +public class StagingIntegrationTests : IDisposable { - /// - /// Staging on the real host, with accounts off: the mode that authenticates with a - /// pasted API key stages files too, so the service must resolve there as well. - /// - public class StagingIntegrationTests : IDisposable + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public StagingIntegrationTests(ITestOutputHelper output) { - private readonly BaGetApplication _app; - private readonly HttpClient _client; + _app = new BaGetApplication(output); + _client = _app.CreateClient(); + } - public StagingIntegrationTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); - _client = _app.CreateClient(); - } + [Fact] + public async Task StagesAndForgetsAPackageWithoutAccounts() + { + var staging = Staging(); - [Fact] - public async Task StagesAndForgetsAPackageWithoutAccounts() - { - var staging = Staging(); + var token = await staging.StageAsync(Package(), ownerId: null, CancellationToken.None); - var token = await staging.StageAsync(Package(), ownerId: null, CancellationToken.None); + using (var staged = await staging.OpenAsync(token, ownerId: null, CancellationToken.None)) + { + Assert.NotNull(staged); + } - using (var staged = await staging.OpenAsync(token, ownerId: null, CancellationToken.None)) - { - Assert.NotNull(staged); - } + Assert.True(await staging.RemoveAsync(token, ownerId: null, CancellationToken.None)); - Assert.True(await staging.RemoveAsync(token, ownerId: null, CancellationToken.None)); + Assert.Null(await staging.OpenAsync(token, ownerId: null, CancellationToken.None)); + } - Assert.Null(await staging.OpenAsync(token, ownerId: null, CancellationToken.None)); - } + [Fact] + public async Task AStagedFileIsNotServedOverHttp() + { + var token = await Staging().StageAsync(Package(), ownerId: null, CancellationToken.None); - [Fact] - public async Task AStagedFileIsNotServedOverHttp() + // No route accepts a storage path: every storage read is composed from a + // database-resolved ID and version, or from a validated symbol key. + foreach (var url in new[] + { + $"staging/{token}.nupkg", + $"v3/package/staging/{token}/{token}.nupkg", + }) { - var token = await Staging().StageAsync(Package(), ownerId: null, CancellationToken.None); - - // No route accepts a storage path: every storage read is composed from a - // database-resolved ID and version, or from a validated symbol key. - foreach (var url in new[] - { - $"staging/{token}.nupkg", - $"v3/package/staging/{token}/{token}.nupkg", - }) - { - using var response = await _client.GetAsync(url); + using var response = await _client.GetAsync(url); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } + } - private IPackageStagingService Staging() - => _app.Services.GetRequiredService(); + private IPackageStagingService Staging() + => _app.Services.GetRequiredService(); - private static Stream Package() => new MemoryStream(Encoding.UTF8.GetBytes("a package")); + private static Stream Package() => new MemoryStream(Encoding.UTF8.GetBytes("a package")); - public void Dispose() - { - _app.Dispose(); - _client.Dispose(); - } + public void Dispose() + { + _app.Dispose(); + _client.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/StaticAssetsTests.cs b/tests/BaGet.Tests/StaticAssetsTests.cs index 6052220da..9c5cff3ff 100644 --- a/tests/BaGet.Tests/StaticAssetsTests.cs +++ b/tests/BaGet.Tests/StaticAssetsTests.cs @@ -7,51 +7,50 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// The layout's stylesheets, scripts and icon come from the Razor class libraries' +/// static web assets. Their URLs must not depend on how the projects are packaged. +/// +public class StaticAssetsTests : IDisposable { - /// - /// The layout's stylesheets, scripts and icon come from the Razor class libraries' - /// static web assets. Their URLs must not depend on how the projects are packaged. - /// - public class StaticAssetsTests : IDisposable - { - private readonly BaGetApplication _app; - private readonly HttpClient _client; + private readonly BaGetApplication _app; + private readonly HttpClient _client; - public StaticAssetsTests(ITestOutputHelper output) - { - // Development, as Visual Studio runs it: the assets are served from the build - // output's static web assets manifest rather than a published wwwroot. - _app = new BaGetApplication(output, environment: "Development"); - _client = _app.CreateClient(); - } + public StaticAssetsTests(ITestOutputHelper output) + { + // Development, as Visual Studio runs it: the assets are served from the build + // output's static web assets manifest rather than a published wwwroot. + _app = new BaGetApplication(output, environment: "Development"); + _client = _app.CreateClient(); + } - [Theory] - [InlineData("")] - [InlineData("upload")] - [InlineData("stats")] - public async Task EveryAssetThePageReferencesIsServed(string page) - { - var html = await _client.GetStringAsync(page); + [Theory] + [InlineData("")] + [InlineData("upload")] + [InlineData("stats")] + public async Task EveryAssetThePageReferencesIsServed(string page) + { + var html = await _client.GetStringAsync(page); - var assets = Regex.Matches(html, "(?:href|src)=\"(/_content/[^\"]+)\"") - .Select(m => m.Groups[1].Value) - .Distinct() - .ToList(); + var assets = Regex.Matches(html, "(?:href|src)=\"(/_content/[^\"]+)\"") + .Select(m => m.Groups[1].Value) + .Distinct() + .ToList(); - Assert.NotEmpty(assets); - foreach (var asset in assets) - { - using var response = await _client.GetAsync(asset); + Assert.NotEmpty(assets); + foreach (var asset in assets) + { + using var response = await _client.GetAsync(asset); - Assert.True(response.StatusCode == HttpStatusCode.OK, $"{asset} answered {(int)response.StatusCode}"); - } + Assert.True(response.StatusCode == HttpStatusCode.OK, $"{asset} answered {(int)response.StatusCode}"); } + } - public void Dispose() - { - _client.Dispose(); - _app.Dispose(); - } + public void Dispose() + { + _client.Dispose(); + _app.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/BaGetApplication.cs b/tests/BaGet.Tests/Support/BaGetApplication.cs index cd7a1c1c1..ccd43eb43 100644 --- a/tests/BaGet.Tests/Support/BaGetApplication.cs +++ b/tests/BaGet.Tests/Support/BaGetApplication.cs @@ -16,158 +16,157 @@ using Moq; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +public class BaGetApplication : WebApplicationFactory { - public class BaGetApplication : WebApplicationFactory + private readonly ITestOutputHelper _output; + private readonly HttpClient _upstreamClient; + private readonly Dictionary _configOverrides; + private readonly Action _configureServices; + private readonly string _environment; + + /// + /// "Production" by default. "Development" serves the Razor class libraries' static web + /// assets from the build output, as running from Visual Studio does. + /// + public BaGetApplication( + ITestOutputHelper output, + HttpClient upstreamClient = null, + Dictionary configOverrides = null, + Action configureServices = null, + string environment = "Production") + { + _configureServices = configureServices; + _environment = environment; + _output = output ?? throw new ArgumentNullException(nameof(output)); + _upstreamClient = upstreamClient; + _configOverrides = configOverrides; + } + + protected override void ConfigureWebHost(IWebHostBuilder builder) { - private readonly ITestOutputHelper _output; - private readonly HttpClient _upstreamClient; - private readonly Dictionary _configOverrides; - private readonly Action _configureServices; - private readonly string _environment; - - /// - /// "Production" by default. "Development" serves the Razor class libraries' static web - /// assets from the build output, as running from Visual Studio does. - /// - public BaGetApplication( - ITestOutputHelper output, - HttpClient upstreamClient = null, - Dictionary configOverrides = null, - Action configureServices = null, - string environment = "Production") + // Create temporary storage paths. + var tempPath = Path.Combine( + Path.GetTempPath(), + "BaGetTests", + Guid.NewGuid().ToString("N")); + var sqlitePath = Path.Combine(tempPath, "BaGet.db"); + var storagePath = Path.Combine(tempPath, "Packages"); + + Directory.CreateDirectory(tempPath); + + // Setup the integration test configuration. + var settings = new Dictionary + { + { "Database:Type", "Sqlite" }, + { "Database:ConnectionString", $"Data Source={sqlitePath}" }, + { "Storage:Type", "FileSystem" }, + { "Storage:Path", storagePath }, + { "Search:Type", "Database" }, + { "Mirror:Enabled", _upstreamClient != null ? "true": "false" }, + { "Mirror:PackageSource", "http://localhost/v3/index.json" }, + }; + + foreach (var pair in _configOverrides ?? new Dictionary()) { - _configureServices = configureServices; - _environment = environment; - _output = output ?? throw new ArgumentNullException(nameof(output)); - _upstreamClient = upstreamClient; - _configOverrides = configOverrides; + settings[pair.Key] = pair.Value; } - protected override void ConfigureWebHost(IWebHostBuilder builder) + // These are applied with UseSetting rather than ConfigureAppConfiguration so + // that they are in place before the application registers its services. Under + // the minimal hosting model the entry point reads builder.Configuration while + // registering - AddBaGetAccounts decides from "Accounts:Enabled", for one - and + // a provider appended afterwards would arrive too late for those reads. + foreach (var pair in settings) { - // Create temporary storage paths. - var tempPath = Path.Combine( - Path.GetTempPath(), - "BaGetTests", - Guid.NewGuid().ToString("N")); - var sqlitePath = Path.Combine(tempPath, "BaGet.db"); - var storagePath = Path.Combine(tempPath, "Packages"); - - Directory.CreateDirectory(tempPath); - - // Setup the integration test configuration. - var settings = new Dictionary - { - { "Database:Type", "Sqlite" }, - { "Database:ConnectionString", $"Data Source={sqlitePath}" }, - { "Storage:Type", "FileSystem" }, - { "Storage:Path", storagePath }, - { "Search:Type", "Database" }, - { "Mirror:Enabled", _upstreamClient != null ? "true": "false" }, - { "Mirror:PackageSource", "http://localhost/v3/index.json" }, - }; - - foreach (var pair in _configOverrides ?? new Dictionary()) + builder.UseSetting(pair.Key, pair.Value); + } + + builder + .UseEnvironment(_environment) + .ConfigureLogging(logging => { - settings[pair.Key] = pair.Value; - } - - // These are applied with UseSetting rather than ConfigureAppConfiguration so - // that they are in place before the application registers its services. Under - // the minimal hosting model the entry point reads builder.Configuration while - // registering - AddBaGetAccounts decides from "Accounts:Enabled", for one - and - // a provider appended afterwards would arrive too late for those reads. - foreach (var pair in settings) + // BaGet uses console logging by default. This logger throws operation + // cancelled exceptions when the host shuts down, causing the the debugger + // to pause repeatedly if CLR exceptions are enabled. + logging.ClearProviders(); + + // Pipe logs to the xunit output. + logging.AddProvider(new XunitLoggerProvider(_output)); + }) + .ConfigureServices(services => { }) + .ConfigureServices((context, services) => { - builder.UseSetting(pair.Key, pair.Value); - } - - builder - .UseEnvironment(_environment) - .ConfigureLogging(logging => + // Make time deterministic for testing purposes. + var time = new Mock(); + time + .Setup(t => t.UtcNow) + // DateTime.Parse converts a "Z" timestamp to local time, so the + // mock would return a local DateTime from a property that is + // documented, and implemented, as returning UTC. + .Returns(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)); + + services.AddSingleton(time.Object); + _configureServices?.Invoke(services); + if (_upstreamClient != null) { - // BaGet uses console logging by default. This logger throws operation - // cancelled exceptions when the host shuts down, causing the the debugger - // to pause repeatedly if CLR exceptions are enabled. - logging.ClearProviders(); - - // Pipe logs to the xunit output. - logging.AddProvider(new XunitLoggerProvider(_output)); - }) - .ConfigureServices(services => { }) - .ConfigureServices((context, services) => - { - // Make time deterministic for testing purposes. - var time = new Mock(); - time - .Setup(t => t.UtcNow) - // DateTime.Parse converts a "Z" timestamp to local time, so the - // mock would return a local DateTime from a property that is - // documented, and implemented, as returning UTC. - .Returns(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)); - - services.AddSingleton(time.Object); - _configureServices?.Invoke(services); - if (_upstreamClient != null) - { - services.AddSingleton(_upstreamClient); - } - - // Setup the integration test database. - var provider = services.BuildServiceProvider(); - var scopeFactory = provider.GetRequiredService(); - - // Ensure the database is created before we run migrations. The migrations - // can create the database too, however, migrations check whether the database exists - // first. The SQLite provider implements this by attempting to open a connection, - // and if that fails, creating the database. This throws several exceptions that - // pauses the debugger repeatedly if CLR exceptions are enabled. - // See: https://github.com/dotnet/efcore/blob/644d3c8c3a604fd0121d90eaf34f14870e19bcff/src/EFCore.Sqlite.Core/Storage/Internal/SqliteDatabaseCreator.cs#L88-L98 - using var scope = scopeFactory.CreateScope(); - var ctx = scope.ServiceProvider.GetRequiredService(); - var dbCreator = ctx.Database.GetService(); - - dbCreator.Create(); - ctx.Database.Migrate(); - }); - } + services.AddSingleton(_upstreamClient); + } + + // Setup the integration test database. + var provider = services.BuildServiceProvider(); + var scopeFactory = provider.GetRequiredService(); + + // Ensure the database is created before we run migrations. The migrations + // can create the database too, however, migrations check whether the database exists + // first. The SQLite provider implements this by attempting to open a connection, + // and if that fails, creating the database. This throws several exceptions that + // pauses the debugger repeatedly if CLR exceptions are enabled. + // See: https://github.com/dotnet/efcore/blob/644d3c8c3a604fd0121d90eaf34f14870e19bcff/src/EFCore.Sqlite.Core/Storage/Internal/SqliteDatabaseCreator.cs#L88-L98 + using var scope = scopeFactory.CreateScope(); + var ctx = scope.ServiceProvider.GetRequiredService(); + var dbCreator = ctx.Database.GetService(); + + dbCreator.Create(); + ctx.Database.Migrate(); + }); } +} - internal static class BaGetWebApplicationFactoryExtensions +internal static class BaGetWebApplicationFactoryExtensions +{ + public static async Task AddPackageAsync( + this WebApplicationFactory factory, + Stream package, + CancellationToken cancellationToken = default) { - public static async Task AddPackageAsync( - this WebApplicationFactory factory, - Stream package, - CancellationToken cancellationToken = default) - { - var scopeFactory = factory.Services.GetRequiredService(); + var scopeFactory = factory.Services.GetRequiredService(); - using var scope = scopeFactory.CreateScope(); - var indexer = scope.ServiceProvider.GetRequiredService(); + using var scope = scopeFactory.CreateScope(); + var indexer = scope.ServiceProvider.GetRequiredService(); - var result = await indexer.IndexAsync(package, cancellationToken); - if (result != PackageIndexingResult.Success) - { - throw new InvalidOperationException($"Unexpected indexing result {result}"); - } + var result = await indexer.IndexAsync(package, cancellationToken); + if (result != PackageIndexingResult.Success) + { + throw new InvalidOperationException($"Unexpected indexing result {result}"); } + } - public static async Task AddSymbolPackageAsync( - this WebApplicationFactory factory, - Stream symbolPackage, - CancellationToken cancellationToken = default) - { - var scopeFactory = factory.Services.GetRequiredService(); + public static async Task AddSymbolPackageAsync( + this WebApplicationFactory factory, + Stream symbolPackage, + CancellationToken cancellationToken = default) + { + var scopeFactory = factory.Services.GetRequiredService(); - using var scope = scopeFactory.CreateScope(); - var indexer = scope.ServiceProvider.GetRequiredService(); + using var scope = scopeFactory.CreateScope(); + var indexer = scope.ServiceProvider.GetRequiredService(); - var result = await indexer.IndexAsync(symbolPackage, cancellationToken); - if (result != SymbolIndexingResult.Success) - { - throw new InvalidOperationException($"Unexpected indexing result {result}"); - } + var result = await indexer.IndexAsync(symbolPackage, cancellationToken); + if (result != SymbolIndexingResult.Success) + { + throw new InvalidOperationException($"Unexpected indexing result {result}"); } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/Browser.cs b/tests/BaGet.Tests/Support/Browser.cs index f8c922ba6..33cb9d0a3 100644 --- a/tests/BaGet.Tests/Support/Browser.cs +++ b/tests/BaGet.Tests/Support/Browser.cs @@ -8,107 +8,106 @@ using Microsoft.AspNetCore.Mvc.Testing; using Xunit; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Drives the Razor pages as a browser would: cookies kept, redirects not followed, and +/// each form posted with the antiforgery token its page rendered. +/// +internal sealed class Browser : System.IDisposable { - /// - /// Drives the Razor pages as a browser would: cookies kept, redirects not followed, and - /// each form posted with the antiforgery token its page rendered. - /// - internal sealed class Browser : System.IDisposable + private readonly HttpClient _client; + + public Browser(BaGetApplication app) { - private readonly HttpClient _client; + _client = app.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + } - public Browser(BaGetApplication app) - { - _client = app.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); - } + public Task GetAsync(string url) => _client.GetAsync(url); - public Task GetAsync(string url) => _client.GetAsync(url); + public async Task GetPageAsync(string url) + { + using var response = await _client.GetAsync(url); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); - public async Task GetPageAsync(string url) - { - using var response = await _client.GetAsync(url); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return await response.Content.ReadAsStringAsync(); + } - return await response.Content.ReadAsStringAsync(); - } + /// + /// An antiforgery token for this session, taken from a page that renders a form. The + /// token is per session rather than per form, so a page that renders no form - the + /// upload page in read-only mode, for one - can still be posted to the way a + /// hand-written request would. + /// + public async Task TokenAsync(string page) + => Regex + .Match( + await GetPageAsync(page), + "name=\"__RequestVerificationToken\" type=\"hidden\" value=\"([^\"]+)\"") + .Groups[1] + .Value; - /// - /// An antiforgery token for this session, taken from a page that renders a form. The - /// token is per session rather than per form, so a page that renders no form - the - /// upload page in read-only mode, for one - can still be posted to the way a - /// hand-written request would. - /// - public async Task TokenAsync(string page) - => Regex - .Match( - await GetPageAsync(page), - "name=\"__RequestVerificationToken\" type=\"hidden\" value=\"([^\"]+)\"") - .Groups[1] - .Value; - - /// - /// Load , then post to - /// (the page itself by default). - /// - /// - /// Where to read the antiforgery token from, if not . - /// - public async Task PostAsync( - string page, - Dictionary fields, - string action = null, - string tokenPage = null) - { - fields["__RequestVerificationToken"] = await TokenAsync(tokenPage ?? page); + /// + /// Load , then post to + /// (the page itself by default). + /// + /// + /// Where to read the antiforgery token from, if not . + /// + public async Task PostAsync( + string page, + Dictionary fields, + string action = null, + string tokenPage = null) + { + fields["__RequestVerificationToken"] = await TokenAsync(tokenPage ?? page); - return await _client.PostAsync(action ?? page, new FormUrlEncodedContent(fields)); - } + return await _client.PostAsync(action ?? page, new FormUrlEncodedContent(fields)); + } - /// - /// Post a file and some fields as multipart/form-data, as a form with a file input - /// does. - /// - public async Task PostFileAsync( - string action, - string fieldName, - string fileName, - Stream file, - Dictionary fields = null, - string tokenPage = null) - { - using var content = new MultipartFormDataContent(); + /// + /// Post a file and some fields as multipart/form-data, as a form with a file input + /// does. + /// + public async Task PostFileAsync( + string action, + string fieldName, + string fileName, + Stream file, + Dictionary fields = null, + string tokenPage = null) + { + using var content = new MultipartFormDataContent(); - // Added last, as the form tag helper's hidden field is rendered last: antiforgery - // reads the whole body before model binding, so the order does not matter. - foreach (var pair in fields ?? new Dictionary()) - { - content.Add(new StringContent(pair.Value), pair.Key); - } + // Added last, as the form tag helper's hidden field is rendered last: antiforgery + // reads the whole body before model binding, so the order does not matter. + foreach (var pair in fields ?? new Dictionary()) + { + content.Add(new StringContent(pair.Value), pair.Key); + } - var fileContent = new StreamContent(file); - fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); - content.Add(fileContent, fieldName, fileName); + var fileContent = new StreamContent(file); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + content.Add(fileContent, fieldName, fileName); - content.Add( - new StringContent(await TokenAsync(tokenPage ?? action.Split('?')[0])), - "__RequestVerificationToken"); + content.Add( + new StringContent(await TokenAsync(tokenPage ?? action.Split('?')[0])), + "__RequestVerificationToken"); - return await _client.PostAsync(action, content); - } + return await _client.PostAsync(action, content); + } - public async Task RegisterAsync(string userName) + public async Task RegisterAsync(string userName) + { + using var response = await PostAsync("account/register", new Dictionary { - using var response = await PostAsync("account/register", new Dictionary - { - { "UserName", userName }, - { "Password", "Passw0rd!" }, - { "ConfirmPassword", "Passw0rd!" }, - }); - - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - } + { "UserName", userName }, + { "Password", "Passw0rd!" }, + { "ConfirmPassword", "Passw0rd!" }, + }); - public void Dispose() => _client.Dispose(); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } -} + + public void Dispose() => _client.Dispose(); +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/HttpSourceResourceProviderTestHost.cs b/tests/BaGet.Tests/Support/HttpSourceResourceProviderTestHost.cs index 2420112a1..71081e6a1 100644 --- a/tests/BaGet.Tests/Support/HttpSourceResourceProviderTestHost.cs +++ b/tests/BaGet.Tests/Support/HttpSourceResourceProviderTestHost.cs @@ -8,40 +8,39 @@ using NuGet.Protocol; using NuGet.Protocol.Core.Types; -namespace BaGet.Tests -{ - /// - /// Similar to official HttpSourceResourceProvider, but uses test host. - /// - public class HttpSourceResourceProviderTestHost : ResourceProvider - { - // Only one HttpSource per source should exist. This is to reduce the number of TCP connections. - private readonly ConcurrentDictionary _cache - = new ConcurrentDictionary(); - private readonly HttpClient _httpClient; +namespace BaGet.Tests; - public HttpSourceResourceProviderTestHost(HttpClient httpClient) - : base(typeof(HttpSourceResource), - nameof(HttpSourceResource), - NuGetResourceProviderPositions.Last) - { - _httpClient = httpClient; - } +/// +/// Similar to official HttpSourceResourceProvider, but uses test host. +/// +public class HttpSourceResourceProviderTestHost : ResourceProvider +{ + // Only one HttpSource per source should exist. This is to reduce the number of TCP connections. + private readonly ConcurrentDictionary _cache + = new ConcurrentDictionary(); + private readonly HttpClient _httpClient; - public override Task> TryCreate(SourceRepository source, CancellationToken token) - { - Debug.Assert(source.PackageSource.IsHttp, "HTTP source requested for a non-http source."); + public HttpSourceResourceProviderTestHost(HttpClient httpClient) + : base(typeof(HttpSourceResource), + nameof(HttpSourceResource), + NuGetResourceProviderPositions.Last) + { + _httpClient = httpClient; + } - HttpSourceResource curResource = null; + public override Task> TryCreate(SourceRepository source, CancellationToken token) + { + Debug.Assert(source.PackageSource.IsHttp, "HTTP source requested for a non-http source."); - if (source.PackageSource.IsHttp) - { - curResource = _cache.GetOrAdd( - source.PackageSource, - packageSource => new HttpSourceResource(TestableHttpSource.Create(source, _httpClient))); - } + HttpSourceResource curResource = null; - return Task.FromResult(new Tuple(curResource != null, curResource)); + if (source.PackageSource.IsHttp) + { + curResource = _cache.GetOrAdd( + source.PackageSource, + packageSource => new HttpSourceResource(TestableHttpSource.Create(source, _httpClient))); } + + return Task.FromResult(new Tuple(curResource != null, curResource)); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/StreamExtensions.cs b/tests/BaGet.Tests/Support/StreamExtensions.cs index 1ad591893..1605e5f5e 100644 --- a/tests/BaGet.Tests/Support/StreamExtensions.cs +++ b/tests/BaGet.Tests/Support/StreamExtensions.cs @@ -1,24 +1,23 @@ using System.IO; using Newtonsoft.Json; -namespace BaGet.Tests +namespace BaGet.Tests; + +public static class StreamExtensions { - public static class StreamExtensions + public static string ToPrettifiedJson(this Stream jsonStream) { - public static string ToPrettifiedJson(this Stream jsonStream) + using var writer = new StringWriter(); + using var jsonWriter = new JsonTextWriter(writer) { - using var writer = new StringWriter(); - using var jsonWriter = new JsonTextWriter(writer) - { - Formatting = Formatting.Indented, - DateTimeZoneHandling = DateTimeZoneHandling.Utc - }; + Formatting = Formatting.Indented, + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }; - using var reader = new StreamReader(jsonStream); - using var jsonReader = new JsonTextReader(reader); + using var reader = new StreamReader(jsonStream); + using var jsonReader = new JsonTextReader(reader); - jsonWriter.WriteToken(jsonReader); - return writer.ToString(); - } + jsonWriter.WriteToken(jsonReader); + return writer.ToString(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/TestPackages.cs b/tests/BaGet.Tests/Support/TestPackages.cs index 668567698..cc74fcb24 100644 --- a/tests/BaGet.Tests/Support/TestPackages.cs +++ b/tests/BaGet.Tests/Support/TestPackages.cs @@ -5,67 +5,66 @@ using NuGet.Packaging; using NuGet.Versioning; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Builds minimal packages in memory, for tests that need more than the one checked in. +/// +internal static class TestPackages { - /// - /// Builds minimal packages in memory, for tests that need more than the one checked in. - /// - internal static class TestPackages + public static MemoryStream Build(string id, string version) { - public static MemoryStream Build(string id, string version) + var builder = new PackageBuilder { - var builder = new PackageBuilder - { - Id = id, - Version = NuGetVersion.Parse(version), - Description = "Test package", - }; - builder.Authors.Add("Test author"); - builder.Files.Add(new InMemoryFile("content/readme.txt", "test")); + Id = id, + Version = NuGetVersion.Parse(version), + Description = "Test package", + }; + builder.Authors.Add("Test author"); + builder.Files.Add(new InMemoryFile("content/readme.txt", "test")); - var stream = new MemoryStream(); - builder.Save(stream); - stream.Position = 0; + var stream = new MemoryStream(); + builder.Save(stream); + stream.Position = 0; - return stream; - } + return stream; + } + + /// + /// A push request as "dotnet nuget push" sends it. + /// + public static HttpRequestMessage PushRequest(Stream package, string apiKey) + { + var content = new MultipartFormDataContent(); + var file = new StreamContent(package); + file.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + content.Add(file, "package", "package.nupkg"); - /// - /// A push request as "dotnet nuget push" sends it. - /// - public static HttpRequestMessage PushRequest(Stream package, string apiKey) + var request = new HttpRequestMessage(HttpMethod.Put, "api/v2/package") { Content = content }; + if (apiKey != null) { - var content = new MultipartFormDataContent(); - var file = new StreamContent(package); - file.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); - content.Add(file, "package", "package.nupkg"); + request.Headers.Add("X-NuGet-ApiKey", apiKey); + } - var request = new HttpRequestMessage(HttpMethod.Put, "api/v2/package") { Content = content }; - if (apiKey != null) - { - request.Headers.Add("X-NuGet-ApiKey", apiKey); - } + return request; + } - return request; - } + private class InMemoryFile : IPackageFile + { + private readonly byte[] _content; - private class InMemoryFile : IPackageFile + public InMemoryFile(string path, string content) { - private readonly byte[] _content; - - public InMemoryFile(string path, string content) - { - Path = path; - _content = Encoding.UTF8.GetBytes(content); - } + Path = path; + _content = Encoding.UTF8.GetBytes(content); + } - public string Path { get; } - public string EffectivePath => Path; - public NuGet.Frameworks.NuGetFramework NuGetFramework => null; - public System.Runtime.Versioning.FrameworkName TargetFramework => null; - public System.DateTimeOffset LastWriteTime => System.DateTimeOffset.UnixEpoch; + public string Path { get; } + public string EffectivePath => Path; + public NuGet.Frameworks.NuGetFramework NuGetFramework => null; + public System.Runtime.Versioning.FrameworkName TargetFramework => null; + public System.DateTimeOffset LastWriteTime => System.DateTimeOffset.UnixEpoch; - public Stream GetStream() => new MemoryStream(_content); - } + public Stream GetStream() => new MemoryStream(_content); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/TestResources.cs b/tests/BaGet.Tests/Support/TestResources.cs index dc80c3f39..ba6e40da6 100644 --- a/tests/BaGet.Tests/Support/TestResources.cs +++ b/tests/BaGet.Tests/Support/TestResources.cs @@ -1,45 +1,44 @@ using System.IO; -namespace BaGet.Tests +namespace BaGet.Tests; + +public static class TestResources { - public static class TestResources - { - private const string ResourcePrefix = "BaGet.Tests.TestData."; + private const string ResourcePrefix = "BaGet.Tests.TestData."; - /// - /// Test package created with the following properties: - /// - /// Test author - /// Test description - /// 1.2.3 - /// true - /// snupkg - /// - public const string Package = "TestData.1.2.3.nupkg"; - public const string SymbolPackage = "TestData.1.2.3.snupkg"; + /// + /// Test package created with the following properties: + /// + /// Test author + /// Test description + /// 1.2.3 + /// true + /// snupkg + /// + public const string Package = "TestData.1.2.3.nupkg"; + public const string SymbolPackage = "TestData.1.2.3.snupkg"; - /// - /// Buffer the resource stream into memory so the caller doesn't have to dispose. - /// - public static MemoryStream GetResourceStream(string resourceName) - { - using var resourceStream = typeof(TestResources) - .Assembly - .GetManifestResourceStream(ResourcePrefix + resourceName); - - if (resourceStream == null) - { - return null; - } + /// + /// Buffer the resource stream into memory so the caller doesn't have to dispose. + /// + public static MemoryStream GetResourceStream(string resourceName) + { + using var resourceStream = typeof(TestResources) + .Assembly + .GetManifestResourceStream(ResourcePrefix + resourceName); - var bufferedStream = new MemoryStream(); - using (resourceStream) - { - resourceStream.CopyTo(bufferedStream); - } + if (resourceStream == null) + { + return null; + } - bufferedStream.Position = 0; - return bufferedStream; + var bufferedStream = new MemoryStream(); + using (resourceStream) + { + resourceStream.CopyTo(bufferedStream); } + + bufferedStream.Position = 0; + return bufferedStream; } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/TestableHttpSource.cs b/tests/BaGet.Tests/Support/TestableHttpSource.cs index a7e022cbc..b3e8844c8 100644 --- a/tests/BaGet.Tests/Support/TestableHttpSource.cs +++ b/tests/BaGet.Tests/Support/TestableHttpSource.cs @@ -7,49 +7,48 @@ using NuGet.Protocol; using NuGet.Protocol.Core.Types; -namespace BaGet.Tests +namespace BaGet.Tests; + +public class TestableHttpSource : HttpSource { - public class TestableHttpSource : HttpSource + public static TestableHttpSource Create(SourceRepository source, HttpClient client) { - public static TestableHttpSource Create(SourceRepository source, HttpClient client) - { - Func> factory = () => source.GetResourceAsync(); - - var httpCacheDirectory = Path.Combine( - Path.GetTempPath(), - "BaGetTests", - Guid.NewGuid().ToString("N")); - - return new TestableHttpSource( - source.PackageSource, - factory, - NullThrottle.Instance, - client, - httpCacheDirectory); - } + Func> factory = () => source.GetResourceAsync(); - private TestableHttpSource( - PackageSource packageSource, - Func> messageHandlerFactory, - IThrottle throttle, - HttpClient httpClient, - string httpCacheDirectory) - : base(packageSource, messageHandlerFactory, throttle) - { - // Set the HTTP client on the parent's private field. - var flags = BindingFlags.NonPublic | BindingFlags.Instance; - var field = typeof(HttpSource).GetField("_httpClient", flags); + var httpCacheDirectory = Path.Combine( + Path.GetTempPath(), + "BaGetTests", + Guid.NewGuid().ToString("N")); - if (field == null) - { - throw new InvalidOperationException( - $"Could not find field '_httpClient' with flags '{flags}' " + - $"on {nameof(HttpSource)}"); - } + return new TestableHttpSource( + source.PackageSource, + factory, + NullThrottle.Instance, + client, + httpCacheDirectory); + } - field.SetValue(this, httpClient); + private TestableHttpSource( + PackageSource packageSource, + Func> messageHandlerFactory, + IThrottle throttle, + HttpClient httpClient, + string httpCacheDirectory) + : base(packageSource, messageHandlerFactory, throttle) + { + // Set the HTTP client on the parent's private field. + var flags = BindingFlags.NonPublic | BindingFlags.Instance; + var field = typeof(HttpSource).GetField("_httpClient", flags); - HttpCacheDirectory = httpCacheDirectory; + if (field == null) + { + throw new InvalidOperationException( + $"Could not find field '_httpClient' with flags '{flags}' " + + $"on {nameof(HttpSource)}"); } + + field.SetValue(this, httpClient); + + HttpCacheDirectory = httpCacheDirectory; } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/XunitLogger.cs b/tests/BaGet.Tests/Support/XunitLogger.cs index 1c3d19647..7c0c05999 100644 --- a/tests/BaGet.Tests/Support/XunitLogger.cs +++ b/tests/BaGet.Tests/Support/XunitLogger.cs @@ -2,39 +2,38 @@ using Microsoft.Extensions.Logging; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +// Based off: +// https://stackoverflow.com/questions/46169169/net-core-2-0-configurelogging-xunit-test +public class XunitLogger : ILogger { - // Based off: - // https://stackoverflow.com/questions/46169169/net-core-2-0-configurelogging-xunit-test - public class XunitLogger : ILogger + private readonly ITestOutputHelper _output; + private readonly string _category; + + public XunitLogger(ITestOutputHelper output, string category) { - private readonly ITestOutputHelper _output; - private readonly string _category; + _output = output ?? throw new ArgumentNullException(nameof(output)); + _category = category ?? throw new ArgumentNullException(nameof(category)); + } - public XunitLogger(ITestOutputHelper output, string category) - { - _output = output ?? throw new ArgumentNullException(nameof(output)); - _category = category ?? throw new ArgumentNullException(nameof(category)); - } + public IDisposable BeginScope(TState state) => NullScope.Instance; + public bool IsEnabled(LogLevel logLevel) => true; - public IDisposable BeginScope(TState state) => NullScope.Instance; - public bool IsEnabled(LogLevel logLevel) => true; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + { + _output.WriteLine($"{_category} [{eventId}] {formatter(state, exception)}"); - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + if (exception != null) { - _output.WriteLine($"{_category} [{eventId}] {formatter(state, exception)}"); - - if (exception != null) - { - _output.WriteLine(exception.ToString()); - } + _output.WriteLine(exception.ToString()); } + } - private class NullScope : IDisposable - { - public static readonly NullScope Instance = new NullScope(); + private class NullScope : IDisposable + { + public static readonly NullScope Instance = new NullScope(); - public void Dispose() { } - } + public void Dispose() { } } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/Support/XunitLoggerProvider.cs b/tests/BaGet.Tests/Support/XunitLoggerProvider.cs index efc71d7e4..9315e2094 100644 --- a/tests/BaGet.Tests/Support/XunitLoggerProvider.cs +++ b/tests/BaGet.Tests/Support/XunitLoggerProvider.cs @@ -2,21 +2,20 @@ using Microsoft.Extensions.Logging; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +// Based off: +// https://stackoverflow.com/questions/46169169/net-core-2-0-configurelogging-xunit-test +public class XunitLoggerProvider : ILoggerProvider { - // Based off: - // https://stackoverflow.com/questions/46169169/net-core-2-0-configurelogging-xunit-test - public class XunitLoggerProvider : ILoggerProvider - { - private readonly ITestOutputHelper _output; + private readonly ITestOutputHelper _output; - public XunitLoggerProvider(ITestOutputHelper output) - { - _output = output ?? throw new ArgumentNullException(nameof(output)); - } + public XunitLoggerProvider(ITestOutputHelper output) + { + _output = output ?? throw new ArgumentNullException(nameof(output)); + } - public ILogger CreateLogger(string category) => new XunitLogger(_output, category); + public ILogger CreateLogger(string category) => new XunitLogger(_output, category); - public void Dispose() { } - } -} + public void Dispose() { } +} \ No newline at end of file diff --git a/tests/BaGet.Tests/UploadPageTests.cs b/tests/BaGet.Tests/UploadPageTests.cs index ac698b09a..9e68e272a 100644 --- a/tests/BaGet.Tests/UploadPageTests.cs +++ b/tests/BaGet.Tests/UploadPageTests.cs @@ -6,152 +6,151 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// The upload page hands the reader a command to copy, so what it renders has to be a +/// command that works against this server. +/// +public class UploadPageTests : IDisposable { - /// - /// The upload page hands the reader a command to copy, so what it renders has to be a - /// command that works against this server. - /// - public class UploadPageTests : IDisposable + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public UploadPageTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output); + _client = _app.CreateDefaultClient(); + } + + private async Task GetPageAsync() + { + using var response = await _client.GetAsync("upload"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + return await response.Content.ReadAsStringAsync(); + } + + [Fact] + public async Task OffersTheDotnetAndNuGetAndPaketCommands() + { + var content = await GetPageAsync(); + + Assert.Contains("dotnet nuget push", content); + Assert.Contains("nuget push -Source", content); + Assert.Contains("paket push", content); + } + + [Fact] + public async Task TheDotnetCommandUsesTheServiceIndex() { - private readonly BaGetApplication _app; - private readonly HttpClient _client; - - public UploadPageTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); - _client = _app.CreateDefaultClient(); - } - - private async Task GetPageAsync() - { - using var response = await _client.GetAsync("upload"); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - return await response.Content.ReadAsStringAsync(); - } - - [Fact] - public async Task OffersTheDotnetAndNuGetAndPaketCommands() - { - var content = await GetPageAsync(); - - Assert.Contains("dotnet nuget push", content); - Assert.Contains("nuget push -Source", content); - Assert.Contains("paket push", content); - } - - [Fact] - public async Task TheDotnetCommandUsesTheServiceIndex() - { - var content = await GetPageAsync(); - - Assert.Contains("dotnet nuget push -s http://localhost/v3/index.json", content); - } - - [Fact] - public async Task PowerShellGetRegistersTheV2Feed() - { - // PowerShellGet reads the V2 protocol. Registering the V3 service index with it - // fails. - var content = await GetPageAsync(); - - Assert.Contains("Register-PSRepository", content); - Assert.Contains(@"-SourceLocation \""http://localhost/api/v2\""", content); - } - - [Fact] - public async Task PowerShellGetDoesNotRegisterTheServiceIndex() - { - var content = await GetPageAsync(); - - Assert.DoesNotContain(@"-SourceLocation \""http://localhost/v3/index.json\""", content); - } - - [Fact] - public async Task PowerShellGetPublishesToThePublishEndpoint() - { - var content = await GetPageAsync(); - - Assert.Contains(@"-PublishLocation \""http://localhost/api/v2/package\""", content); - } - - [Fact] - public async Task TheAddressPowerShellGetIsToldToRegisterIsServed() - { - // Whatever the page tells the reader to register has to answer, or the - // instructions are broken in a different way. - await GetPageAsync(); - - using var response = await _client.GetAsync("api/v2"); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } - - [Fact] - public async Task ThePopoverAttributeIsSpelledCorrectly() - { - var content = await GetPageAsync(); - - Assert.Contains(@"data-toggle=""popover""", content); - Assert.DoesNotContain("data-tottle", content); - } - - public void Dispose() - { - _client?.Dispose(); - _app?.Dispose(); - } + var content = await GetPageAsync(); + + Assert.Contains("dotnet nuget push -s http://localhost/v3/index.json", content); } - /// - /// The upload page with the V2 feed switched off. - /// - public class UploadPageWithoutV2Tests : IDisposable + [Fact] + public async Task PowerShellGetRegistersTheV2Feed() { - private readonly BaGetApplication _app; - private readonly HttpClient _client; - - public UploadPageWithoutV2Tests(ITestOutputHelper output) - { - _app = new BaGetApplication( - output, - configOverrides: new Dictionary - { - { "Feeds:EnableV2", "false" }, - }); - - _client = _app.CreateDefaultClient(); - } - - [Fact] - public async Task PowerShellGetIsNotOffered() - { - // Its only supported protocol is not being served, so advertising it would send - // the reader to an address that answers 404. - using var response = await _client.GetAsync("upload"); - var content = await response.Content.ReadAsStringAsync(); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.DoesNotContain("Register-PSRepository", content); - Assert.DoesNotContain("PowerShellGet", content); - } - - [Fact] - public async Task TheOtherClientsAreStillOffered() - { - using var response = await _client.GetAsync("upload"); - var content = await response.Content.ReadAsStringAsync(); - - Assert.Contains("dotnet nuget push", content); - Assert.Contains("paket push", content); - } - - public void Dispose() - { - _client?.Dispose(); - _app?.Dispose(); - } + // PowerShellGet reads the V2 protocol. Registering the V3 service index with it + // fails. + var content = await GetPageAsync(); + + Assert.Contains("Register-PSRepository", content); + Assert.Contains(@"-SourceLocation \""http://localhost/api/v2\""", content); + } + + [Fact] + public async Task PowerShellGetDoesNotRegisterTheServiceIndex() + { + var content = await GetPageAsync(); + + Assert.DoesNotContain(@"-SourceLocation \""http://localhost/v3/index.json\""", content); + } + + [Fact] + public async Task PowerShellGetPublishesToThePublishEndpoint() + { + var content = await GetPageAsync(); + + Assert.Contains(@"-PublishLocation \""http://localhost/api/v2/package\""", content); + } + + [Fact] + public async Task TheAddressPowerShellGetIsToldToRegisterIsServed() + { + // Whatever the page tells the reader to register has to answer, or the + // instructions are broken in a different way. + await GetPageAsync(); + + using var response = await _client.GetAsync("api/v2"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task ThePopoverAttributeIsSpelledCorrectly() + { + var content = await GetPageAsync(); + + Assert.Contains(@"data-toggle=""popover""", content); + Assert.DoesNotContain("data-tottle", content); + } + + public void Dispose() + { + _client?.Dispose(); + _app?.Dispose(); } } + +/// +/// The upload page with the V2 feed switched off. +/// +public class UploadPageWithoutV2Tests : IDisposable +{ + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public UploadPageWithoutV2Tests(ITestOutputHelper output) + { + _app = new BaGetApplication( + output, + configOverrides: new Dictionary + { + { "Feeds:EnableV2", "false" }, + }); + + _client = _app.CreateDefaultClient(); + } + + [Fact] + public async Task PowerShellGetIsNotOffered() + { + // Its only supported protocol is not being served, so advertising it would send + // the reader to an address that answers 404. + using var response = await _client.GetAsync("upload"); + var content = await response.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Register-PSRepository", content); + Assert.DoesNotContain("PowerShellGet", content); + } + + [Fact] + public async Task TheOtherClientsAreStillOffered() + { + using var response = await _client.GetAsync("upload"); + var content = await response.Content.ReadAsStringAsync(); + + Assert.Contains("dotnet nuget push", content); + Assert.Contains("paket push", content); + } + + public void Dispose() + { + _client?.Dispose(); + _app?.Dispose(); + } +} \ No newline at end of file diff --git a/tests/BaGet.Tests/V2FeedIntegrationTests.cs b/tests/BaGet.Tests/V2FeedIntegrationTests.cs index 9163efb39..dd3007352 100644 --- a/tests/BaGet.Tests/V2FeedIntegrationTests.cs +++ b/tests/BaGet.Tests/V2FeedIntegrationTests.cs @@ -10,249 +10,248 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// The V2 (OData) feed. These drive the HTTP surface a V2 client actually calls - +/// see also , which drives NuGet's own +/// V2 client against it. +/// +public class V2FeedIntegrationTests : IDisposable { - /// - /// The V2 (OData) feed. These drive the HTTP surface a V2 client actually calls - - /// see also , which drives NuGet's own - /// V2 client against it. - /// - public class V2FeedIntegrationTests : IDisposable + private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom"; + private static readonly XNamespace DataServices = "http://schemas.microsoft.com/ado/2007/08/dataservices"; + + private readonly BaGetApplication _app; + private readonly HttpClient _client; + private readonly Stream _packageStream; + + public V2FeedIntegrationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output); + _client = _app.CreateDefaultClient(); + _packageStream = TestResources.GetResourceStream(TestResources.Package); + } + + private static IEnumerable Entries(string document) + => XDocument.Parse(document).Root.Elements(Atom + "entry"); + + private static string PropertyOf(XElement entry, string name) + => entry.Descendants(DataServices + name).FirstOrDefault()?.Value; + + [Fact] + public async Task TheServiceDocumentAdvertisesThePackagesCollection() + { + using var response = await _client.GetAsync("api/v2"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var document = XDocument.Parse(await response.Content.ReadAsStringAsync()); + Assert.Contains( + "Packages", + document.Descendants() + .Where(e => e.Name.LocalName == "collection") + .Select(e => e.Attribute("href")?.Value)); + } + + [Fact] + public async Task TheMetadataDocumentParsesAndDescribesTheEntity() { - private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom"; - private static readonly XNamespace DataServices = "http://schemas.microsoft.com/ado/2007/08/dataservices"; + using var response = await _client.GetAsync("api/v2/$metadata"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + // Parsing is the assertion: a malformed EDM breaks every V2 client. + var document = XDocument.Parse(await response.Content.ReadAsStringAsync()); - private readonly BaGetApplication _app; - private readonly HttpClient _client; - private readonly Stream _packageStream; - - public V2FeedIntegrationTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output); - _client = _app.CreateDefaultClient(); - _packageStream = TestResources.GetResourceStream(TestResources.Package); - } - - private static IEnumerable Entries(string document) - => XDocument.Parse(document).Root.Elements(Atom + "entry"); - - private static string PropertyOf(XElement entry, string name) - => entry.Descendants(DataServices + name).FirstOrDefault()?.Value; - - [Fact] - public async Task TheServiceDocumentAdvertisesThePackagesCollection() - { - using var response = await _client.GetAsync("api/v2"); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var document = XDocument.Parse(await response.Content.ReadAsStringAsync()); - Assert.Contains( - "Packages", - document.Descendants() - .Where(e => e.Name.LocalName == "collection") - .Select(e => e.Attribute("href")?.Value)); - } - - [Fact] - public async Task TheMetadataDocumentParsesAndDescribesTheEntity() - { - using var response = await _client.GetAsync("api/v2/$metadata"); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - - // Parsing is the assertion: a malformed EDM breaks every V2 client. - var document = XDocument.Parse(await response.Content.ReadAsStringAsync()); - - var entityType = document.Descendants() - .Single(e => e.Name.LocalName == "EntityType"); - Assert.Equal("V2FeedPackage", entityType.Attribute("Name").Value); - - var properties = entityType.Elements() - .Where(e => e.Name.LocalName == "Property") - .Select(e => e.Attribute("Name").Value) - .ToList(); - - Assert.Contains("Id", properties); - Assert.Contains("Version", properties); - Assert.Contains("IsLatestVersion", properties); - Assert.Contains("Dependencies", properties); - } + var entityType = document.Descendants() + .Single(e => e.Name.LocalName == "EntityType"); + Assert.Equal("V2FeedPackage", entityType.Attribute("Name").Value); - [Fact] - public async Task FindPackagesByIdReturnsEveryVersion() - { - await _app.AddPackageAsync(_packageStream); - - using var response = await _client.GetAsync("api/v2/FindPackagesById()?id='TestData'"); + var properties = entityType.Elements() + .Where(e => e.Name.LocalName == "Property") + .Select(e => e.Attribute("Name").Value) + .ToList(); + + Assert.Contains("Id", properties); + Assert.Contains("Version", properties); + Assert.Contains("IsLatestVersion", properties); + Assert.Contains("Dependencies", properties); + } + + [Fact] + public async Task FindPackagesByIdReturnsEveryVersion() + { + await _app.AddPackageAsync(_packageStream); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var entries = Entries(await response.Content.ReadAsStringAsync()).ToList(); + using var response = await _client.GetAsync("api/v2/FindPackagesById()?id='TestData'"); - Assert.Single(entries); - Assert.Equal("1.2.3", PropertyOf(entries[0], "NormalizedVersion")); - } - - [Fact] - public async Task FindPackagesByIdAcceptsAnUnquotedId() - { - await _app.AddPackageAsync(_packageStream); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var entries = Entries(await response.Content.ReadAsStringAsync()).ToList(); - using var response = await _client.GetAsync("api/v2/FindPackagesById()?id=TestData"); - - Assert.Single(Entries(await response.Content.ReadAsStringAsync())); - } - - [Fact] - public async Task FindPackagesByIdIsEmptyForAnUnknownId() - { - using var response = await _client.GetAsync("api/v2/FindPackagesById()?id='No.Such.Package'"); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Empty(Entries(await response.Content.ReadAsStringAsync())); - } - - [Fact] - public async Task AnEntryPointsAtADownloadablePackage() - { - await _app.AddPackageAsync(_packageStream); - - using var feed = await _client.GetAsync("api/v2/FindPackagesById()?id='TestData'"); - var entry = Entries(await feed.Content.ReadAsStringAsync()).Single(); - - var source = entry.Element(Atom + "content").Attribute("src").Value; - - // The advertised content URL has to actually serve the nupkg. - using var download = await _client.GetAsync(source); - Assert.Equal(HttpStatusCode.OK, download.StatusCode); - Assert.NotEqual(0, (await download.Content.ReadAsByteArrayAsync()).Length); - } - - [Fact] - public async Task TheLatestVersionFlagsAreSet() - { - await _app.AddPackageAsync(_packageStream); + Assert.Single(entries); + Assert.Equal("1.2.3", PropertyOf(entries[0], "NormalizedVersion")); + } - using var response = await _client.GetAsync("api/v2/FindPackagesById()?id='TestData'"); - var entry = Entries(await response.Content.ReadAsStringAsync()).Single(); - - // A single stable version is both the latest and the absolute latest. - Assert.Equal("true", PropertyOf(entry, "IsLatestVersion")); - Assert.Equal("true", PropertyOf(entry, "IsAbsoluteLatestVersion")); - Assert.Equal("false", PropertyOf(entry, "IsPrerelease")); - } - - [Fact] - public async Task PackagesByKeyReturnsOneEntry() - { - await _app.AddPackageAsync(_packageStream); - - using var response = await _client.GetAsync("api/v2/Packages(Id='TestData',Version='1.2.3')"); + [Fact] + public async Task FindPackagesByIdAcceptsAnUnquotedId() + { + await _app.AddPackageAsync(_packageStream); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var document = XDocument.Parse(await response.Content.ReadAsStringAsync()); - Assert.Equal("entry", document.Root.Name.LocalName); - Assert.Equal("1.2.3", PropertyOf(document.Root, "NormalizedVersion")); - } + using var response = await _client.GetAsync("api/v2/FindPackagesById()?id=TestData"); - [Fact] - public async Task PackagesByKeyIsNotFoundForAnUnknownVersion() - { - await _app.AddPackageAsync(_packageStream); + Assert.Single(Entries(await response.Content.ReadAsStringAsync())); + } - using var response = await _client.GetAsync("api/v2/Packages(Id='TestData',Version='9.9.9')"); + [Fact] + public async Task FindPackagesByIdIsEmptyForAnUnknownId() + { + using var response = await _client.GetAsync("api/v2/FindPackagesById()?id='No.Such.Package'"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Empty(Entries(await response.Content.ReadAsStringAsync())); + } - [Fact] - public async Task SearchFindsAPushedPackage() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task AnEntryPointsAtADownloadablePackage() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync("api/v2/Search()?searchTerm=''&includePrerelease=false"); + using var feed = await _client.GetAsync("api/v2/FindPackagesById()?id='TestData'"); + var entry = Entries(await feed.Content.ReadAsStringAsync()).Single(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - var entries = Entries(await response.Content.ReadAsStringAsync()).ToList(); + var source = entry.Element(Atom + "content").Attribute("src").Value; - Assert.Contains("TestData", entries.Select(e => e.Element(Atom + "title").Value)); - } + // The advertised content URL has to actually serve the nupkg. + using var download = await _client.GetAsync(source); + Assert.Equal(HttpStatusCode.OK, download.StatusCode); + Assert.NotEqual(0, (await download.Content.ReadAsByteArrayAsync()).Length); + } - [Fact] - public async Task PackagesListsWhatTheFeedHolds() - { - await _app.AddPackageAsync(_packageStream); + [Fact] + public async Task TheLatestVersionFlagsAreSet() + { + await _app.AddPackageAsync(_packageStream); - using var response = await _client.GetAsync("api/v2/Packages()"); + using var response = await _client.GetAsync("api/v2/FindPackagesById()?id='TestData'"); + var entry = Entries(await response.Content.ReadAsStringAsync()).Single(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.NotEmpty(Entries(await response.Content.ReadAsStringAsync())); - } + // A single stable version is both the latest and the absolute latest. + Assert.Equal("true", PropertyOf(entry, "IsLatestVersion")); + Assert.Equal("true", PropertyOf(entry, "IsAbsoluteLatestVersion")); + Assert.Equal("false", PropertyOf(entry, "IsPrerelease")); + } - [Fact] - public async Task TheFeedIsAtomEncoded() - { - using var response = await _client.GetAsync("api/v2/Packages()"); + [Fact] + public async Task PackagesByKeyReturnsOneEntry() + { + await _app.AddPackageAsync(_packageStream); - Assert.Equal("application/atom+xml", response.Content.Headers.ContentType.MediaType); - } + using var response = await _client.GetAsync("api/v2/Packages(Id='TestData',Version='1.2.3')"); - public void Dispose() - { - _packageStream?.Dispose(); - _client?.Dispose(); - _app?.Dispose(); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var document = XDocument.Parse(await response.Content.ReadAsStringAsync()); + Assert.Equal("entry", document.Root.Name.LocalName); + Assert.Equal("1.2.3", PropertyOf(document.Root, "NormalizedVersion")); } - /// - /// The V2 feed with "Feeds:EnableV2" switched off. - /// - public class V2FeedDisabledTests : IDisposable + [Fact] + public async Task PackagesByKeyIsNotFoundForAnUnknownVersion() { - private readonly BaGetApplication _app; - private readonly HttpClient _client; - - public V2FeedDisabledTests(ITestOutputHelper output) - { - _app = new BaGetApplication( - output, - configOverrides: new Dictionary - { - { "Feeds:EnableV2", "false" }, - }); - - _client = _app.CreateDefaultClient(); - } - - [Theory] - [InlineData("api/v2")] - [InlineData("api/v2/$metadata")] - [InlineData("api/v2/Packages()")] - [InlineData("api/v2/FindPackagesById()?id='TestData'")] - public async Task TheFeedIsNotFound(string path) - { - using var response = await _client.GetAsync(path); - - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } - - [Fact] - public async Task PushingStillWorks() - { - // Turning off the read feed must not turn off the publish endpoint, which - // shares the "api/v2" prefix. - using var stream = TestResources.GetResourceStream(TestResources.Package); - - await _app.AddPackageAsync(stream); - - using var response = await _client.GetAsync("v3/registration/testdata/index.json"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } - - public void Dispose() - { - _client?.Dispose(); - _app?.Dispose(); - } + await _app.AddPackageAsync(_packageStream); + + using var response = await _client.GetAsync("api/v2/Packages(Id='TestData',Version='9.9.9')"); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task SearchFindsAPushedPackage() + { + await _app.AddPackageAsync(_packageStream); + + using var response = await _client.GetAsync("api/v2/Search()?searchTerm=''&includePrerelease=false"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var entries = Entries(await response.Content.ReadAsStringAsync()).ToList(); + + Assert.Contains("TestData", entries.Select(e => e.Element(Atom + "title").Value)); + } + + [Fact] + public async Task PackagesListsWhatTheFeedHolds() + { + await _app.AddPackageAsync(_packageStream); + + using var response = await _client.GetAsync("api/v2/Packages()"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.NotEmpty(Entries(await response.Content.ReadAsStringAsync())); + } + + [Fact] + public async Task TheFeedIsAtomEncoded() + { + using var response = await _client.GetAsync("api/v2/Packages()"); + + Assert.Equal("application/atom+xml", response.Content.Headers.ContentType.MediaType); + } + + public void Dispose() + { + _packageStream?.Dispose(); + _client?.Dispose(); + _app?.Dispose(); } } + +/// +/// The V2 feed with "Feeds:EnableV2" switched off. +/// +public class V2FeedDisabledTests : IDisposable +{ + private readonly BaGetApplication _app; + private readonly HttpClient _client; + + public V2FeedDisabledTests(ITestOutputHelper output) + { + _app = new BaGetApplication( + output, + configOverrides: new Dictionary + { + { "Feeds:EnableV2", "false" }, + }); + + _client = _app.CreateDefaultClient(); + } + + [Theory] + [InlineData("api/v2")] + [InlineData("api/v2/$metadata")] + [InlineData("api/v2/Packages()")] + [InlineData("api/v2/FindPackagesById()?id='TestData'")] + public async Task TheFeedIsNotFound(string path) + { + using var response = await _client.GetAsync(path); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task PushingStillWorks() + { + // Turning off the read feed must not turn off the publish endpoint, which + // shares the "api/v2" prefix. + using var stream = TestResources.GetResourceStream(TestResources.Package); + + await _app.AddPackageAsync(stream); + + using var response = await _client.GetAsync("v3/registration/testdata/index.json"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + public void Dispose() + { + _client?.Dispose(); + _app?.Dispose(); + } +} \ No newline at end of file diff --git a/tests/BaGet.Tests/ValidationIntegrationTests.cs b/tests/BaGet.Tests/ValidationIntegrationTests.cs index ff1ddbd49..0ec5ef3c1 100644 --- a/tests/BaGet.Tests/ValidationIntegrationTests.cs +++ b/tests/BaGet.Tests/ValidationIntegrationTests.cs @@ -16,281 +16,280 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// With validation on, a push is accepted, staged and validated, and the package only +/// appears once every validator passes. +/// +public class ValidationIntegrationTests : IDisposable { - /// - /// With validation on, a push is accepted, staged and validated, and the package only - /// appears once every validator passes. - /// - public class ValidationIntegrationTests : IDisposable + private readonly ITestOutputHelper _output; + private readonly List _disposables = new List(); + + public ValidationIntegrationTests(ITestOutputHelper output) { - private readonly ITestOutputHelper _output; - private readonly List _disposables = new List(); + _output = output; + } - public ValidationIntegrationTests(ITestOutputHelper output) - { - _output = output; - } + [Fact] + public async Task APackageBeingValidatedIsNotServed() + { + var gate = new GateValidator(); + var client = CreateClient(configureServices: s => s.AddSingleton(gate)); - [Fact] - public async Task APackageBeingValidatedIsNotServed() - { - var gate = new GateValidator(); - var client = CreateClient(configureServices: s => s.AddSingleton(gate)); + Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Gated.Package", "1.0.0")); + await gate.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); - Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Gated.Package", "1.0.0")); - await gate.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + Assert.Equal("Validating", await StatusAsync(client, "Gated.Package", "1.0.0")); + await AssertNotServedAsync(client, "Gated.Package", "1.0.0"); - Assert.Equal("Validating", await StatusAsync(client, "Gated.Package", "1.0.0")); - await AssertNotServedAsync(client, "Gated.Package", "1.0.0"); + gate.Release.SetResult(true); - gate.Release.SetResult(true); + Assert.Equal("Available", await WaitForResultAsync(client, "Gated.Package", "1.0.0")); + using var download = await client.GetAsync("v3/package/gated.package/1.0.0/gated.package.1.0.0.nupkg"); + Assert.Equal(HttpStatusCode.OK, download.StatusCode); + } - Assert.Equal("Available", await WaitForResultAsync(client, "Gated.Package", "1.0.0")); - using var download = await client.GetAsync("v3/package/gated.package/1.0.0/gated.package.1.0.0.nupkg"); - Assert.Equal(HttpStatusCode.OK, download.StatusCode); - } + [Fact] + public async Task AFailedPackageIsQuarantinedAndNeverServed() + { + var client = CreateClient(configureServices: s => s.AddSingleton(new RejectingValidator())); - [Fact] - public async Task AFailedPackageIsQuarantinedAndNeverServed() - { - var client = CreateClient(configureServices: s => s.AddSingleton(new RejectingValidator())); + Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Rejected.Package", "1.0.0")); - Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Rejected.Package", "1.0.0")); + Assert.Equal("Quarantined", await WaitForResultAsync(client, "Rejected.Package", "1.0.0")); + await AssertNotServedAsync(client, "Rejected.Package", "1.0.0"); - Assert.Equal("Quarantined", await WaitForResultAsync(client, "Rejected.Package", "1.0.0")); - await AssertNotServedAsync(client, "Rejected.Package", "1.0.0"); + using var status = JsonDocument.Parse(await client.GetStringAsync("v3/package/Rejected.Package/1.0.0/validation")); + var rejection = status.RootElement.GetProperty("steps").EnumerateArray() + .Single(s => s.GetProperty("type").GetString() == "Rejecting"); + Assert.Equal("Failed", rejection.GetProperty("state").GetString()); + Assert.Equal("Rejected by the test.", rejection.GetProperty("message").GetString()); + } - using var status = JsonDocument.Parse(await client.GetStringAsync("v3/package/Rejected.Package/1.0.0/validation")); - var rejection = status.RootElement.GetProperty("steps").EnumerateArray() - .Single(s => s.GetProperty("type").GetString() == "Rejecting"); - Assert.Equal("Failed", rejection.GetProperty("state").GetString()); - Assert.Equal("Rejected by the test.", rejection.GetProperty("message").GetString()); - } + [Fact] + public async Task AnUnsignedPackageIsQuarantinedWhenSignaturesAreRequired() + { + var client = CreateClient(new Dictionary { { "Validation:RequireSignedPackages", "true" } }); - [Fact] - public async Task AnUnsignedPackageIsQuarantinedWhenSignaturesAreRequired() - { - var client = CreateClient(new Dictionary { { "Validation:RequireSignedPackages", "true" } }); + await PushAsync(client, "Unsigned.Package", "1.0.0"); - await PushAsync(client, "Unsigned.Package", "1.0.0"); + Assert.Equal("Quarantined", await WaitForResultAsync(client, "Unsigned.Package", "1.0.0")); + } - Assert.Equal("Quarantined", await WaitForResultAsync(client, "Unsigned.Package", "1.0.0")); - } + [Fact] + public async Task TheSameVersionCannotBeValidatedTwiceAtOnce() + { + var gate = new GateValidator(); + var client = CreateClient(configureServices: s => s.AddSingleton(gate)); - [Fact] - public async Task TheSameVersionCannotBeValidatedTwiceAtOnce() + Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Twice.Package", "1.0.0")); + Assert.Equal(HttpStatusCode.Conflict, await PushAsync(client, "Twice.Package", "1.0.0")); + + gate.Release.SetResult(true); + Assert.Equal("Available", await WaitForResultAsync(client, "Twice.Package", "1.0.0")); + } + + [Fact] + public async Task AValidatedPackageIsRepositorySigned() + { + var (path, fingerprint) = CreateSigningCertificate(); + var client = CreateClient(new Dictionary { - var gate = new GateValidator(); - var client = CreateClient(configureServices: s => s.AddSingleton(gate)); + { "Validation:RepositorySigningCertificatePath", path }, + { "Validation:RepositorySigningCertificatePassword", "test" }, + { "Validation:RepositorySigningServiceIndexUrl", "https://localhost/v3/index.json" }, + }); - Assert.Equal(HttpStatusCode.Accepted, await PushAsync(client, "Twice.Package", "1.0.0")); - Assert.Equal(HttpStatusCode.Conflict, await PushAsync(client, "Twice.Package", "1.0.0")); + await PushAsync(client, "Signed.Package", "1.0.0"); + Assert.Equal("Available", await WaitForResultAsync(client, "Signed.Package", "1.0.0")); - gate.Release.SetResult(true); - Assert.Equal("Available", await WaitForResultAsync(client, "Twice.Package", "1.0.0")); - } + using var download = await client.GetAsync("v3/package/signed.package/1.0.0/signed.package.1.0.0.nupkg"); + using var package = new MemoryStream(await download.Content.ReadAsByteArrayAsync()); + using var reader = new PackageArchiveReader(package); - [Fact] - public async Task AValidatedPackageIsRepositorySigned() - { - var (path, fingerprint) = CreateSigningCertificate(); - var client = CreateClient(new Dictionary - { - { "Validation:RepositorySigningCertificatePath", path }, - { "Validation:RepositorySigningCertificatePassword", "test" }, - { "Validation:RepositorySigningServiceIndexUrl", "https://localhost/v3/index.json" }, - }); - - await PushAsync(client, "Signed.Package", "1.0.0"); - Assert.Equal("Available", await WaitForResultAsync(client, "Signed.Package", "1.0.0")); - - using var download = await client.GetAsync("v3/package/signed.package/1.0.0/signed.package.1.0.0.nupkg"); - using var package = new MemoryStream(await download.Content.ReadAsByteArrayAsync()); - using var reader = new PackageArchiveReader(package); - - Assert.True(await reader.IsSignedAsync(CancellationToken.None)); - var signature = await reader.GetPrimarySignatureAsync(CancellationToken.None); - Assert.Equal(SignatureType.Repository, signature.Type); - - // The resource lists the certificate that signed it, and serves it. - using var resource = JsonDocument.Parse(await client.GetStringAsync("v3/repository-signatures/index.json")); - var certificate = resource.RootElement.GetProperty("signingCertificates")[0]; - Assert.Equal(fingerprint, certificate.GetProperty("fingerprints").GetProperty("2.16.840.1.101.3.4.2.1").GetString()); - Assert.False(resource.RootElement.GetProperty("allRepositorySigned").GetBoolean()); - - using var crt = await client.GetAsync(certificate.GetProperty("contentUrl").GetString()); - Assert.Equal(HttpStatusCode.OK, crt.StatusCode); - - var index = await client.GetStringAsync("v3/index.json"); - Assert.Contains("RepositorySignatures/5.0.0", index); - } + Assert.True(await reader.IsSignedAsync(CancellationToken.None)); + var signature = await reader.GetPrimarySignatureAsync(CancellationToken.None); + Assert.Equal(SignatureType.Repository, signature.Type); - [Fact] - public async Task ASignedPackagePassesWhenSignaturesAreRequired() - { - // Sign a package on one server, then push the signed copy to another that - // requires signatures: its signature must verify, untrusted root and all. - var (path, _) = CreateSigningCertificate(); - var signer = CreateClient(new Dictionary - { - { "Validation:RepositorySigningCertificatePath", path }, - { "Validation:RepositorySigningCertificatePassword", "test" }, - { "Validation:RepositorySigningServiceIndexUrl", "https://localhost/v3/index.json" }, - }); - await PushAsync(signer, "Resigned.Package", "1.0.0"); - Assert.Equal("Available", await WaitForResultAsync(signer, "Resigned.Package", "1.0.0")); - var signed = await signer.GetByteArrayAsync("v3/package/resigned.package/1.0.0/resigned.package.1.0.0.nupkg"); - - var strict = CreateClient(new Dictionary { { "Validation:RequireSignedPackages", "true" } }); - using (var package = new MemoryStream(signed)) - using (var request = TestPackages.PushRequest(package, apiKey: null)) - using (var response = await strict.SendAsync(request)) - { - Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); - } - - Assert.Equal("Available", await WaitForResultAsync(strict, "Resigned.Package", "1.0.0")); - } + // The resource lists the certificate that signed it, and serves it. + using var resource = JsonDocument.Parse(await client.GetStringAsync("v3/repository-signatures/index.json")); + var certificate = resource.RootElement.GetProperty("signingCertificates")[0]; + Assert.Equal(fingerprint, certificate.GetProperty("fingerprints").GetProperty("2.16.840.1.101.3.4.2.1").GetString()); + Assert.False(resource.RootElement.GetProperty("allRepositorySigned").GetBoolean()); + + using var crt = await client.GetAsync(certificate.GetProperty("contentUrl").GetString()); + Assert.Equal(HttpStatusCode.OK, crt.StatusCode); - [Fact] - public async Task SigningWithAnInsecureSourceUrlQuarantinesWithAReason() + var index = await client.GetStringAsync("v3/index.json"); + Assert.Contains("RepositorySignatures/5.0.0", index); + } + + [Fact] + public async Task ASignedPackagePassesWhenSignaturesAreRequired() + { + // Sign a package on one server, then push the signed copy to another that + // requires signatures: its signature must verify, untrusted root and all. + var (path, _) = CreateSigningCertificate(); + var signer = CreateClient(new Dictionary { - var (path, _) = CreateSigningCertificate(); - var client = CreateClient(new Dictionary - { - { "Validation:RepositorySigningCertificatePath", path }, - { "Validation:RepositorySigningCertificatePassword", "test" }, - { "Validation:RepositorySigningServiceIndexUrl", "http://localhost/v3/index.json" }, - }); - - await PushAsync(client, "Insecure.Package", "1.0.0"); - - Assert.Equal("Quarantined", await WaitForResultAsync(client, "Insecure.Package", "1.0.0")); - using var status = JsonDocument.Parse(await client.GetStringAsync("v3/package/Insecure.Package/1.0.0/validation")); - var index = status.RootElement.GetProperty("steps").EnumerateArray().Single(s => s.GetProperty("type").GetString() == "Index"); - Assert.Contains("https", index.GetProperty("message").GetString()); + { "Validation:RepositorySigningCertificatePath", path }, + { "Validation:RepositorySigningCertificatePassword", "test" }, + { "Validation:RepositorySigningServiceIndexUrl", "https://localhost/v3/index.json" }, + }); + await PushAsync(signer, "Resigned.Package", "1.0.0"); + Assert.Equal("Available", await WaitForResultAsync(signer, "Resigned.Package", "1.0.0")); + var signed = await signer.GetByteArrayAsync("v3/package/resigned.package/1.0.0/resigned.package.1.0.0.nupkg"); + + var strict = CreateClient(new Dictionary { { "Validation:RequireSignedPackages", "true" } }); + using (var package = new MemoryStream(signed)) + using (var request = TestPackages.PushRequest(package, apiKey: null)) + using (var response = await strict.SendAsync(request)) + { + Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); } - [Fact] - public async Task WithoutASigningCertificateTheResourceIsAbsent() + Assert.Equal("Available", await WaitForResultAsync(strict, "Resigned.Package", "1.0.0")); + } + + [Fact] + public async Task SigningWithAnInsecureSourceUrlQuarantinesWithAReason() + { + var (path, _) = CreateSigningCertificate(); + var client = CreateClient(new Dictionary { - var client = CreateClient(); + { "Validation:RepositorySigningCertificatePath", path }, + { "Validation:RepositorySigningCertificatePassword", "test" }, + { "Validation:RepositorySigningServiceIndexUrl", "http://localhost/v3/index.json" }, + }); - Assert.DoesNotContain("RepositorySignatures", await client.GetStringAsync("v3/index.json")); - using var response = await client.GetAsync("v3/repository-signatures/index.json"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + await PushAsync(client, "Insecure.Package", "1.0.0"); + + Assert.Equal("Quarantined", await WaitForResultAsync(client, "Insecure.Package", "1.0.0")); + using var status = JsonDocument.Parse(await client.GetStringAsync("v3/package/Insecure.Package/1.0.0/validation")); + var index = status.RootElement.GetProperty("steps").EnumerateArray().Single(s => s.GetProperty("type").GetString() == "Index"); + Assert.Contains("https", index.GetProperty("message").GetString()); + } + + [Fact] + public async Task WithoutASigningCertificateTheResourceIsAbsent() + { + var client = CreateClient(); + + Assert.DoesNotContain("RepositorySignatures", await client.GetStringAsync("v3/index.json")); + using var response = await client.GetAsync("v3/repository-signatures/index.json"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - private HttpClient CreateClient( - Dictionary config = null, - Action configureServices = null) + private HttpClient CreateClient( + Dictionary config = null, + Action configureServices = null) + { + var settings = new Dictionary { { "Validation:Enabled", "true" } }; + foreach (var pair in config ?? new Dictionary()) { - var settings = new Dictionary { { "Validation:Enabled", "true" } }; - foreach (var pair in config ?? new Dictionary()) - { - settings[pair.Key] = pair.Value; - } - - var app = new BaGetApplication(_output, configOverrides: settings, configureServices: configureServices); - var client = app.CreateClient(); - _disposables.Add(client); - _disposables.Add(app); - - return client; + settings[pair.Key] = pair.Value; } - private static async Task PushAsync(HttpClient client, string id, string version) - { - using var package = TestPackages.Build(id, version); - using var request = TestPackages.PushRequest(package, apiKey: null); - using var response = await client.SendAsync(request); + var app = new BaGetApplication(_output, configOverrides: settings, configureServices: configureServices); + var client = app.CreateClient(); + _disposables.Add(client); + _disposables.Add(app); - return response.StatusCode; - } + return client; + } - private static async Task StatusAsync(HttpClient client, string id, string version) - { - using var status = JsonDocument.Parse(await client.GetStringAsync($"v3/package/{id}/{version}/validation")); + private static async Task PushAsync(HttpClient client, string id, string version) + { + using var package = TestPackages.Build(id, version); + using var request = TestPackages.PushRequest(package, apiKey: null); + using var response = await client.SendAsync(request); - return status.RootElement.GetProperty("status").GetString(); - } + return response.StatusCode; + } + + private static async Task StatusAsync(HttpClient client, string id, string version) + { + using var status = JsonDocument.Parse(await client.GetStringAsync($"v3/package/{id}/{version}/validation")); - private static async Task WaitForResultAsync(HttpClient client, string id, string version) + return status.RootElement.GetProperty("status").GetString(); + } + + private static async Task WaitForResultAsync(HttpClient client, string id, string version) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (true) { - var deadline = DateTime.UtcNow.AddSeconds(30); - while (true) - { - var status = await StatusAsync(client, id, version); - if (status != "Validating" || DateTime.UtcNow > deadline) return status; - - await Task.Delay(50); - } + var status = await StatusAsync(client, id, version); + if (status != "Validating" || DateTime.UtcNow > deadline) return status; + + await Task.Delay(50); } + } - private static async Task AssertNotServedAsync(HttpClient client, string id, string version) - { - var lower = id.ToLowerInvariant(); + private static async Task AssertNotServedAsync(HttpClient client, string id, string version) + { + var lower = id.ToLowerInvariant(); - using var download = await client.GetAsync($"v3/package/{lower}/{version}/{lower}.{version}.nupkg"); - Assert.Equal(HttpStatusCode.NotFound, download.StatusCode); + using var download = await client.GetAsync($"v3/package/{lower}/{version}/{lower}.{version}.nupkg"); + Assert.Equal(HttpStatusCode.NotFound, download.StatusCode); - using var registration = await client.GetAsync($"v3/registration/{lower}/index.json"); - Assert.Equal(HttpStatusCode.NotFound, registration.StatusCode); - } + using var registration = await client.GetAsync($"v3/registration/{lower}/index.json"); + Assert.Equal(HttpStatusCode.NotFound, registration.StatusCode); + } - /// - /// A self-signed code signing certificate, as a PFX file, and its SHA-256 fingerprint. - /// - private (string Path, string Fingerprint) CreateSigningCertificate() - { - using var rsa = RSA.Create(2048); - var request = new CertificateRequest("CN=BaGet Test Repository", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); - request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); - request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true)); - request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( - new OidCollection { new Oid("1.3.6.1.5.5.7.3.3") }, // Code signing. - false)); + /// + /// A self-signed code signing certificate, as a PFX file, and its SHA-256 fingerprint. + /// + private (string Path, string Fingerprint) CreateSigningCertificate() + { + using var rsa = RSA.Create(2048); + var request = new CertificateRequest("CN=BaGet Test Repository", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( + new OidCollection { new Oid("1.3.6.1.5.5.7.3.3") }, // Code signing. + false)); - using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); - var path = Path.Combine(Path.GetTempPath(), "BaGetTests", Guid.NewGuid().ToString("N") + ".pfx"); - Directory.CreateDirectory(Path.GetDirectoryName(path)); - File.WriteAllBytes(path, certificate.Export(X509ContentType.Pfx, "test")); + var path = Path.Combine(Path.GetTempPath(), "BaGetTests", Guid.NewGuid().ToString("N") + ".pfx"); + Directory.CreateDirectory(Path.GetDirectoryName(path)); + File.WriteAllBytes(path, certificate.Export(X509ContentType.Pfx, "test")); - return (path, RepositorySignaturesController.Fingerprint(certificate.RawData)); - } + return (path, RepositorySignaturesController.Fingerprint(certificate.RawData)); + } - public void Dispose() + public void Dispose() + { + foreach (var disposable in Enumerable.Reverse(_disposables)) { - foreach (var disposable in Enumerable.Reverse(_disposables)) - { - disposable.Dispose(); - } + disposable.Dispose(); } + } - private class GateValidator : IPackageValidator - { - public TaskCompletionSource Entered { get; } = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - public TaskCompletionSource Release { get; } = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + private class GateValidator : IPackageValidator + { + public TaskCompletionSource Entered { get; } = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - public string Name => "Gate"; + public string Name => "Gate"; - public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) - { - Entered.TrySetResult(true); - await Release.Task.WaitAsync(TimeSpan.FromSeconds(30), cancellationToken); + public async Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + { + Entered.TrySetResult(true); + await Release.Task.WaitAsync(TimeSpan.FromSeconds(30), cancellationToken); - return PackageValidatorResult.Valid; - } + return PackageValidatorResult.Valid; } + } - private class RejectingValidator : IPackageValidator - { - public string Name => "Rejecting"; + private class RejectingValidator : IPackageValidator + { + public string Name => "Rejecting"; - public Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) - => Task.FromResult(PackageValidatorResult.Invalid("Rejected by the test.")); - } + public Task ValidateAsync(PackageValidationContext context, CancellationToken cancellationToken) + => Task.FromResult(PackageValidatorResult.Invalid("Rejected by the test.")); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Tests/WebUiIntegrationTests.cs b/tests/BaGet.Tests/WebUiIntegrationTests.cs index 4be4526fe..9a014e97a 100644 --- a/tests/BaGet.Tests/WebUiIntegrationTests.cs +++ b/tests/BaGet.Tests/WebUiIntegrationTests.cs @@ -13,276 +13,275 @@ using Xunit; using Xunit.Abstractions; -namespace BaGet.Tests +namespace BaGet.Tests; + +/// +/// Statistics and abuse reports, which work with or without accounts. +/// +public class WebUiIntegrationTests : IDisposable { - /// - /// Statistics and abuse reports, which work with or without accounts. - /// - public class WebUiIntegrationTests : IDisposable + private readonly BaGetApplication _app; + private readonly Browser _browser; + + public WebUiIntegrationTests(ITestOutputHelper output) { - private readonly BaGetApplication _app; - private readonly Browser _browser; + _app = new BaGetApplication(output); + _browser = new Browser(_app); + } - public WebUiIntegrationTests(ITestOutputHelper output) + [Fact] + public async Task StatisticsCountThePackages() + { + using (var package = TestResources.GetResourceStream(TestResources.Package)) { - _app = new BaGetApplication(output); - _browser = new Browser(_app); + await _app.AddPackageAsync(package); } - [Fact] - public async Task StatisticsCountThePackages() - { - using (var package = TestResources.GetResourceStream(TestResources.Package)) - { - await _app.AddPackageAsync(package); - } - - var html = await _browser.GetPageAsync("stats"); + var html = await _browser.GetPageAsync("stats"); - Assert.Contains("

1

", html); - Assert.Contains("

1

", html); - Assert.Contains("TestData", html); - } + Assert.Contains("

1

", html); + Assert.Contains("

1

", html); + Assert.Contains("TestData", html); + } - [Fact] - public async Task AnAbuseReportIsRecorded() + [Fact] + public async Task AnAbuseReportIsRecorded() + { + using var response = await _browser.PostAsync("packages/TestData/1.2.3/report-abuse", new Dictionary { - using var response = await _browser.PostAsync("packages/TestData/1.2.3/report-abuse", new Dictionary - { - { "Reason", "Contains malicious code" }, - { "Details", "It mines coins." }, - { "ReporterEmail", "reporter@example.test" }, - }); - - Assert.Contains("report-submitted", await response.Content.ReadAsStringAsync()); - - var report = Assert.Single(await ReportsAsync()); - Assert.Equal("TestData", report.PackageId); - Assert.Equal("1.2.3", report.PackageVersion); - Assert.Equal("It mines coins.", report.Details); - Assert.Null(report.Resolved); - } + { "Reason", "Contains malicious code" }, + { "Details", "It mines coins." }, + { "ReporterEmail", "reporter@example.test" }, + }); + + Assert.Contains("report-submitted", await response.Content.ReadAsStringAsync()); + + var report = Assert.Single(await ReportsAsync()); + Assert.Equal("TestData", report.PackageId); + Assert.Equal("1.2.3", report.PackageVersion); + Assert.Equal("It mines coins.", report.Details); + Assert.Null(report.Resolved); + } - [Fact] - public async Task AReportNeedsAKnownReason() + [Fact] + public async Task AReportNeedsAKnownReason() + { + using var response = await _browser.PostAsync("packages/TestData/1.2.3/report-abuse", new Dictionary { - using var response = await _browser.PostAsync("packages/TestData/1.2.3/report-abuse", new Dictionary - { - { "Reason", "Because" }, - { "Details", "x" }, - }); - - Assert.DoesNotContain("report-submitted", await response.Content.ReadAsStringAsync()); - Assert.Empty(await ReportsAsync()); - } + { "Reason", "Because" }, + { "Details", "x" }, + }); - private async Task> ReportsAsync() - { - using var scope = _app.Services.CreateScope(); + Assert.DoesNotContain("report-submitted", await response.Content.ReadAsStringAsync()); + Assert.Empty(await ReportsAsync()); + } - return await scope.ServiceProvider.GetRequiredService().AbuseReports.ToListAsync(); - } + private async Task> ReportsAsync() + { + using var scope = _app.Services.CreateScope(); - public void Dispose() - { - _browser.Dispose(); - _app.Dispose(); - } + return await scope.ServiceProvider.GetRequiredService().AbuseReports.ToListAsync(); } - /// - /// The owner-facing pages: profiles, package management and organizations. - /// - public class AccountsUiIntegrationTests : IDisposable + public void Dispose() { - private const string GlobalKey = "global-key"; + _browser.Dispose(); + _app.Dispose(); + } +} - private readonly BaGetApplication _app; - private readonly HttpClient _client; - private readonly Browser _alice; - private readonly Browser _bob; +/// +/// The owner-facing pages: profiles, package management and organizations. +/// +public class AccountsUiIntegrationTests : IDisposable +{ + private const string GlobalKey = "global-key"; - public AccountsUiIntegrationTests(ITestOutputHelper output) - { - _app = new BaGetApplication(output, configOverrides: new Dictionary - { - { "ApiKey", GlobalKey }, - { "Accounts:Enabled", "true" }, - }); - _client = _app.CreateClient(); - _alice = new Browser(_app); - _bob = new Browser(_app); - } + private readonly BaGetApplication _app; + private readonly HttpClient _client; + private readonly Browser _alice; + private readonly Browser _bob; - [Fact] - public async Task AProfileListsTheUsersPackages() + public AccountsUiIntegrationTests(ITestOutputHelper output) + { + _app = new BaGetApplication(output, configOverrides: new Dictionary { - await _alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); + { "ApiKey", GlobalKey }, + { "Accounts:Enabled", "true" }, + }); + _client = _app.CreateClient(); + _alice = new Browser(_app); + _bob = new Browser(_app); + } - using var redirect = await _alice.GetAsync("account/profile"); - Assert.Equal(HttpStatusCode.Redirect, redirect.StatusCode); - Assert.EndsWith("/profiles/alice", redirect.Headers.Location.ToString()); + [Fact] + public async Task AProfileListsTheUsersPackages() + { + await _alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); - var html = await _bob.GetPageAsync("profiles/alice"); - Assert.Contains("Alice.Package", html); - } + using var redirect = await _alice.GetAsync("account/profile"); + Assert.Equal(HttpStatusCode.Redirect, redirect.StatusCode); + Assert.EndsWith("/profiles/alice", redirect.Headers.Location.ToString()); - [Fact] - public async Task AnUnknownProfileIsNotFound() - { - using var response = await _bob.GetAsync("profiles/nobody"); + var html = await _bob.GetPageAsync("profiles/alice"); + Assert.Contains("Alice.Package", html); + } - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + [Fact] + public async Task AnUnknownProfileIsNotFound() + { + using var response = await _bob.GetAsync("profiles/nobody"); - [Fact] - public async Task AnOwnerCanUnlistFromTheManagePage() - { - await _alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); - - using var response = await _alice.PostAsync("packages/Alice.Package/manage", new Dictionary - { - { "version", "1.0.0" }, - }, action: "packages/Alice.Package/manage?handler=Unlist"); - - Assert.Contains("is unlisted", await response.Content.ReadAsStringAsync()); - var package = await WithScopeAsync(s => s.GetRequiredService() - .FindOrNullAsync("Alice.Package", NuGet.Versioning.NuGetVersion.Parse("1.0.0"), includeUnlisted: true, CancellationToken.None)); - Assert.False(package.Listed); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } - [Fact] - public async Task AnOwnerCanDeprecateFromTheManagePage() - { - await _alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); - - using var response = await _alice.PostAsync("packages/Alice.Package/manage", new Dictionary - { - { "version", "1.0.0" }, - { "reasons", "Legacy" }, - { "message", "Use the new one" }, - }, action: "packages/Alice.Package/manage?handler=Deprecate"); - - Assert.Contains("is deprecated", await response.Content.ReadAsStringAsync()); - var registration = await _client.GetStringAsync("v3/registration/alice.package/index.json"); - Assert.Contains("Use the new one", registration); - } + [Fact] + public async Task AnOwnerCanUnlistFromTheManagePage() + { + await _alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); - [Fact] - public async Task SomeoneElseCannotManageThePackage() + using var response = await _alice.PostAsync("packages/Alice.Package/manage", new Dictionary { - await _alice.RegisterAsync("alice"); - await _bob.RegisterAsync("bob"); - await PushAsAsync("alice", "Alice.Package"); + { "version", "1.0.0" }, + }, action: "packages/Alice.Package/manage?handler=Unlist"); - using var response = await _bob.GetAsync("packages/Alice.Package/manage"); + Assert.Contains("is unlisted", await response.Content.ReadAsStringAsync()); + var package = await WithScopeAsync(s => s.GetRequiredService() + .FindOrNullAsync("Alice.Package", NuGet.Versioning.NuGetVersion.Parse("1.0.0"), includeUnlisted: true, CancellationToken.None)); + Assert.False(package.Listed); + } - Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); - } + [Fact] + public async Task AnOwnerCanDeprecateFromTheManagePage() + { + await _alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); - [Fact] - public async Task TheManagePageNeedsASignedInUser() + using var response = await _alice.PostAsync("packages/Alice.Package/manage", new Dictionary { - using var response = await _bob.GetAsync("packages/Alice.Package/manage"); + { "version", "1.0.0" }, + { "reasons", "Legacy" }, + { "message", "Use the new one" }, + }, action: "packages/Alice.Package/manage?handler=Deprecate"); + + Assert.Contains("is deprecated", await response.Content.ReadAsStringAsync()); + var registration = await _client.GetStringAsync("v3/registration/alice.package/index.json"); + Assert.Contains("Use the new one", registration); + } - Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.Contains("/account/login", response.Headers.Location.ToString()); - } + [Fact] + public async Task SomeoneElseCannotManageThePackage() + { + await _alice.RegisterAsync("alice"); + await _bob.RegisterAsync("bob"); + await PushAsAsync("alice", "Alice.Package"); + + using var response = await _bob.GetAsync("packages/Alice.Package/manage"); + + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } - [Fact] - public async Task AnOwnerCanAddAnotherOwner() + [Fact] + public async Task TheManagePageNeedsASignedInUser() + { + using var response = await _bob.GetAsync("packages/Alice.Package/manage"); + + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/account/login", response.Headers.Location.ToString()); + } + + [Fact] + public async Task AnOwnerCanAddAnotherOwner() + { + await _alice.RegisterAsync("alice"); + await _bob.RegisterAsync("bob"); + await PushAsAsync("alice", "Alice.Package"); + + using (await _alice.PostAsync("packages/Alice.Package/manage", new Dictionary + { + { "ownerName", "bob" }, + }, action: "packages/Alice.Package/manage?handler=AddOwner")) { - await _alice.RegisterAsync("alice"); - await _bob.RegisterAsync("bob"); - await PushAsAsync("alice", "Alice.Package"); - - using (await _alice.PostAsync("packages/Alice.Package/manage", new Dictionary - { - { "ownerName", "bob" }, - }, action: "packages/Alice.Package/manage?handler=AddOwner")) - { - } - - using var response = await _bob.GetAsync("packages/Alice.Package/manage"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] - public async Task OwnersSeeAndResolveAbuseReports() + using var response = await _bob.GetAsync("packages/Alice.Package/manage"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task OwnersSeeAndResolveAbuseReports() + { + await _alice.RegisterAsync("alice"); + await PushAsAsync("alice", "Alice.Package"); + using (await _bob.PostAsync("packages/Alice.Package/1.0.0/report-abuse", new Dictionary + { + { "Reason", "Other" }, + { "Details", "Suspicious behaviour" }, + })) { - await _alice.RegisterAsync("alice"); - await PushAsAsync("alice", "Alice.Package"); - using (await _bob.PostAsync("packages/Alice.Package/1.0.0/report-abuse", new Dictionary - { - { "Reason", "Other" }, - { "Details", "Suspicious behaviour" }, - })) - { - } - - var html = await _alice.GetPageAsync("packages/Alice.Package/manage"); - Assert.Contains("Suspicious behaviour", html); - - var key = await WithScopeAsync(async s => (await s.GetRequiredService().AbuseReports.SingleAsync()).Key); - using (await _alice.PostAsync("packages/Alice.Package/manage", new Dictionary - { - { "key", key.ToString() }, - }, action: "packages/Alice.Package/manage?handler=ResolveReport")) - { - } - - Assert.DoesNotContain("Suspicious behaviour", await _alice.GetPageAsync("packages/Alice.Package/manage")); } - [Fact] - public async Task AUserCanCreateAnOrganization() + var html = await _alice.GetPageAsync("packages/Alice.Package/manage"); + Assert.Contains("Suspicious behaviour", html); + + var key = await WithScopeAsync(async s => (await s.GetRequiredService().AbuseReports.SingleAsync()).Key); + using (await _alice.PostAsync("packages/Alice.Package/manage", new Dictionary + { + { "key", key.ToString() }, + }, action: "packages/Alice.Package/manage?handler=ResolveReport")) { - await _alice.RegisterAsync("alice"); + } - using (await _alice.PostAsync("account/organizations", new Dictionary - { - { "name", "contoso" }, - }, action: "account/organizations?handler=Create")) - { - } + Assert.DoesNotContain("Suspicious behaviour", await _alice.GetPageAsync("packages/Alice.Package/manage")); + } - var html = await _bob.GetPageAsync("profiles/contoso"); - Assert.Contains("alice", html); + [Fact] + public async Task AUserCanCreateAnOrganization() + { + await _alice.RegisterAsync("alice"); + + using (await _alice.PostAsync("account/organizations", new Dictionary + { + { "name", "contoso" }, + }, action: "account/organizations?handler=Create")) + { } - private async Task PushAsAsync(string userName, string packageId) + var html = await _bob.GetPageAsync("profiles/contoso"); + Assert.Contains("alice", html); + } + + private async Task PushAsAsync(string userName, string packageId) + { + var key = await WithScopeAsync(async s => { - var key = await WithScopeAsync(async s => - { - var user = await s.GetRequiredService>().FindByNameAsync(userName); + var user = await s.GetRequiredService>().FindByNameAsync(userName); - return await s.GetRequiredService().CreateAsync( - user.Id, "test", new[] { ApiKeyScopes.Push }, "*", expires: null, CancellationToken.None); - }); + return await s.GetRequiredService().CreateAsync( + user.Id, "test", new[] { ApiKeyScopes.Push }, "*", expires: null, CancellationToken.None); + }); - using var package = TestPackages.Build(packageId, "1.0.0"); - using var request = TestPackages.PushRequest(package, key); - using var response = await _client.SendAsync(request); + using var package = TestPackages.Build(packageId, "1.0.0"); + using var request = TestPackages.PushRequest(package, key); + using var response = await _client.SendAsync(request); - Assert.Equal(HttpStatusCode.Created, response.StatusCode); - } + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } - private async Task WithScopeAsync(Func> action) - { - using var scope = _app.Services.CreateScope(); + private async Task WithScopeAsync(Func> action) + { + using var scope = _app.Services.CreateScope(); - return await action(scope.ServiceProvider); - } + return await action(scope.ServiceProvider); + } - public void Dispose() - { - _alice.Dispose(); - _bob.Dispose(); - _client.Dispose(); - _app.Dispose(); - } + public void Dispose() + { + _alice.Dispose(); + _bob.Dispose(); + _client.Dispose(); + _app.Dispose(); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Web.Tests/NavLinkTagHelperTests.cs b/tests/BaGet.Web.Tests/NavLinkTagHelperTests.cs index 8d3fa4fc7..ed08a2ebd 100644 --- a/tests/BaGet.Web.Tests/NavLinkTagHelperTests.cs +++ b/tests/BaGet.Web.Tests/NavLinkTagHelperTests.cs @@ -5,208 +5,207 @@ using Microsoft.AspNetCore.Razor.TagHelpers; using Xunit; -namespace BaGet.Web.Tests +namespace BaGet.Web.Tests; + +public class NavLinkTagHelperTests { - public class NavLinkTagHelperTests + private static TagHelperOutput Output(params (string Name, string Value)[] attributes) { - private static TagHelperOutput Output(params (string Name, string Value)[] attributes) + var list = new TagHelperAttributeList(); + foreach (var attribute in attributes) { - var list = new TagHelperAttributeList(); - foreach (var attribute in attributes) - { - list.Add(attribute.Name, attribute.Value); - } - - return new TagHelperOutput( - "a", - list, - (useCachedResult, encoder) => - Task.FromResult(new DefaultTagHelperContent())); + list.Add(attribute.Name, attribute.Value); } - private static TagHelperContext Context() - => new TagHelperContext( - new TagHelperAttributeList(), - new Dictionary(), - "test"); - - private static IHttpContextAccessor Accessor( - string viewEnginePath, - string requestPath = "/", - string areaName = null, - bool withEndpoint = true, - bool withHttpContext = true) + return new TagHelperOutput( + "a", + list, + (useCachedResult, encoder) => + Task.FromResult(new DefaultTagHelperContent())); + } + + private static TagHelperContext Context() + => new TagHelperContext( + new TagHelperAttributeList(), + new Dictionary(), + "test"); + + private static IHttpContextAccessor Accessor( + string viewEnginePath, + string requestPath = "/", + string areaName = null, + bool withEndpoint = true, + bool withHttpContext = true) + { + if (!withHttpContext) { - if (!withHttpContext) - { - return new HttpContextAccessor(); - } + return new HttpContextAccessor(); + } - var httpContext = new DefaultHttpContext(); - httpContext.Request.Path = requestPath; + var httpContext = new DefaultHttpContext(); + httpContext.Request.Path = requestPath; - if (withEndpoint) + if (withEndpoint) + { + var descriptor = new PageActionDescriptor { - var descriptor = new PageActionDescriptor - { - ViewEnginePath = viewEnginePath, - AreaName = areaName, - }; - - httpContext.SetEndpoint(new Endpoint( - _ => Task.CompletedTask, - new EndpointMetadataCollection(descriptor), - "test")); - } - - return new HttpContextAccessor { HttpContext = httpContext }; + ViewEnginePath = viewEnginePath, + AreaName = areaName, + }; + + httpContext.SetEndpoint(new Endpoint( + _ => Task.CompletedTask, + new EndpointMetadataCollection(descriptor), + "test")); } - private static string ClassOf(TagHelperOutput output) - => output.Attributes.ContainsName("class") - ? output.Attributes["class"].Value?.ToString() - : null; + return new HttpContextAccessor { HttpContext = httpContext }; + } - [Fact] - public void MarksTheLinkForTheCurrentPageActive() - { - var target = new NavLinkTagHelper(Accessor("/Upload")) { Page = "/Upload" }; - var output = Output(); + private static string ClassOf(TagHelperOutput output) + => output.Attributes.ContainsName("class") + ? output.Attributes["class"].Value?.ToString() + : null; - target.Process(Context(), output); + [Fact] + public void MarksTheLinkForTheCurrentPageActive() + { + var target = new NavLinkTagHelper(Accessor("/Upload")) { Page = "/Upload" }; + var output = Output(); - Assert.Equal("active", ClassOf(output)); - } + target.Process(Context(), output); - [Fact] - public void LeavesALinkForAnotherPageAlone() - { - var target = new NavLinkTagHelper(Accessor("/Index")) { Page = "/Upload" }; - var output = Output(); + Assert.Equal("active", ClassOf(output)); + } - target.Process(Context(), output); + [Fact] + public void LeavesALinkForAnotherPageAlone() + { + var target = new NavLinkTagHelper(Accessor("/Index")) { Page = "/Upload" }; + var output = Output(); - Assert.Null(ClassOf(output)); - } + target.Process(Context(), output); - [Fact] - public void KeepsTheClassesTheElementAlreadyHas() - { - // The helper targets any element carrying "nav-link", so it must add its class - // rather than replace whatever the markup specified. - var target = new NavLinkTagHelper(Accessor("/Upload")) { Page = "/Upload" }; - var output = Output(("class", "nav-item highlighted")); + Assert.Null(ClassOf(output)); + } - target.Process(Context(), output); + [Fact] + public void KeepsTheClassesTheElementAlreadyHas() + { + // The helper targets any element carrying "nav-link", so it must add its class + // rather than replace whatever the markup specified. + var target = new NavLinkTagHelper(Accessor("/Upload")) { Page = "/Upload" }; + var output = Output(("class", "nav-item highlighted")); - var classes = ClassOf(output); - Assert.Contains("nav-item", classes); - Assert.Contains("highlighted", classes); - Assert.Contains("active", classes); - } + target.Process(Context(), output); - [Fact] - public void DoesNotAddTheClassTwice() - { - var target = new NavLinkTagHelper(Accessor("/Upload")) { Page = "/Upload" }; - var output = Output(("class", "active")); + var classes = ClassOf(output); + Assert.Contains("nav-item", classes); + Assert.Contains("highlighted", classes); + Assert.Contains("active", classes); + } - target.Process(Context(), output); + [Fact] + public void DoesNotAddTheClassTwice() + { + var target = new NavLinkTagHelper(Accessor("/Upload")) { Page = "/Upload" }; + var output = Output(("class", "active")); - Assert.Equal("active", ClassOf(output)); - } + target.Process(Context(), output); - [Fact] - public void IsNotActiveWithoutAnHttpContext() + Assert.Equal("active", ClassOf(output)); + } + + [Fact] + public void IsNotActiveWithoutAnHttpContext() + { + var target = new NavLinkTagHelper(Accessor("/Upload", withHttpContext: false)) { - var target = new NavLinkTagHelper(Accessor("/Upload", withHttpContext: false)) - { - Page = "/Upload", - }; - var output = Output(); + Page = "/Upload", + }; + var output = Output(); - target.Process(Context(), output); + target.Process(Context(), output); - Assert.Null(ClassOf(output)); - } + Assert.Null(ClassOf(output)); + } - [Fact] - public void IsNotActiveWithoutAnEndpoint() + [Fact] + public void IsNotActiveWithoutAnEndpoint() + { + var target = new NavLinkTagHelper(Accessor("/Upload", withEndpoint: false)) { - var target = new NavLinkTagHelper(Accessor("/Upload", withEndpoint: false)) - { - Page = "/Upload", - }; - var output = Output(); + Page = "/Upload", + }; + var output = Output(); - target.Process(Context(), output); + target.Process(Context(), output); - Assert.Null(ClassOf(output)); - } + Assert.Null(ClassOf(output)); + } - [Fact] - public void IsNotActiveForAPageInAnArea() + [Fact] + public void IsNotActiveForAPageInAnArea() + { + var target = new NavLinkTagHelper(Accessor("/Upload", areaName: "Admin")) { - var target = new NavLinkTagHelper(Accessor("/Upload", areaName: "Admin")) - { - Page = "/Upload", - }; - var output = Output(); + Page = "/Upload", + }; + var output = Output(); - target.Process(Context(), output); + target.Process(Context(), output); - Assert.Null(ClassOf(output)); - } + Assert.Null(ClassOf(output)); + } - [Theory] - [InlineData("/packages")] - [InlineData("/")] - public void ThePackagesLinkIsActiveOnBothOfItsRoutes(string requestPath) - { - // _Layout.cshtml links to /packages with no asp-page, and both / and /packages - // render the Index page. - var target = new NavLinkTagHelper(Accessor("/Index", requestPath)); - var output = Output(); + [Theory] + [InlineData("/packages")] + [InlineData("/")] + public void ThePackagesLinkIsActiveOnBothOfItsRoutes(string requestPath) + { + // _Layout.cshtml links to /packages with no asp-page, and both / and /packages + // render the Index page. + var target = new NavLinkTagHelper(Accessor("/Index", requestPath)); + var output = Output(); - target.Process(Context(), output); + target.Process(Context(), output); - Assert.Equal("active", ClassOf(output)); - } + Assert.Equal("active", ClassOf(output)); + } - [Theory] - [InlineData("/Packages")] - [InlineData("/PACKAGES")] - public void ThePackagesLinkIsActiveWhateverTheCaseOfTheRequestPath(string requestPath) - { - // Routing is case-insensitive, so these all render the package list. - var target = new NavLinkTagHelper(Accessor("/Index", requestPath)); - var output = Output(); + [Theory] + [InlineData("/Packages")] + [InlineData("/PACKAGES")] + public void ThePackagesLinkIsActiveWhateverTheCaseOfTheRequestPath(string requestPath) + { + // Routing is case-insensitive, so these all render the package list. + var target = new NavLinkTagHelper(Accessor("/Index", requestPath)); + var output = Output(); - target.Process(Context(), output); + target.Process(Context(), output); - Assert.Equal("active", ClassOf(output)); - } + Assert.Equal("active", ClassOf(output)); + } - [Fact] - public void ThePackagesLinkIsActiveWithATrailingSlash() - { - var target = new NavLinkTagHelper(Accessor("/Index", "/packages/")); - var output = Output(); + [Fact] + public void ThePackagesLinkIsActiveWithATrailingSlash() + { + var target = new NavLinkTagHelper(Accessor("/Index", "/packages/")); + var output = Output(); - target.Process(Context(), output); + target.Process(Context(), output); - Assert.Equal("active", ClassOf(output)); - } + Assert.Equal("active", ClassOf(output)); + } - [Fact] - public void ThePackagesLinkIsNotActiveOnAnUnrelatedPath() - { - var target = new NavLinkTagHelper(Accessor("/Index", "/something-else")); - var output = Output(); + [Fact] + public void ThePackagesLinkIsNotActiveOnAnUnrelatedPath() + { + var target = new NavLinkTagHelper(Accessor("/Index", "/something-else")); + var output = Output(); - target.Process(Context(), output); + target.Process(Context(), output); - Assert.Null(ClassOf(output)); - } + Assert.Null(ClassOf(output)); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Web.Tests/Pages/IndexModelFacts.cs b/tests/BaGet.Web.Tests/Pages/IndexModelFacts.cs index 85ee67299..1860d0687 100644 --- a/tests/BaGet.Web.Tests/Pages/IndexModelFacts.cs +++ b/tests/BaGet.Web.Tests/Pages/IndexModelFacts.cs @@ -5,59 +5,58 @@ using Moq; using Xunit; -namespace BaGet.Web.Tests +namespace BaGet.Web.Tests; + +public class IndexModelFacts { - public class IndexModelFacts + private readonly IndexModel _target; + + private SearchRequest _capturedRequest = null; + private readonly SearchResponse _response = new SearchResponse(); + private readonly CancellationToken _cancellation = CancellationToken.None; + + public IndexModelFacts() + { + var search = new Mock(); + search + .Setup(s => s.SearchAsync(It.IsAny(), _cancellation)) + .Callback((SearchRequest r, CancellationToken c) => _capturedRequest = r) + .ReturnsAsync(_response); + + _target = new IndexModel(search.Object); + } + + [Fact] + public async Task DefaultSearch() + { + await _target.OnGetAsync(_cancellation); + + Assert.Equal(0, _capturedRequest.Skip); + Assert.Equal(20, _capturedRequest.Take); + Assert.True(_capturedRequest.IncludePrerelease); + Assert.True(_capturedRequest.IncludeSemVer2); + Assert.Null(_capturedRequest.PackageType); + Assert.Null(_capturedRequest.Framework); + Assert.Null(_capturedRequest.Query); + } + + [Fact] + public async Task AcceptsParameters() { - private readonly IndexModel _target; - - private SearchRequest _capturedRequest = null; - private readonly SearchResponse _response = new SearchResponse(); - private readonly CancellationToken _cancellation = CancellationToken.None; - - public IndexModelFacts() - { - var search = new Mock(); - search - .Setup(s => s.SearchAsync(It.IsAny(), _cancellation)) - .Callback((SearchRequest r, CancellationToken c) => _capturedRequest = r) - .ReturnsAsync(_response); - - _target = new IndexModel(search.Object); - } - - [Fact] - public async Task DefaultSearch() - { - await _target.OnGetAsync(_cancellation); - - Assert.Equal(0, _capturedRequest.Skip); - Assert.Equal(20, _capturedRequest.Take); - Assert.True(_capturedRequest.IncludePrerelease); - Assert.True(_capturedRequest.IncludeSemVer2); - Assert.Null(_capturedRequest.PackageType); - Assert.Null(_capturedRequest.Framework); - Assert.Null(_capturedRequest.Query); - } - - [Fact] - public async Task AcceptsParameters() - { - _target.Prerelease = false; - _target.PageIndex = 5; - _target.PackageType = "foo"; - _target.Framework = "bar"; - _target.Query = "Hello world"; - - await _target.OnGetAsync(_cancellation); - - Assert.Equal(80, _capturedRequest.Skip); - Assert.Equal(20, _capturedRequest.Take); - Assert.False(_capturedRequest.IncludePrerelease); - Assert.True(_capturedRequest.IncludeSemVer2); - Assert.Equal("foo", _capturedRequest.PackageType); - Assert.Equal("bar", _capturedRequest.Framework); - Assert.Equal("Hello world", _capturedRequest.Query); - } + _target.Prerelease = false; + _target.PageIndex = 5; + _target.PackageType = "foo"; + _target.Framework = "bar"; + _target.Query = "Hello world"; + + await _target.OnGetAsync(_cancellation); + + Assert.Equal(80, _capturedRequest.Skip); + Assert.Equal(20, _capturedRequest.Take); + Assert.False(_capturedRequest.IncludePrerelease); + Assert.True(_capturedRequest.IncludeSemVer2); + Assert.Equal("foo", _capturedRequest.PackageType); + Assert.Equal("bar", _capturedRequest.Framework); + Assert.Equal("Hello world", _capturedRequest.Query); } -} +} \ No newline at end of file diff --git a/tests/BaGet.Web.Tests/Pages/PackageModelFacts.cs b/tests/BaGet.Web.Tests/Pages/PackageModelFacts.cs index cefea3416..cf1155f82 100644 --- a/tests/BaGet.Web.Tests/Pages/PackageModelFacts.cs +++ b/tests/BaGet.Web.Tests/Pages/PackageModelFacts.cs @@ -9,358 +9,357 @@ using NuGet.Versioning; using Xunit; -namespace BaGet.Web.Tests +namespace BaGet.Web.Tests; + +public class PackageModelFacts { - public class PackageModelFacts - { - private readonly Mock _content; - private readonly Mock _packages; - private readonly Mock _search; - private readonly Mock _url; - private readonly PackageModel _target; + private readonly Mock _content; + private readonly Mock _packages; + private readonly Mock _search; + private readonly Mock _url; + private readonly PackageModel _target; - private readonly CancellationToken _cancellation = CancellationToken.None; + private readonly CancellationToken _cancellation = CancellationToken.None; - public PackageModelFacts() - { - _content = new Mock(); - _packages = new Mock(); - _search = new Mock(); - _url = new Mock(); - _target = new PackageModel( - _packages.Object, - _content.Object, - _search.Object, - _url.Object); - - _search - .Setup(s => s.FindDependentsAsync("testpackage", _cancellation)) - .ReturnsAsync(new DependentsResponse()); - } + public PackageModelFacts() + { + _content = new Mock(); + _packages = new Mock(); + _search = new Mock(); + _url = new Mock(); + _target = new PackageModel( + _packages.Object, + _content.Object, + _search.Object, + _url.Object); + + _search + .Setup(s => s.FindDependentsAsync("testpackage", _cancellation)) + .ReturnsAsync(new DependentsResponse()); + } - [Fact] - public async Task ReturnsNotFound() - { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List()); + [Fact] + public async Task ReturnsNotFound() + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List()); - await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); + await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - Assert.False(_target.Found); - Assert.Equal("testpackage", _target.Package.Id); - Assert.Null(_target.DependencyGroups); - Assert.Null(_target.Versions); - } + Assert.False(_target.Found); + Assert.Equal("testpackage", _target.Package.Id); + Assert.Null(_target.DependencyGroups); + Assert.Null(_target.Versions); + } - [Fact] - public async Task ReturnsNotFoundIfAllUnlisted() - { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List - { - CreatePackage("1.0.0", listed: false), - }); + [Fact] + public async Task ReturnsNotFoundIfAllUnlisted() + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0", listed: false), + }); - await _target.OnGetAsync("testpackage", version: null, _cancellation); + await _target.OnGetAsync("testpackage", version: null, _cancellation); - Assert.False(_target.Found); - Assert.Equal("testpackage", _target.Package.Id); - Assert.Null(_target.DependencyGroups); - Assert.Null(_target.Versions); - } + Assert.False(_target.Found); + Assert.Equal("testpackage", _target.Package.Id); + Assert.Null(_target.DependencyGroups); + Assert.Null(_target.Versions); + } - [Fact] - public async Task ReturnsRequestedVersion() - { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List - { - CreatePackage("1.0.0"), - CreatePackage("2.0.0"), - CreatePackage("3.0.0"), - }); + [Fact] + public async Task ReturnsRequestedVersion() + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0"), + CreatePackage("2.0.0"), + CreatePackage("3.0.0"), + }); + + await _target.OnGetAsync("testpackage", "2.0.0", _cancellation); + + Assert.True(_target.Found); + Assert.Equal("testpackage", _target.Package.Id); + Assert.Equal("2.0.0", _target.Package.NormalizedVersionString); + + Assert.Equal(3, _target.Versions.Count); + Assert.Equal("3.0.0", _target.Versions[0].Version.OriginalVersion); + Assert.False(_target.Versions[0].Selected); + Assert.Equal("2.0.0", _target.Versions[1].Version.OriginalVersion); + Assert.True(_target.Versions[1].Selected); + Assert.Equal("1.0.0", _target.Versions[2].Version.OriginalVersion); + Assert.False(_target.Versions[2].Selected); + } - await _target.OnGetAsync("testpackage", "2.0.0", _cancellation); + [Fact] + public async Task ReturnsRequestedUnlistedVersion() + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0"), + CreatePackage("2.0.0", listed: false), + CreatePackage("3.0.0"), + }); + + await _target.OnGetAsync("testpackage", "2.0.0", _cancellation); + + Assert.True(_target.Found); + Assert.Equal("testpackage", _target.Package.Id); + Assert.Equal("2.0.0", _target.Package.NormalizedVersionString); + + Assert.Equal(2, _target.Versions.Count); + Assert.Equal("3.0.0", _target.Versions[0].Version.OriginalVersion); + Assert.False(_target.Versions[0].Selected); + Assert.Equal("1.0.0", _target.Versions[1].Version.OriginalVersion); + Assert.False(_target.Versions[1].Selected); + } - Assert.True(_target.Found); - Assert.Equal("testpackage", _target.Package.Id); - Assert.Equal("2.0.0", _target.Package.NormalizedVersionString); + [Fact] + public async Task FallsBackToLatestListedVersion() + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0"), + CreatePackage("2.0.0"), + CreatePackage("3.0.0", listed: false), + }); + + await _target.OnGetAsync("testpackage", "4.0.0", _cancellation); + + Assert.True(_target.Found); + Assert.Equal("testpackage", _target.Package.Id); + Assert.Equal("2.0.0", _target.Package.NormalizedVersionString); + + Assert.Equal(2, _target.Versions.Count); + Assert.Equal("2.0.0", _target.Versions[0].Version.OriginalVersion); + Assert.True(_target.Versions[0].Selected); + Assert.Equal("1.0.0", _target.Versions[1].Version.OriginalVersion); + Assert.False(_target.Versions[1].Selected); + } - Assert.Equal(3, _target.Versions.Count); - Assert.Equal("3.0.0", _target.Versions[0].Version.OriginalVersion); - Assert.False(_target.Versions[0].Selected); - Assert.Equal("2.0.0", _target.Versions[1].Version.OriginalVersion); - Assert.True(_target.Versions[1].Selected); - Assert.Equal("1.0.0", _target.Versions[2].Version.OriginalVersion); - Assert.False(_target.Versions[2].Selected); - } + [Theory] + [InlineData(new[] { "test" }, /*expectDotnetTemplate: */ false, /*expectDotnetTool: */ false)] + [InlineData(new[] { "template" }, /*expectDotnetTemplate: */ true, /*expectDotnetTool: */ false)] + [InlineData(new[] { "dOtNeTtOoL" }, /*expectDotnetTemplate: */ false, /*expectDotnetTool: */ true)] - [Fact] - public async Task ReturnsRequestedUnlistedVersion() - { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List - { - CreatePackage("1.0.0"), - CreatePackage("2.0.0", listed: false), - CreatePackage("3.0.0"), - }); + [InlineData(new[] { "tEmPlAte", "dOtNeTtOoL" }, /*expectDotnetTemplate: */ true, /*expectDotnetTool: */ true)] + public async Task HandlesPackageTypes(IEnumerable packageTypes, bool expectDotnetTemplate, bool expectDotnetTool) + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0", packageTypes: packageTypes) + }); - await _target.OnGetAsync("testpackage", "2.0.0", _cancellation); + await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - Assert.True(_target.Found); - Assert.Equal("testpackage", _target.Package.Id); - Assert.Equal("2.0.0", _target.Package.NormalizedVersionString); + Assert.True(_target.Found); + Assert.Equal(expectDotnetTemplate, _target.IsDotnetTemplate); + Assert.Equal(expectDotnetTool, _target.IsDotnetTool); + } - Assert.Equal(2, _target.Versions.Count); - Assert.Equal("3.0.0", _target.Versions[0].Version.OriginalVersion); - Assert.False(_target.Versions[0].Selected); - Assert.Equal("1.0.0", _target.Versions[1].Version.OriginalVersion); - Assert.False(_target.Versions[1].Selected); - } + [Fact] + public async Task FindsDependentPackages() + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0") + }); - [Fact] - public async Task FallsBackToLatestListedVersion() - { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List + _search + .Setup(s => s.FindDependentsAsync("testpackage", _cancellation)) + .ReturnsAsync(new DependentsResponse + { + Data = new List { - CreatePackage("1.0.0"), - CreatePackage("2.0.0"), - CreatePackage("3.0.0", listed: false), - }); - - await _target.OnGetAsync("testpackage", "4.0.0", _cancellation); - - Assert.True(_target.Found); - Assert.Equal("testpackage", _target.Package.Id); - Assert.Equal("2.0.0", _target.Package.NormalizedVersionString); + new PackageDependent { Id = "Used by 1" }, + new PackageDependent { Id = "Used by 2" }, + } + }); - Assert.Equal(2, _target.Versions.Count); - Assert.Equal("2.0.0", _target.Versions[0].Version.OriginalVersion); - Assert.True(_target.Versions[0].Selected); - Assert.Equal("1.0.0", _target.Versions[1].Version.OriginalVersion); - Assert.False(_target.Versions[1].Selected); - } + await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - [Theory] - [InlineData(new[] { "test" }, /*expectDotnetTemplate: */ false, /*expectDotnetTool: */ false)] - [InlineData(new[] { "template" }, /*expectDotnetTemplate: */ true, /*expectDotnetTool: */ false)] - [InlineData(new[] { "dOtNeTtOoL" }, /*expectDotnetTemplate: */ false, /*expectDotnetTool: */ true)] + Assert.Equal(2, _target.UsedBy.Count); + Assert.Equal("Used by 1", _target.UsedBy[0].Id); + Assert.Equal("Used by 2", _target.UsedBy[1].Id); + } - [InlineData(new[] { "tEmPlAte", "dOtNeTtOoL" }, /*expectDotnetTemplate: */ true, /*expectDotnetTool: */ true)] - public async Task HandlesPackageTypes(IEnumerable packageTypes, bool expectDotnetTemplate, bool expectDotnetTool) - { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List + [Fact] + public async Task GroupsVersions() + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0", dependencies: new[] { - CreatePackage("1.0.0", packageTypes: packageTypes) - }); + new PackageDependency + { + TargetFramework = "net5.0", + Id = "Dependency1", + VersionRange = "[1.0.0, )", + }, + new PackageDependency + { + TargetFramework = "net4.8", + Id = "Dependency2", + VersionRange = "[2.0.0, )", + }, + new PackageDependency + { + TargetFramework = "net5.0", + Id = "Dependency3", + VersionRange = "[3.0.0, )", + }, + }) + }); - await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); + await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - Assert.True(_target.Found); - Assert.Equal(expectDotnetTemplate, _target.IsDotnetTemplate); - Assert.Equal(expectDotnetTool, _target.IsDotnetTool); - } + Assert.True(_target.Found); + Assert.Equal(2, _target.DependencyGroups.Count); + Assert.Equal(".NET 5.0", _target.DependencyGroups[0].Name); + Assert.Equal(".NET Framework 4.8", _target.DependencyGroups[1].Name); - [Fact] - public async Task FindsDependentPackages() - { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List - { - CreatePackage("1.0.0") - }); + Assert.Equal(2, _target.DependencyGroups[0].Dependencies.Count); + Assert.Single(_target.DependencyGroups[1].Dependencies); - _search - .Setup(s => s.FindDependentsAsync("testpackage", _cancellation)) - .ReturnsAsync(new DependentsResponse - { - Data = new List - { - new PackageDependent { Id = "Used by 1" }, - new PackageDependent { Id = "Used by 2" }, - } - }); + Assert.Equal("Dependency1", _target.DependencyGroups[0].Dependencies[0].PackageId); + Assert.Equal("(>= 1.0.0)", _target.DependencyGroups[0].Dependencies[0].VersionSpec); - await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); + Assert.Equal("Dependency3", _target.DependencyGroups[0].Dependencies[1].PackageId); + Assert.Equal("(>= 3.0.0)", _target.DependencyGroups[0].Dependencies[1].VersionSpec); - Assert.Equal(2, _target.UsedBy.Count); - Assert.Equal("Used by 1", _target.UsedBy[0].Id); - Assert.Equal("Used by 2", _target.UsedBy[1].Id); - } + Assert.Equal("Dependency2", _target.DependencyGroups[1].Dependencies[0].PackageId); + Assert.Equal("(>= 2.0.0)", _target.DependencyGroups[1].Dependencies[0].VersionSpec); + } - [Fact] - public async Task GroupsVersions() - { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List + [Theory] + [InlineData(null, "All Frameworks")] + [InlineData("net5.0", ".NET 5.0")] + [InlineData("netstandard2.1", ".NET Standard 2.1")] + [InlineData("net10.0", ".NET 10.0")] + [InlineData("net4.8", ".NET Framework 4.8")] + public async Task PrettifiesTargetFramework(string targetFramework, string expectedResult) + { + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0", dependencies: new[] { - CreatePackage("1.0.0", dependencies: new[] + new PackageDependency { - new PackageDependency - { - TargetFramework = "net5.0", - Id = "Dependency1", - VersionRange = "[1.0.0, )", - }, - new PackageDependency - { - TargetFramework = "net4.8", - Id = "Dependency2", - VersionRange = "[2.0.0, )", - }, - new PackageDependency - { - TargetFramework = "net5.0", - Id = "Dependency3", - VersionRange = "[3.0.0, )", - }, - }) - }); + TargetFramework = targetFramework, + Id = "DependencyPackage", + VersionRange = "[1.0.0, )", + } + }) + }); - await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); + await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - Assert.True(_target.Found); - Assert.Equal(2, _target.DependencyGroups.Count); - Assert.Equal(".NET 5.0", _target.DependencyGroups[0].Name); - Assert.Equal(".NET Framework 4.8", _target.DependencyGroups[1].Name); + Assert.True(_target.Found); + var group = Assert.Single(_target.DependencyGroups); + Assert.Equal(expectedResult, group.Name); + } - Assert.Equal(2, _target.DependencyGroups[0].Dependencies.Count); - Assert.Single(_target.DependencyGroups[1].Dependencies); + [Fact] + public async Task StatisticsIncludeUnlistedPackages() + { + var now = DateTime.Now; - Assert.Equal("Dependency1", _target.DependencyGroups[0].Dependencies[0].PackageId); - Assert.Equal("(>= 1.0.0)", _target.DependencyGroups[0].Dependencies[0].VersionSpec); + _packages + .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) + .ReturnsAsync(new List + { + CreatePackage("1.0.0", downloads: 10, published: DateTime.Now.AddDays(-2)), + CreatePackage("2.0.0", listed: false, downloads: 5, published: now), + }); - Assert.Equal("Dependency3", _target.DependencyGroups[0].Dependencies[1].PackageId); - Assert.Equal("(>= 3.0.0)", _target.DependencyGroups[0].Dependencies[1].VersionSpec); + await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - Assert.Equal("Dependency2", _target.DependencyGroups[1].Dependencies[0].PackageId); - Assert.Equal("(>= 2.0.0)", _target.DependencyGroups[1].Dependencies[0].VersionSpec); - } + Assert.True(_target.Found); + Assert.Equal(15, _target.TotalDownloads); + Assert.Equal(now, _target.LastUpdated); + } - [Theory] - [InlineData(null, "All Frameworks")] - [InlineData("net5.0", ".NET 5.0")] - [InlineData("netstandard2.1", ".NET Standard 2.1")] - [InlineData("net10.0", ".NET 10.0")] - [InlineData("net4.8", ".NET Framework 4.8")] - public async Task PrettifiesTargetFramework(string targetFramework, string expectedResult) + [Fact] + public async Task RendersReadme() + { + using (var readmeStream = new MemoryStream()) { - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List - { - CreatePackage("1.0.0", dependencies: new[] - { - new PackageDependency - { - TargetFramework = targetFramework, - Id = "DependencyPackage", - VersionRange = "[1.0.0, )", - } - }) - }); - - await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - - Assert.True(_target.Found); - var group = Assert.Single(_target.DependencyGroups); - Assert.Equal(expectedResult, group.Name); - } + using (var streamWriter = new StreamWriter(readmeStream, leaveOpen: true)) + { + await streamWriter.WriteLineAsync("# My readme"); + await streamWriter.WriteLineAsync("Hello world!"); + await streamWriter.FlushAsync(); + } - [Fact] - public async Task StatisticsIncludeUnlistedPackages() - { - var now = DateTime.Now; + readmeStream.Position = 0; _packages .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) .ReturnsAsync(new List { - CreatePackage("1.0.0", downloads: 10, published: DateTime.Now.AddDays(-2)), - CreatePackage("2.0.0", listed: false, downloads: 5, published: now), + CreatePackage("1.0.0", hasReadme: true), }); + _content + .Setup(c => c.GetPackageReadmeStreamOrNullAsync( + "testpackage", + It.Is(v => v.OriginalVersion == "1.0.0"), + _cancellation)) + .ReturnsAsync(readmeStream); + await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - Assert.True(_target.Found); - Assert.Equal(15, _target.TotalDownloads); - Assert.Equal(now, _target.LastUpdated); + Assert.Equal( + "

My readme

\n

Hello world!

\n", + _target.Readme.Value); } + } - [Fact] - public async Task RendersReadme() - { - using (var readmeStream = new MemoryStream()) - { - using (var streamWriter = new StreamWriter(readmeStream, leaveOpen: true)) - { - await streamWriter.WriteLineAsync("# My readme"); - await streamWriter.WriteLineAsync("Hello world!"); - await streamWriter.FlushAsync(); - } - - readmeStream.Position = 0; - - _packages - .Setup(m => m.FindPackagesAsync("testpackage", _cancellation)) - .ReturnsAsync(new List - { - CreatePackage("1.0.0", hasReadme: true), - }); - - _content - .Setup(c => c.GetPackageReadmeStreamOrNullAsync( - "testpackage", - It.Is(v => v.OriginalVersion == "1.0.0"), - _cancellation)) - .ReturnsAsync(readmeStream); - - await _target.OnGetAsync("testpackage", "1.0.0", _cancellation); - - Assert.Equal( - "

My readme

\n

Hello world!

\n", - _target.Readme.Value); - } - } + private Package CreatePackage( + string version, + long downloads = 0, + bool hasReadme = false, + bool listed = true, + DateTime? published = null, + IEnumerable dependencies = null, + IEnumerable packageTypes = null) + { + published = published ?? DateTime.Now; + dependencies = dependencies ?? Array.Empty(); + packageTypes = packageTypes ?? Array.Empty(); - private Package CreatePackage( - string version, - long downloads = 0, - bool hasReadme = false, - bool listed = true, - DateTime? published = null, - IEnumerable dependencies = null, - IEnumerable packageTypes = null) + return new Package { - published = published ?? DateTime.Now; - dependencies = dependencies ?? Array.Empty(); - packageTypes = packageTypes ?? Array.Empty(); - - return new Package - { - Id = "testpackage", - Downloads = downloads, - HasReadme = hasReadme, - Listed = listed, - NormalizedVersionString = version, - Published = published.Value, - - Dependencies = dependencies.ToList(), - PackageTypes = packageTypes - .Select(name => new PackageType { Name = name }) - .ToList(), - }; - } + Id = "testpackage", + Downloads = downloads, + HasReadme = hasReadme, + Listed = listed, + NormalizedVersionString = version, + Published = published.Value, + + Dependencies = dependencies.ToList(), + PackageTypes = packageTypes + .Select(name => new PackageType { Name = name }) + .ToList(), + }; } -} +} \ No newline at end of file From 3d871a1118be14e1ec7407055535fe55e42c7a4d Mon Sep 17 00:00:00 2001 From: pieroviano Date: Sat, 17 Oct 2026 08:24:57 +0300 Subject: [PATCH 070/498] Plan nuget.org look and feel and account parity Accounts on by default with visible sign-in, optional SMTP for password recovery and email confirmation, account settings with 2FA, nuget.org's page design under BaGet's identity, package page tabs, search sort, avatars and contact owners. Puts first that enabling accounts by default makes keyless pushes fail on a default install. --- .../nuget-org-look-and-account-parity.md | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 docs/plans/nuget-org-look-and-account-parity.md diff --git a/docs/plans/nuget-org-look-and-account-parity.md b/docs/plans/nuget-org-look-and-account-parity.md new file mode 100644 index 000000000..4b7830145 --- /dev/null +++ b/docs/plans/nuget-org-look-and-account-parity.md @@ -0,0 +1,130 @@ +# nuget.org look and feel, accounts on by default, account and site parity + +Make BaGet look and behave as much like nuget.org as practical: visible sign-in, account settings with +2FA and password recovery, nuget.org's page design, package page tabs, search sort, avatars, contact +owners. + +## Blocking — resolve before coding + +| # | Item | Why it blocks | Status / how | +|---|---|---|---| +| **B0** | **Accounts on by default breaks keyless pushes.** With accounts enabled and `ApiKey` empty, `AccountAuthenticationService.AuthenticatePrincipalAsync` returns null for an absent key, by design, so ownership cannot be bypassed. A default install today accepts `dotnet nuget push` with no key. | Any CI pushing keyless to a default-configured BaGet gets **401 after upgrade**. | **Decided: proceed** (D1), with the mitigations in P1: startup warning, upload page message, docs note. Re-confirm before release. | +| B1 | Search sort per provider | `SearchRequest` (`src/BaGet.Core/Search/SearchRequest.cs:12-42`) has no sort. `DatabaseSearchService` can order; Azure Search needs sortable index fields; Azure Table cannot sort server-side. | Read `AzureSearchService` index definition (`src/BaGet.Azure/Search/`) and `TableSearchService`. If a provider cannot sort, it ignores `SortBy` and the UI hides the control (no in-memory sort of one page — that is wrong ordering). | +| B2 | Identity schema for 2FA / email confirmation | Needs `AspNetUsers.TwoFactorEnabled`, `EmailConfirmed`, and `AspNetUserTokens`. | `TwoFactorEnabled` present in all four `*ContextModelSnapshot.cs`. Confirm `AspNetUserTokens` likewise. Expected: **no migration**. | +| B3 | Test harness default | `tests/BaGet.Tests/Support/BaGetApplication.cs` does not set `Accounts:Enabled`; the test host reads `src/BaGet/appsettings.json`. Flipping it there changes ~250 tests. | Pin `{ "Accounts:Enabled", "false" }` in the harness's default settings **first**; tests needing accounts already override it. | +| B4 | Visual assets and licensing | nuget.org's gallery is `NuGet/NuGetGallery` (Apache-2.0); the NuGet logo is a Microsoft trademark. | Write BaGet's own CSS that reproduces the design; copy no logo or images; if any CSS is adapted, keep the Apache-2.0 notice. | +| B5 | Email in tests | No real SMTP in CI. | A capturing fake `IEmailSender` registered by the harness; assert on captured messages. | + +## Decisions + +| # | Decision | Consequence | +|---|---|---| +| D1 | Accounts **on by default**, registration allowed | Enabled in the shipped `appsettings.json`; the C# default `AccountsOptions.Enabled = false` (`src/BaGet.Core/Configuration/AccountsOptions.cs:19`) stays, so hosts embedding `AddBaGetAccounts` are unchanged. B0 applies to the BaGet host. | +| D2 | nuget.org design, **BaGet identity** | nuget.org layout, `#004880` header, typography, search hero, tabs, footer; BaGet name and logo. No NuGet logo. | +| D3 | **Optional SMTP** | `Email:Smtp` section. Unconfigured ⇒ every email-dependent feature (forgot password, email confirmation, change email, contact owners) is hidden, not broken; an admin CLI `baget account reset-password` covers recovery. | +| D4 | Scope: package page, account settings + 2FA, search/home/footer, avatars + contact | Six phases below. | + +## Phases + +Ordered by dependency. Each phase: tests red first, full suite green (baseline **892**), commit. + +### P1 — Accounts on, header links (D1) + +| File | Change | +|---|---| +| `tests/BaGet.Tests/Support/BaGetApplication.cs` (settings dictionary, ~line 66) | Add `{ "Accounts:Enabled", "false" }` — B3, done before the next row | +| `src/BaGet/appsettings.json:12` | Add `"Accounts": { "Enabled": true, "AllowRegistration": true }` | +| `src/BaGet/Program.cs` `Main` | Log a warning at startup when accounts are on and `ApiKey` is empty: keyless pushes are refused; create a user API key or set `ApiKey` | +| `src/BaGet.Web/Pages/Upload.cshtml` | CLI tabs state that `-k ` is required when accounts are on, linking to `~/account/apikeys` | +| `src/BaGet.Web/Pages/Shared/_Layout.cshtml:35-49` | Signed out: **Sign in** (and **Register** when `AllowRegistration`). Signed in: avatar dropdown — Account settings, API keys, Manage packages, Organizations, Upload package, Sign out (nuget.org's menu) | +| `docs/` | Upgrade note for B0 | + +### P2 — Optional email (D3) + +| File | Change | +|---|---| +| `src/BaGet.Core/Configuration/EmailOptions.cs` (new) | `Smtp { Host, Port, UserName, Password, EnableSsl, From }`; `IsConfigured => !string.IsNullOrEmpty(Smtp.Host) && !string.IsNullOrEmpty(Smtp.From)` | +| `src/BaGet.Identity/SmtpEmailSender.cs` (new) | `IEmailSender` over **MailKit** (MIT; Microsoft discourages `System.Net.Mail.SmtpClient` for new code). Version lever in `src/Directory.Build.props` | +| `AccountsServiceCollectionExtensions.AddBaGetAccounts` | Register the sender; `SignIn.RequireConfirmedEmail = email.IsConfigured` | +| `src/BaGet/Program.cs` | `account reset-password ` command, printing a one-time password; works without email | + +### P3 — Account settings and 2FA + +New pages in `src/BaGet.Identity/Pages/Account/`, all `AccountPageModel` with `RequiresSignIn` where applicable: + +| Page | Notes | +|---|---| +| `Settings` | Change password; change email (confirmation link when email configured); delete account | +| `ForgotPassword`, `ResetPassword`, `ConfirmEmail` | Shown only when `EmailOptions.IsConfigured`; ForgotPassword never reveals whether an account exists | +| `TwoFactor` | Enable authenticator (TOTP via Identity's `AuthenticatorTokenProvider`, already registered by `AddDefaultTokenProviders`); QR code via **QRCoder** (MIT) rendered server-side as SVG; 10 recovery codes; disable; reset | +| `LoginWith2fa`, `LoginWithRecoveryCode` | `Login.cshtml.cs` handles `SignInResult.RequiresTwoFactor` | + +Delete account **refuses while the user is the last owner of any package ID**, consistent with the +existing "last owner is kept" rule in `PackageOwnershipService.RemoveOwnerAsync`; the page lists those +IDs. API keys and organization memberships are removed with the user. + +### P4 — Look and feel (D2) + +| File | Change | +|---|---| +| `src/BaGet.Web/wwwroot/css/site.css` (429 lines) | Rework into nuget.org's design: `#004880` header, white nav, Segoe UI stack, result cards, tabs, sidebar, footer. Office UI Fabric icons stay | +| `_Layout.cshtml:19-79` | nuget.org header: brand left, Packages / Upload / Statistics / Documentation, account area right; search bar under the header except on home | +| `_Layout.cshtml` after `@RenderBody()` (line 82) | Footer: Documentation, GitHub, Terms of Use and Privacy (when configured), "Powered by BaGet" | +| `src/BaGet.Web/Pages/Index.cshtml` (267 lines) | No query ⇒ nuget.org home: hero search, totals (packages, versions, downloads) from `/stats` data. Results: nuget.org cards — icon, id, "by" owners, downloads, last updated, latest version, tags, description, verified and deprecated badges | +| Terms / Privacy | `Site:TermsOfUsePath` / `Site:PrivacyPolicyPath` point at operator Markdown rendered by a page; links hidden when unset. **No placeholder legal text is invented** | + +### P5 — Package page like nuget.org + +`src/BaGet.Web/Pages/Package.cshtml` (363 lines): + +| Area | Change | +|---|---| +| Lines 38-200 (expandable sections) | Horizontal tabs: **README · Frameworks · Dependencies · Used By · Versions · Release Notes**, keeping each section's existing content | +| Frameworks tab (new) | From `Package.TargetFrameworks` (`Package.cs:82`): declared frameworks grouped .NET / .NET Core / .NET Standard / .NET Framework, plus "computed" compatible frameworks from `NuGet.Frameworks` `CompatibilityProvider` against a fixed list of current TFMs, as nuget.org does. No schema change | +| Install snippets (lines 299-346) | Add Script & Interactive (`#r "nuget: Id, Ver"`), File-based apps (`#:package Id@Ver`), Cake (`#addin`/`#tool`), NUKE (`nuke :add-package`), Central Package Management | +| Sidebar (204-290) | nuget.org "About": last updated, project website, source repository, license, download package, download symbols when present, report package; Owners with avatars; **Contact owners** | + +### P6 — Search sort, avatars, contact owners + +| Item | Change | +|---|---| +| Sort | `SearchRequest.SortBy` (`Relevance`, `TotalDownloads`, `LastUpdated`), web UI only — the V3 search API has no sort parameter and stays protocol-identical. Providers per B1. Control in `Index.cshtml` filters (lines 16-66), hidden when the provider cannot sort | +| Avatars | Gravatar `https://www.gravatar.com/avatar/{md5(lower(email))}?s=…&d=retro`; organizations hash their name. `Site:UseGravatar` (default true) so a private feed can turn off the request to gravatar.com | +| Contact owners | `/packages/{id}/contact-owners`, signed-in only, hidden without email (D3). Mails user owners and the admins of owning organizations, `Reply-To` the sender, optional copy to self. One message per sender per package per 10 minutes | + +## Verification + +| # | Check | Expected | +|---|---|---| +| 1 | Full suite | 892 existing green after P1's harness pin, then each phase adds tests | +| 2 | Fresh install, `dotnet run` | Sign in / Register visible; register, sign in, avatar menu shows all six entries | +| 3 | Keyless `dotnet nuget push` on a fresh install | 401, startup warning logged (B0 documented behaviour) | +| 4 | Push with a user API key from `/account/apikeys` | 201, user becomes owner | +| 5 | Email unconfigured | Forgot password, change email, contact owners absent; `baget account reset-password` works | +| 6 | Email configured (fake sender in tests) | Confirmation on register, reset link valid once, expired token refused | +| 7 | 2FA | Enable with a TOTP code; sign-in demands a code; recovery code works once; disable | +| 8 | Delete account as last owner | Refused, IDs listed; after transferring ownership, succeeds and keys are gone | +| 9 | Package page | Six tabs; Frameworks shows declared and computed; every install snippet copies the right text | +| 10 | Sort | Database provider orders correctly; on Azure Table the control is hidden | +| 11 | Contact owners | Reaches every user owner and owning-org admin; second message inside 10 minutes refused | +| 12 | `Accounts:Enabled=false` | Whole site still works with no account links or pages (regression guard) | +| 13 | Visual check | Run the app and compare home, search, package and account pages with nuget.org side by side | + +## Risks + +| Risk | Likelihood | Handling | +|---|---|---| +| B0: keyless CI breaks on upgrade | **High** for default-config users | Startup warning, upload page text, docs; operator can set `Accounts:Enabled=false` | +| Email features half-working when SMTP is misconfigured | Medium | `IsConfigured` gate; send failures logged and shown as "could not send", never as success | +| Gravatar leaks a hash of the email (dictionary-reversible) to a third party | Medium | `Site:UseGravatar` switch, documented | +| Contact owners used for spam | Medium | Sign-in required, rate limit, sender's address in `Reply-To` | +| 2FA lockout | Low | Recovery codes; admin `reset-password` also clears 2FA | +| CSS rework regresses existing pages | Medium | Verification 13 on every page, including account and manage pages | +| Two new dependencies (MailKit, QRCoder) | Low | Both MIT, single version levers | + +## Out of scope + +- The NuGet logo or nuget.org wording (D2). +- Microsoft account sign-in: generic OpenID Connect already exists (`Accounts:OpenIdConnect:*`). +- Package ID prefix reservation, email notification preferences, package transfer requests. +- Invented Terms of Use or Privacy text. From 3b9bb9f76519d1cf7ee5beda72dead6279bdd0ac Mon Sep 17 00:00:00 2001 From: pieroviano Date: Sun, 18 Oct 2026 03:51:29 +0300 Subject: [PATCH 071/498] Offer the API key again after a rejected confirm or discard, and drop the stray semicolon after @namespace --- src/BaGet.Identity/Pages/_ViewImports.cshtml | 2 +- src/BaGet.Web/Pages/Upload.cshtml | 20 ++++++++++++++++++++ src/BaGet.Web/Pages/_ViewImports.cshtml | 2 +- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/BaGet.Identity/Pages/_ViewImports.cshtml b/src/BaGet.Identity/Pages/_ViewImports.cshtml index 85d5de36e..d2689af2b 100644 --- a/src/BaGet.Identity/Pages/_ViewImports.cshtml +++ b/src/BaGet.Identity/Pages/_ViewImports.cshtml @@ -1,4 +1,4 @@ @using BaGet.Core @using BaGet.Identity -@namespace BaGet.Identity.Pages; +@namespace BaGet.Identity.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/src/BaGet.Web/Pages/Upload.cshtml b/src/BaGet.Web/Pages/Upload.cshtml index 3e2d0131a..ddbac61f6 100644 --- a/src/BaGet.Web/Pages/Upload.cshtml +++ b/src/BaGet.Web/Pages/Upload.cshtml @@ -61,6 +61,26 @@ any time, with an API key.

} + else if (Model.RetryToken != null) + { +
+ +
+ + +
+
+ +
+ + +
+ } else if (staged != null) { @* Step two: what was staged, and nothing is published until it is confirmed. *@ diff --git a/src/BaGet.Web/Pages/_ViewImports.cshtml b/src/BaGet.Web/Pages/_ViewImports.cshtml index 7ce999104..311ed1e12 100644 --- a/src/BaGet.Web/Pages/_ViewImports.cshtml +++ b/src/BaGet.Web/Pages/_ViewImports.cshtml @@ -2,6 +2,6 @@ @using BaGet.Core @using Humanizer @using Microsoft.AspNetCore.Html -@namespace BaGet.Web; +@namespace BaGet.Web @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, BaGet.Web From bd409c7127220700d489c64adc484a530694baf6 Mon Sep 17 00:00:00 2001 From: pieroviano Date: Sun, 18 Oct 2026 03:56:05 +0300 Subject: [PATCH 072/498] Pin Accounts:Enabled=false in the integration harness defaults --- tests/BaGet.Tests/Support/BaGetApplication.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/BaGet.Tests/Support/BaGetApplication.cs b/tests/BaGet.Tests/Support/BaGetApplication.cs index ccd43eb43..bb940afd9 100644 --- a/tests/BaGet.Tests/Support/BaGetApplication.cs +++ b/tests/BaGet.Tests/Support/BaGetApplication.cs @@ -64,6 +64,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { "Storage:Type", "FileSystem" }, { "Storage:Path", storagePath }, { "Search:Type", "Database" }, + { "Accounts:Enabled", "false" }, { "Mirror:Enabled", _upstreamClient != null ? "true": "false" }, { "Mirror:PackageSource", "http://localhost/v3/index.json" }, }; From 0bc843bfc7e6df4f66647697e92ab92963770f31 Mon Sep 17 00:00:00 2001 From: pieroviano Date: Sun, 18 Oct 2026 03:58:37 +0300 Subject: [PATCH 073/498] P1: enable accounts by default, add header sign-in/register links and account menu, keyless-push guidance --- docs/configuration.md | 13 +- src/BaGet.Web/Pages/Shared/_Layout.cshtml | 26 ++- src/BaGet.Web/Pages/Upload.cshtml | 13 +- src/BaGet/Program.cs | 12 +- src/BaGet/appsettings.json | 9 + tests/BaGet.Tests/HeaderLinksTests.cs | 196 ++++++++++++++++++++++ 6 files changed, 258 insertions(+), 11 deletions(-) create mode 100644 tests/BaGet.Tests/HeaderLinksTests.cs diff --git a/docs/configuration.md b/docs/configuration.md index a5a08b030..63fcab187 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -157,8 +157,9 @@ older `Install-Package`, and PowerShellGet. It is on by default. To turn it off: ## Accounts, package owners and API keys -Accounts are **off** by default; with them off, only the global `ApiKey` authenticates, exactly as -before. Turn them on with: +Accounts are **on** in the shipped `appsettings.json` (the code default, for hosts embedding BaGet, is +off). With them off, only the global `ApiKey` authenticates. Set `Accounts:Enabled` to `false` to get +that behaviour back; otherwise configure them with: ```json { @@ -194,8 +195,14 @@ Who may change a package: * A package pushed before accounts were enabled has no owner, and only the global `ApiKey` may change it. Add owners from its manage page (`/packages/{id}/manage`) to hand it over. +!!! warning "Upgrade note: keyless pushes are refused" + Earlier releases shipped with accounts off, so a default install accepted `dotnet nuget push` with + no key. With accounts on and `ApiKey` empty, a push without a key now gets **401**; BaGet logs a + warning at startup. Fix CI by pushing with `-k `, using a user key from `/account/apikeys` (or + the global `ApiKey`), or restore the old behaviour with `"Accounts": { "Enabled": false }`. + !!! warning - Set `ApiKey`. Without it the server is open: anyone may push anything, and per-user keys restrict nothing. + With accounts off, set `ApiKey`. Without it the server is open: anyone may push anything. ### Organizations diff --git a/src/BaGet.Web/Pages/Shared/_Layout.cshtml b/src/BaGet.Web/Pages/Shared/_Layout.cshtml index 2ffc63111..65beba7a5 100644 --- a/src/BaGet.Web/Pages/Shared/_Layout.cshtml +++ b/src/BaGet.Web/Pages/Shared/_Layout.cshtml @@ -37,14 +37,30 @@ } diff --git a/src/BaGet.Web/Pages/Upload.cshtml b/src/BaGet.Web/Pages/Upload.cshtml index ddbac61f6..5f59269ed 100644 --- a/src/BaGet.Web/Pages/Upload.cshtml +++ b/src/BaGet.Web/Pages/Upload.cshtml @@ -266,6 +266,15 @@
You can push packages using the service index @serviceIndexUrl.
+ @if (Model.AccountsEnabled) + { +

+ Accounts are enabled, so a push must carry an API key: add + -k <your API key> to the command. Create one on the + API keys page. +

+ } +