Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to authenticate to an upstream mirror #114

Merged
merged 7 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PackageVersion Include="Microsoft.Azure.Cosmos" Version="3.38.1" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.3" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.3" />
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="8.0.3" />
Expand Down Expand Up @@ -45,4 +46,4 @@
<PackageVersion Include="Google.Cloud.Storage.V1" Version="4.9.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.3" />
</ItemGroup>
</Project>
</Project>
97 changes: 86 additions & 11 deletions docs/docs/configuration.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Configuration

You can modify BaGetter's configurations by editing the `appsettings.json` file.
Expand Down Expand Up @@ -42,18 +45,90 @@ caching to:

The following `Mirror` setting configures BaGetter to index packages from [nuget.org](https://nuget.org):

```json
{
...
<Tabs>
<TabItem value="None" label="No Authentication" default>
```json
{
...

"Mirror": {
"Enabled": true,
"PackageSource": "https://api.nuget.org/v3/index.json"
},

...
}
```
</TabItem>

<TabItem value="Basic" label="Basic Authentication">
For basic authentication, set `Type` to `Basic` and provide a `Username` and `Password`:

```json
{
...

"Mirror": {
"Enabled": true,
"PackageSource": "https://api.nuget.org/v3/index.json",
"Authentication": {
"Type": "Basic",
"Username": "username",
"Password": "password"
}
},

...
}
```
</TabItem>

<TabItem value="Bearer" label="Bearer Token">
For bearer authentication, set `Type` to `Bearer` and provide a `Token`:

```json
{
...

"Mirror": {
"Enabled": true,
"PackageSource": "https://api.nuget.org/v3/index.json",
"Authentication": {
"Type": "Bearer",
"Token": "your-token"
}
},

...
}
```
</TabItem>

<TabItem value="Custom" label="Custom Authentication">
With the custom authentication type, you can provide any key-value pairs which will be set as headers in the request:

```json
{
...

"Mirror": {
"Enabled": true,
"PackageSource": "https://api.nuget.org/v3/index.json",
"Authentication": {
"Type": "Custom",
"CustomHeaders": {
"My-Auth": "your-value",
"Other-Header": "value"
}
}
},

...
}
```
</TabItem>
</Tabs>

"Mirror": {
"Enabled": true,
"PackageSource": "https://api.nuget.org/v3/index.json"
},

...
}
```

:::info

Expand Down
16 changes: 16 additions & 0 deletions src/BaGetter.Core/Configuration/MirrorAuthenticationOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Collections.Generic;

namespace BaGetter.Core;

public class MirrorAuthenticationOptions
{
public MirrorAuthenticationType Type { get; set; } = MirrorAuthenticationType.None;

public string Username { get; set; }

public string Password { get; set; }

public string Token { get; set; }

public Dictionary<string, string> CustomHeaders { get; set; } = [];
}
9 changes: 9 additions & 0 deletions src/BaGetter.Core/Configuration/MirrorAuthenticationType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace BaGetter.Core;

public enum MirrorAuthenticationType
{
None,
Basic,
Bearer,
Custom
}
67 changes: 65 additions & 2 deletions src/BaGetter.Core/Configuration/MirrorOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,76 @@ public class MirrorOptions : IValidatableObject
[Range(0, int.MaxValue)]
public int PackageDownloadTimeoutSeconds { get; set; } = 600;

public MirrorAuthenticationOptions Authentication { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Enabled && PackageSource == null)
if (!Enabled)
{
yield break;
}

if (PackageSource == null)
{
yield return new ValidationResult(
$"The {nameof(PackageSource)} configuration is required if mirroring is enabled",
new[] { nameof(PackageSource) });
[nameof(PackageSource)]);
}

if (Authentication != null)
{
if (Legacy && Authentication.Type is not (MirrorAuthenticationType.None or MirrorAuthenticationType.Basic))
{
yield return new ValidationResult(
"Legacy v2 feeds only support basic authentication",
[nameof(Legacy), nameof(Authentication)]);
}

switch (Authentication.Type)
{
case MirrorAuthenticationType.Basic:
if (string.IsNullOrEmpty(Authentication.Username))
{
yield return new ValidationResult(
$"The {nameof(Authentication.Username)} configuration is required for basic authentication",
[nameof(Authentication.Username)]);
}

if (string.IsNullOrEmpty(Authentication.Password))
{
yield return new ValidationResult(
$"The {nameof(Authentication.Password)} configuration is required for basic authentication",
[nameof(Authentication.Password)]);
}
break;

case MirrorAuthenticationType.Bearer:
if (string.IsNullOrEmpty(Authentication.Token))
{
yield return new ValidationResult(
$"The {nameof(Authentication.Token)} configuration is required for bearer authentication",
[nameof(Authentication.Token)]);
}
break;

case MirrorAuthenticationType.Custom:
if (Authentication.CustomHeaders == null)
{
yield return new ValidationResult(
$"The {nameof(Authentication.CustomHeaders)} configuration is required for custom authentication",
[nameof(Authentication.CustomHeaders)]);
break;
}

if (Authentication.CustomHeaders.Count == 0)
{
yield return new ValidationResult(
$"The {nameof(Authentication.CustomHeaders)} configuration has no headers defined." +
$" Use \"{nameof(Authentication.Type)}\": \"{nameof(MirrorAuthenticationType.None)}\" instead if you intend you use no authentication.",
[nameof(Authentication.CustomHeaders)]);
}
break;
}
}
}
}
28 changes: 26 additions & 2 deletions src/BaGetter.Core/Extensions/DependencyInjectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using BaGetter.Core.Statistics;
using BaGetter.Protocol;
using Microsoft.Extensions.Configuration;
Expand Down Expand Up @@ -191,11 +193,33 @@ private static HttpClient HttpClientFactory(IServiceProvider provider)
private static NuGetClientFactory NuGetClientFactoryFactory(IServiceProvider provider)
{
var httpClient = provider.GetRequiredService<HttpClient>();
var options = provider.GetRequiredService<IOptions<MirrorOptions>>();
var options = provider.GetRequiredService<IOptions<MirrorOptions>>().Value;

if (options.Authentication is { } auth)
{
switch (auth.Type)
{
case MirrorAuthenticationType.Basic:
var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{auth.Username}:{auth.Password}"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
break;

case MirrorAuthenticationType.Bearer:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.Token);
break;

case MirrorAuthenticationType.Custom:
foreach (var (header, value) in auth.CustomHeaders)
{
httpClient.DefaultRequestHeaders.Add(header, value);
}
break;
}
}

return new NuGetClientFactory(
httpClient,
options.Value.PackageSource.ToString());
options.PackageSource.ToString());
}

private static IUpstreamClient UpstreamClientFactory(IServiceProvider provider)
Expand Down
24 changes: 22 additions & 2 deletions src/BaGetter.Core/Upstream/Clients/V2UpstreamClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class V2UpstreamClient : IUpstreamClient, IDisposable
private readonly SourceRepository _repository;
private readonly INuGetLogger _ngLogger;
private readonly ILogger _logger;
private static readonly char[] TagsSeparators = {';'};
private static readonly char[] TagsSeparators = { ';' };
private static readonly char[] AuthorsSeparators = new[] { ',', ';', '\t', '\n', '\r' };

public V2UpstreamClient(
Expand All @@ -45,7 +45,27 @@ public V2UpstreamClient(

_ngLogger = NullLogger.Instance;
_cache = new SourceCacheContext();
_repository = Repository.Factory.GetCoreV2(new PackageSource(options.Value.PackageSource.AbsoluteUri));
var packageSource = new PackageSource(options.Value.PackageSource.AbsoluteUri);
if (options.Value.Authentication is { } auth)
{
switch (auth.Type)
{
case MirrorAuthenticationType.None:
break;
case MirrorAuthenticationType.Basic:
packageSource.Credentials = new PackageSourceCredential(
packageSource.Source,
auth.Username,
auth.Password,
true,
null);
break;
default:
throw new NotSupportedException($"The authentication type {auth.Type} is not supported.");
Regenhardt marked this conversation as resolved.
Show resolved Hide resolved
}
}
_repository = Repository.Factory.GetCoreV2(packageSource);

}

public async Task<IReadOnlyList<NuGetVersion>> ListPackageVersionsAsync(string id, CancellationToken cancellationToken)
Expand Down
4 changes: 4 additions & 0 deletions tests/BaGetter.Core.Tests/BaGetter.Core.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@
<ProjectReference Include="..\..\src\BaGetter.Core\BaGetter.Core.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" />
</ItemGroup>

</Project>
Loading