using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using System.Net; using System.Security.Claims; using System.Security.Cryptography; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; public sealed class MdpPurchaseHandoffAuthenticationHandler( IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration) : AuthenticationHandler(options, logger, encoder) { public const string SchemeName = "MdpPurchaseHandoff"; protected override Task HandleAuthenticateAsync() { var remoteAddress = Context.Connection.RemoteIpAddress; var loopback = remoteAddress is not null && IPAddress.IsLoopback(remoteAddress.IsIPv4MappedToIPv6 ? remoteAddress.MapToIPv4() : remoteAddress); if ((!Request.IsHttps && !loopback) || !HasValidToken()) return Task.FromResult(AuthenticateResult.Fail("Invalid purchase handoff credential.")); var principal = new ClaimsPrincipal(new ClaimsIdentity(Scheme.Name)); return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name))); } private bool HasValidToken() { var key = PurchaseDispatchProof.ReadKey(configuration[PurchaseDispatchProof.CredentialSetting]); if (key is null || !Request.Headers.TryGetValue(PurchaseDispatchProof.DigestHeader, out var digest) || digest.Count != 1 || digest[0]?.Length != 64 || !Request.Headers.TryGetValue(PurchaseDispatchProof.ProofHeader, out var proof) || proof.Count != 1) return false; var submitted = PurchaseDispatchProof.ReadKey(proof[0]); return submitted is not null && CryptographicOperations.FixedTimeEquals(submitted, PurchaseDispatchProof.Sign(key, Request.Method, (Request.PathBase + Request.Path).Value!, digest[0]!)); } }