wabbajack/Wabbajack.Server/ApiKeyAuthorizationHandler.cs

169 lines
5.9 KiB
C#
Raw Normal View History

2022-03-31 22:55:33 +00:00
using System.Security.Claims;
2020-05-09 22:16:16 +00:00
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
2022-03-31 22:55:33 +00:00
using Microsoft.Extensions.Caching.Memory;
2020-05-09 22:16:16 +00:00
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2021-09-27 12:42:46 +00:00
using Wabbajack.DTOs.JsonConverters;
2022-03-31 22:55:33 +00:00
using Wabbajack.Networking.GitHub;
using Wabbajack.Networking.GitHub.DTOs;
2021-11-27 18:31:35 +00:00
using Wabbajack.Server.DataModels;
2022-02-09 18:24:31 +00:00
using Wabbajack.Server.DTOs;
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
namespace Wabbajack.BuildServer;
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
public const string DefaultScheme = "API Key";
public string AuthenticationType = DefaultScheme;
public string Scheme => DefaultScheme;
}
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
{
private const string ProblemDetailsContentType = "application/problem+json";
public const string ApiKeyHeaderName = "X-Api-Key";
private readonly DTOSerializer _dtos;
private readonly AppSettings _settings;
2021-11-27 18:31:35 +00:00
private readonly AuthorKeys _authorKeys;
2022-02-09 18:24:31 +00:00
private readonly Metrics _metricsStore;
private readonly TarLog _tarLog;
2022-03-31 22:55:33 +00:00
private readonly Client _githubClient;
private readonly MemoryCache _githubCache;
2021-10-23 16:51:17 +00:00
public ApiKeyAuthenticationHandler(
IOptionsMonitor<ApiKeyAuthenticationOptions> options,
2021-11-27 18:31:35 +00:00
AuthorKeys authorKeys,
2022-03-31 22:55:33 +00:00
Client githubClient,
2021-10-23 16:51:17 +00:00
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
DTOSerializer dtos,
2022-02-09 18:24:31 +00:00
Metrics metricsStore,
TarLog tarlog,
2021-11-27 18:31:35 +00:00
AppSettings settings) : base(options, logger, encoder, clock)
2020-05-09 22:16:16 +00:00
{
2022-02-09 18:24:31 +00:00
_tarLog = tarlog;
_metricsStore = metricsStore;
2021-10-23 16:51:17 +00:00
_dtos = dtos;
2021-11-27 18:31:35 +00:00
_authorKeys = authorKeys;
2021-10-23 16:51:17 +00:00
_settings = settings;
2022-03-31 22:55:33 +00:00
_githubClient = githubClient;
_githubCache = new MemoryCache(new MemoryCacheOptions());
2020-05-09 22:16:16 +00:00
}
2021-10-23 16:51:17 +00:00
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
var metricsKey = Request.Headers[_settings.MetricsKeyHeader].FirstOrDefault();
// Never needed this, disabled for now
//await LogRequest(metricsKey);
if (metricsKey != default)
2020-05-09 22:16:16 +00:00
{
2022-02-09 18:24:31 +00:00
if (await _tarLog.Contains(metricsKey))
2020-06-14 13:13:29 +00:00
{
2022-02-09 18:38:11 +00:00
await _metricsStore.Ingest(new Metric
2020-06-14 13:13:29 +00:00
{
2022-02-09 18:24:31 +00:00
Subject = metricsKey,
Action = "tarlog",
2021-10-23 16:51:17 +00:00
MetricsKey = metricsKey,
2022-03-31 16:22:38 +00:00
UserAgent = Request.Headers.UserAgent,
2022-03-31 22:55:33 +00:00
Ip = Request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? ""
2021-10-23 16:51:17 +00:00
});
2022-02-09 18:41:11 +00:00
await Task.Delay(TimeSpan.FromSeconds(20));
2022-02-09 18:38:11 +00:00
throw new Exception("Error, lipsum timeout of the cross distant cloud.");
2020-06-14 13:13:29 +00:00
}
2021-10-23 16:51:17 +00:00
}
2020-06-14 13:13:29 +00:00
2021-10-23 16:51:17 +00:00
var authorKey = Request.Headers[ApiKeyHeaderName].FirstOrDefault();
2021-02-17 05:46:05 +00:00
2021-10-23 16:51:17 +00:00
if (authorKey == null)
Request.Cookies.TryGetValue(ApiKeyHeaderName, out authorKey);
2021-02-17 05:46:05 +00:00
2021-10-23 16:51:17 +00:00
if (authorKey == null && metricsKey == null) return AuthenticateResult.NoResult();
2021-11-27 18:31:35 +00:00
2021-10-23 16:51:17 +00:00
if (authorKey != null)
{
2021-11-27 18:31:35 +00:00
var owner = await _authorKeys.AuthorForKey(authorKey);
2021-10-23 16:51:17 +00:00
if (owner == null)
2022-03-31 22:55:33 +00:00
{
var ghUser = await GetGithubUserInfo(authorKey);
if (ghUser == null)
return AuthenticateResult.Fail("Invalid author key");
owner = "github/" + ghUser.Login;
}
2020-06-16 22:21:01 +00:00
if (await _tarLog.Contains(owner))
return AuthenticateResult.Fail("Banned author key");
2021-10-23 16:51:17 +00:00
var claims = new List<Claim> {new(ClaimTypes.Name, owner)};
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
claims.Add(new Claim(ClaimTypes.Role, "Author"));
claims.Add(new Claim(ClaimTypes.Role, "User"));
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
var identity = new ClaimsIdentity(claims, Options.AuthenticationType);
var identities = new List<ClaimsIdentity> {identity};
var principal = new ClaimsPrincipal(identities);
var ticket = new AuthenticationTicket(principal, Options.Scheme);
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
return AuthenticateResult.Success(ticket);
}
2020-05-09 22:16:16 +00:00
2021-11-27 18:31:35 +00:00
if (!string.IsNullOrWhiteSpace(metricsKey))
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
var claims = new List<Claim> {new(ClaimTypes.Role, "User")};
var identity = new ClaimsIdentity(claims, Options.AuthenticationType);
var identities = new List<ClaimsIdentity> {identity};
var principal = new ClaimsPrincipal(identities);
var ticket = new AuthenticationTicket(principal, Options.Scheme);
return AuthenticateResult.Success(ticket);
2020-05-09 22:16:16 +00:00
}
2021-11-27 18:31:35 +00:00
return AuthenticateResult.NoResult();
2020-05-09 22:16:16 +00:00
}
2022-03-31 22:55:33 +00:00
protected async Task<UserInfo?> GetGithubUserInfo(string authToken)
{
if (_githubCache.TryGetValue<UserInfo>(authToken, out var value)) return value;
var info = await _githubClient.GetUserInfoFromPAT(authToken);
if (info != null)
_githubCache.Set(authToken, info,
new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromHours(6)));
return info;
}
2021-10-23 16:51:17 +00:00
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
2020-05-09 22:16:16 +00:00
{
2021-10-23 16:51:17 +00:00
Response.StatusCode = 401;
Response.ContentType = ProblemDetailsContentType;
await Response.WriteAsync("Unauthorized");
}
2020-05-09 22:16:16 +00:00
2021-10-23 16:51:17 +00:00
protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.StatusCode = 403;
Response.ContentType = ProblemDetailsContentType;
await Response.WriteAsync("forbidden");
2020-05-09 22:16:16 +00:00
}
}
2021-10-23 16:51:17 +00:00
public static class ApiKeyAuthorizationHandlerExtensions
{
public static AuthenticationBuilder AddApiKeySupport(this AuthenticationBuilder authenticationBuilder,
Action<ApiKeyAuthenticationOptions> options)
{
return authenticationBuilder.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(
ApiKeyAuthenticationOptions.DefaultScheme, options);
}
}