| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- using System.Net;
- using System.Security.Claims;
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- using Microsoft.Extensions.Configuration;
- using Microsoft.IdentityModel.JsonWebTokens;
- using Microsoft.IdentityModel.Tokens;
- using Xunit;
- namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
- public sealed class MdpIngestAuthenticationTests
- {
- private const string Issuer = "https://issuer.example.test";
- private const string Audience = "mdp-ingress";
- private const string OAuth = "MdpUnifiedIngress:ExternalIdentity:OAuth2:";
- private const string Mtls = "MdpUnifiedIngress:ExternalIdentity:Mtls:";
- [Fact]
- public async Task OAuth2_RequiresVerifiedIssuerAudienceSignatureApplicationAndScope()
- {
- using var issuerRsa = RSA.Create(2048);
- using var otherRsa = RSA.Create(2048);
- var key = new RsaSecurityKey(issuerRsa) { KeyId = "documented-key" };
- var otherKey = new RsaSecurityKey(otherRsa) { KeyId = key.KeyId };
- using var metadata = new HttpClient(new Metadata(issuerRsa.ExportParameters(false)));
- var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
- {
- [OAuth + "MetadataAddress"] = Issuer + "/.well-known/openid-configuration",
- [OAuth + "Issuer"] = Issuer,
- [OAuth + "Audience"] = Audience,
- [OAuth + "AppOnlyClaim"] = "token_kind",
- [OAuth + "AppOnlyValue"] = "app",
- [OAuth + "ReadScope"] = "batch.read",
- [OAuth + "WriteScope"] = "batch.write",
- [OAuth + "Clients:0:Enabled"] = "true",
- [OAuth + "Clients:0:Identity"] = "factory-client",
- [OAuth + "Clients:0:GrantReference"] = "factory-source",
- [OAuth + "Clients:0:TenantId"] = "101",
- [OAuth + "Clients:0:UserId"] = "102"
- }).Build();
- var service = new MdpIngestExternalIdentities(configuration, new ClientFactory(metadata));
- var caller = await Resolve(Token());
- Assert.NotNull(caller);
- Assert.Equal(101, caller.TenantId);
- Assert.Equal(102, caller.UserId);
- var expectedHash = Convert.ToHexString(SHA256.HashData("mdp-external\0oauth2\0factory-source"u8)).ToLowerInvariant();
- Assert.Equal(expectedHash, caller.AccessKeyHash);
- Assert.Null(await Resolve(Token(), read: true));
- Assert.NotNull(await Resolve(Token(scope: "batch.read"), read: true));
- Assert.Null(await Resolve(Token(audience: "another-api")));
- Assert.Null(await Resolve(Token(issuer: Issuer + "/other")));
- Assert.Null(await Resolve(Token(app: "user")));
- Assert.Null(await Resolve(Token(client: "other-client")));
- Assert.Null(await Resolve(Token(signingKey: otherKey)));
- Assert.Null(await Resolve(Token(expired: true)));
- configuration[OAuth + "Clients:0:Enabled"] = "false";
- Assert.Null(await Resolve(Token()));
- Task<MdpIngestIdentity?> Resolve(string token, bool read = false) =>
- service.ResolveBearerAsync("Bearer " + token, read, CancellationToken.None);
- string Token(string issuer = Issuer, string audience = Audience, string app = "app", string client = "factory-client",
- string scope = "batch.write", RsaSecurityKey? signingKey = null, bool expired = false)
- {
- var now = DateTime.UtcNow;
- return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
- {
- Issuer = issuer, Audience = audience,
- IssuedAt = now.AddMinutes(-5), NotBefore = now.AddMinutes(-5), Expires = now.AddMinutes(expired ? -2 : 2),
- Subject = new ClaimsIdentity([new Claim("token_kind", app), new Claim("client_id", client), new Claim("scope", scope)]),
- SigningCredentials = new SigningCredentials(signingKey ?? key, SecurityAlgorithms.RsaSha256)
- });
- }
- }
- [Fact]
- public void Mtls_RejectsAnExplicitlyMappedCertificateWithoutATrustedChain()
- {
- using var rsa = RSA.Create(2048);
- var request = new CertificateRequest("CN=isolated-factory", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
- request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.2") }, true));
- using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddMinutes(1));
- var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
- {
- [Mtls + "Clients:0:Enabled"] = "true",
- [Mtls + "Clients:0:Identity"] = certificate.GetCertHashString(HashAlgorithmName.SHA256),
- [Mtls + "Clients:0:GrantReference"] = "factory-source",
- [Mtls + "Clients:0:TenantId"] = "101",
- [Mtls + "Clients:0:UserId"] = "102"
- }).Build();
- using var http = new HttpClient();
- var service = new MdpIngestExternalIdentities(configuration, new ClientFactory(http));
- Assert.Null(service.ResolveCertificate(certificate));
- }
- private sealed class ClientFactory(HttpClient client) : IHttpClientFactory
- {
- public HttpClient CreateClient(string name) => client;
- }
- private sealed class Metadata(RSAParameters publicKey) : HttpMessageHandler
- {
- protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
- {
- var document = request.RequestUri!.AbsolutePath switch
- {
- "/.well-known/openid-configuration" => JsonSerializer.Serialize(new
- {
- issuer = Issuer, jwks_uri = Issuer + "/keys"
- }),
- "/keys" => JsonSerializer.Serialize(new
- {
- keys = new[]
- {
- new
- {
- kty = "RSA", kid = "documented-key", use = "sig", alg = "RS256",
- n = Base64UrlEncoder.Encode(publicKey.Modulus), e = Base64UrlEncoder.Encode(publicKey.Exponent)
- }
- }
- }),
- _ => throw new InvalidOperationException()
- };
- return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(document) });
- }
- }
- }
|