diff --git a/src/Sign.Cli/AzureKeyVaultCommand.cs b/src/Sign.Cli/AzureKeyVaultCommand.cs index 25e9ee82..fdf796c3 100644 --- a/src/Sign.Cli/AzureKeyVaultCommand.cs +++ b/src/Sign.Cli/AzureKeyVaultCommand.cs @@ -6,7 +6,7 @@ using System.CommandLine.Parsing; using Azure.Core; using Azure.Security.KeyVault.Certificates; -using Azure.Security.KeyVault.Keys.Cryptography; +using Azure.Security.KeyVault.Keys; using Microsoft.Extensions.Azure; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -18,6 +18,7 @@ namespace Sign.Cli internal sealed class AzureKeyVaultCommand : Command { internal Option UrlOption { get; } + internal Option CertificateVersionOption { get; } internal Option CertificateOption { get; } internal AzureCredentialOptions AzureCredentialOptions { get; } = new(); @@ -40,6 +41,11 @@ internal AzureKeyVaultCommand(CodeCommand codeCommand, IServiceProviderFactory s Description = AzureKeyVaultResources.CertificateOptionDescription, Required = true }; + CertificateVersionOption = new Option("--azure-key-vault-certificate-version", "-kvcv") + { + Description = AzureKeyVaultResources.CertificateVersionOptionDescription, + CustomParser = ParseCertificateVersion + }; FilesArgument = new Argument?>("file(s)") { Description = Resources.FilesArgumentDescription, @@ -48,6 +54,7 @@ internal AzureKeyVaultCommand(CodeCommand codeCommand, IServiceProviderFactory s Options.Add(UrlOption); Options.Add(CertificateOption); + Options.Add(CertificateVersionOption); AzureCredentialOptions.AddOptionsToCommand(this); Arguments.Add(FilesArgument); @@ -82,8 +89,9 @@ internal AzureKeyVaultCommand(CodeCommand codeCommand, IServiceProviderFactory s // the null-forgiving operator (!) to simplify the code. Uri url = parseResult.GetValue(UrlOption)!; string certificateId = parseResult.GetValue(CertificateOption)!; + string? certificateVersion = parseResult.GetValue(CertificateVersionOption); - // Construct the URI for the certificate and the key from user parameters. We'll validate those with the SDK + // Construct the URI for the certificate from user parameters. We'll validate it with the SDK. var certUri = new Uri($"{url.Scheme}://{url.Authority}/certificates/{certificateId}"); if (!KeyVaultCertificateIdentifier.TryCreate(certUri, out var certId)) @@ -93,15 +101,12 @@ internal AzureKeyVaultCommand(CodeCommand codeCommand, IServiceProviderFactory s return Task.FromResult(ExitCode.InvalidOptions); } - // The key uri is similar and the key name matches the certificate name - var keyUri = new Uri($"{url.Scheme}://{url.Authority}/keys/{certificateId}"); - serviceProviderFactory.AddServices(services => { services.AddAzureClients(builder => { builder.AddCertificateClient(certId.VaultUri); - builder.AddCryptographyClient(keyUri); + builder.AddKeyClient(certId.VaultUri); builder.UseCredential(credential); builder.ConfigureDefaults(options => options.Retry.Mode = RetryMode.Exponential); }); @@ -110,8 +115,9 @@ internal AzureKeyVaultCommand(CodeCommand codeCommand, IServiceProviderFactory s { return new KeyVaultService( serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), + serviceProvider.GetRequiredService(), certId.Name, + certificateVersion, serviceProvider.GetRequiredService>()); }); }); @@ -135,5 +141,17 @@ internal AzureKeyVaultCommand(CodeCommand codeCommand, IServiceProviderFactory s return uri; } + + private static string? ParseCertificateVersion(ArgumentResult result) + { + if (result.Tokens.Count != 1 || result.Tokens[0].Value.Length != 32) + { + result.AddError(AzureKeyVaultResources.InvalidCertificateVersionValue); + + return null; + } + + return result.Tokens[0].Value; + } } } diff --git a/src/Sign.Cli/AzureKeyVaultResources.Designer.cs b/src/Sign.Cli/AzureKeyVaultResources.Designer.cs index 531aa76e..696f7e14 100644 --- a/src/Sign.Cli/AzureKeyVaultResources.Designer.cs +++ b/src/Sign.Cli/AzureKeyVaultResources.Designer.cs @@ -69,6 +69,12 @@ internal static string CertificateOptionDescription { } } + internal static string CertificateVersionOptionDescription { + get { + return ResourceManager.GetString("CertificateVersionOptionDescription", resourceCulture); + } + } + /// /// Looks up a localized string similar to ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation.. /// @@ -95,6 +101,15 @@ internal static string InvalidKeyVaultUrl { return ResourceManager.GetString("InvalidKeyVaultUrl", resourceCulture); } } + + /// + /// Looks up a localized string similar to Certificate version must be a 32-character string.. + /// + internal static string InvalidCertificateVersionValue { + get { + return ResourceManager.GetString("InvalidCertificateVersionValue", resourceCulture); + } + } /// /// Looks up a localized string similar to URL must be an absolute HTTPS URL to an Azure Key Vault.. diff --git a/src/Sign.Cli/AzureKeyVaultResources.resx b/src/Sign.Cli/AzureKeyVaultResources.resx index 6f08ccd8..6546be2f 100644 --- a/src/Sign.Cli/AzureKeyVaultResources.resx +++ b/src/Sign.Cli/AzureKeyVaultResources.resx @@ -120,6 +120,9 @@ Name of the certificate in Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. @@ -129,6 +132,9 @@ URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) + + Certificate version must be a 32-character string. + URL must be an absolute HTTPS URL to an Azure Key Vault. diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.cs.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.cs.xlf index a70d7d2c..8b4fa123 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.cs.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.cs.xlf @@ -7,6 +7,11 @@ Název certifikátu v Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. Podepisování ClickOnce prostřednictvím starší verze alternativního řešení .clickonce ZIP se už nepodporuje. Projděte si dokumentaci. @@ -17,6 +22,11 @@ Použijte Azure Key Vault. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) Adresa URL musí obsahovat pouze protokol a hostitele. (např. https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.de.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.de.xlf index 7d343694..8fe8dbff 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.de.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.de.xlf @@ -7,6 +7,11 @@ Name des Zertifikats in Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. Die ClickOnce-Signierung über die Legacy-.clickonce-ZIP-Problemumgehung wird nicht mehr unterstützt. Siehe Dokumentation. @@ -17,6 +22,11 @@ Verwenden Sie Azure Key Vault. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) Die URL darf nur das Protokoll und den Host enthalten. (Beispiel: https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.es.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.es.xlf index 3c9608ec..122bf7ae 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.es.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.es.xlf @@ -7,6 +7,11 @@ Nombre del certificado en Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. Ya no se admite la firma ClickOnce a través de la solución zip heredada .clickonce. Consulte la documentación. @@ -17,6 +22,11 @@ Use Azure Key Vault. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) La dirección URL solo debe contener el protocolo y el host. (por ejemplo: https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.fr.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.fr.xlf index e121c215..822ba897 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.fr.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.fr.xlf @@ -7,6 +7,11 @@ Nom du certificat dans Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. La signature ClickOnce via la solution de contournement zip .clickonce héritée n’est plus prise en charge. Consulter la documentation. @@ -17,6 +22,11 @@ Utilisez Azure Key Vault. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) L’URL doit contenir uniquement le protocole et l’hôte. (par exemple : https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.it.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.it.xlf index 789b87dc..3f989cc4 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.it.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.it.xlf @@ -7,6 +7,11 @@ Nome del certificato in Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. La firma ClickOnce tramite la soluzione alternativa legacy .clickonce ZIP non è più supportata. Vedere la documentazione. @@ -17,6 +22,11 @@ Usare Azure Key Vault. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) L'URL deve contenere solo il protocollo e l'host. (ad esempio: https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.ja.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.ja.xlf index eedd4e97..5f04ffd6 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.ja.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.ja.xlf @@ -7,6 +7,11 @@ Azure Key Vault 内の証明書の名前。 + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. 従来の .clickonce ZIP 回避策による ClickOnce 署名はサポートされなくなりました。ドキュメントを参照してください。 @@ -17,6 +22,11 @@ Azure Key Vault を使用してください。 + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) URL にはプロトコルとホストのみを含めなければなりません。(例: https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.ko.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.ko.xlf index 98ad3687..a1f69461 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.ko.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.ko.xlf @@ -7,6 +7,11 @@ Azure Key Vault의 인증서 이름입니다. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. 레거시 .clickonce ZIP 해결 방법을 통한 ClickOnce 서명은 더 이상 지원되지 않습니다. 설명서를 참조하세요. @@ -17,6 +22,11 @@ Azure Key Vault를 사용합니다. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) URL은 프로토콜과 호스트만 포함해야 합니다. (예: https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.pl.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.pl.xlf index 77bdf2d8..418d6a93 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.pl.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.pl.xlf @@ -7,6 +7,11 @@ Nazwa certyfikatu w usłudze Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. Podpisywanie clickOnce za pośrednictwem starszego obejścia .clickonce ZIP nie jest już obsługiwane. Zobacz dokumentację. @@ -17,6 +22,11 @@ Użyj usługi Azure Key Vault. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) Adres URL może zawierać tylko protokół i hosta. (np. https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.pt-BR.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.pt-BR.xlf index db0e2ffc..86efc305 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.pt-BR.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.pt-BR.xlf @@ -7,6 +7,11 @@ Nome do certificado no Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. Não há mais suporte para a assinatura do ClickOnce por meio da solução alternativa .clickonce ZIP herdada. Consulte a documentação. @@ -17,6 +22,11 @@ Use o Azure Key Vault. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) A URL deve conter somente o protocolo e o host. (por exemplo: https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.ru.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.ru.xlf index 9268dbfd..d5f825d1 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.ru.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.ru.xlf @@ -7,6 +7,11 @@ Имя сертификата в Azure Key Vault. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. Подписание ClickOnce с помощью устаревшего обходного пути .clickonce ZIP больше не поддерживается. См. документацию. @@ -17,6 +22,11 @@ Использование Azure Key Vault. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) URL-адрес должен содержать только протокол и хост. (например, https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.tr.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.tr.xlf index a97f35d3..bc25c667 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.tr.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.tr.xlf @@ -7,6 +7,11 @@ Azure Key Vault’taki sertifikanın adı. + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. Eski .clickonce ZIP geçici çözümü aracılığıyla ClickOnce imzalama işlemi artık desteklenmiyor. Belgelere bakın. @@ -17,6 +22,11 @@ Azure Key Vault’u kullanın. + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) URL yalnızca protokolü ve ana bilgisayarı içermeli. (ör. https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.zh-Hans.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.zh-Hans.xlf index fb048ffd..0b4247ff 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.zh-Hans.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.zh-Hans.xlf @@ -7,6 +7,11 @@ Azure Key Vault 中的证书名称。 + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. 不再支持通过旧版 .clickonce ZIP 解决方法进行 ClickOnce 签名。参阅文档。 @@ -17,6 +22,11 @@ 使用 Azure Key Vault。 + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) URL 只能包含协议和主机。(,例如: https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.Cli/xlf/AzureKeyVaultResources.zh-Hant.xlf b/src/Sign.Cli/xlf/AzureKeyVaultResources.zh-Hant.xlf index 223505aa..b0c9038b 100644 --- a/src/Sign.Cli/xlf/AzureKeyVaultResources.zh-Hant.xlf +++ b/src/Sign.Cli/xlf/AzureKeyVaultResources.zh-Hant.xlf @@ -7,6 +7,11 @@ Azure Key Vault 中的憑證名稱。 + + Optional version of the Azure Key Vault certificate. + Optional version of the Azure Key Vault certificate. + + ClickOnce signing via the legacy .clickonce ZIP workaround is no longer supported. See documentation. 已不再支援透過舊版 .clickonce ZIP 因應措施進行 ClickOnce 簽署。請參閱文件。 @@ -17,6 +22,11 @@ 使用 Azure Key Vault。 + + Certificate version must be a 32-character string. + Certificate version must be a 32-character string. + + URL must only contain the protocol and host. (e.g.: https://<vault-name>.vault.azure.net/) URL 只能包含通訊協定和主機。(例如: https://<vault-name>.vault.azure.net/) diff --git a/src/Sign.SignatureProviders.KeyVault/KeyVaultService.cs b/src/Sign.SignatureProviders.KeyVault/KeyVaultService.cs index 6e418c31..542e2285 100644 --- a/src/Sign.SignatureProviders.KeyVault/KeyVaultService.cs +++ b/src/Sign.SignatureProviders.KeyVault/KeyVaultService.cs @@ -7,6 +7,7 @@ using System.Security.Cryptography.X509Certificates; using Azure; using Azure.Security.KeyVault.Certificates; +using Azure.Security.KeyVault.Keys; using Azure.Security.KeyVault.Keys.Cryptography; using Microsoft.Extensions.Logging; using Sign.Core; @@ -16,61 +17,106 @@ namespace Sign.SignatureProviders.KeyVault internal sealed class KeyVaultService : ISignatureAlgorithmProvider, ICertificateProvider, IDisposable { private readonly CertificateClient _certificateClient; - private readonly CryptographyClient _cryptographyClient; + private readonly string? _certificateVersion; private readonly string _certificateName; + private readonly KeyClient _keyClient; private readonly ILogger _logger; private readonly SemaphoreSlim _mutex = new(1); - private X509Certificate2? _certificate; + private CertificateInfo? _certificateInfo; + private CryptographyClient? _cryptographyClient; internal KeyVaultService( CertificateClient certificateClient, - CryptographyClient cryptographyClient, + KeyClient keyClient, string certificateName, + string? certificateVersion, ILogger logger) { ArgumentNullException.ThrowIfNull(certificateClient, nameof(certificateClient)); - ArgumentNullException.ThrowIfNull(cryptographyClient, nameof(cryptographyClient)); + ArgumentNullException.ThrowIfNull(keyClient, nameof(keyClient)); ArgumentException.ThrowIfNullOrEmpty(certificateName, nameof(certificateName)); ArgumentNullException.ThrowIfNull(logger, nameof(logger)); _certificateName = certificateName; + _certificateVersion = certificateVersion; _certificateClient = certificateClient; - _cryptographyClient = cryptographyClient; + _keyClient = keyClient; _logger = logger; } public void Dispose() { _mutex.Dispose(); - _certificate?.Dispose(); + _certificateInfo?.Certificate.Dispose(); GC.SuppressFinalize(this); } public async Task GetCertificateAsync(CancellationToken cancellationToken) { - if (_certificate is not null) + CertificateInfo certificateInfo = await GetCertificateInfoAsync(cancellationToken); + + return new X509Certificate2(certificateInfo.Certificate); // clone it as it's disposable + } + + public async Task GetRsaAsync(CancellationToken cancellationToken) + { + CertificateInfo certificateInfo = await GetCertificateInfoAsync(cancellationToken); + + await _mutex.WaitAsync(cancellationToken); + + try + { + _cryptographyClient ??= _keyClient.GetCryptographyClient( + certificateInfo.KeyIdentifier.Name, + certificateInfo.KeyIdentifier.Version); + } + finally + { + _mutex.Release(); + } + + RSAKeyVault rsaKeyVault = await _cryptographyClient.CreateRSAAsync(cancellationToken); + RSA rsaPublicKey = certificateInfo.Certificate.GetRSAPublicKey()!; + return new RSAKeyVaultWrapper(rsaKeyVault, rsaPublicKey); + } + + private async Task GetCertificateInfoAsync(CancellationToken cancellationToken) + { + if (_certificateInfo is not null) { - return new X509Certificate2(_certificate); // clone it as it's disposable + return _certificateInfo; } await _mutex.WaitAsync(cancellationToken); try { - if (_certificate is null) + if (_certificateInfo is null) { Stopwatch stopwatch = Stopwatch.StartNew(); _logger.LogTrace(Resources.FetchingCertificate); - Response response = await _certificateClient.GetCertificateAsync(_certificateName, cancellationToken); + KeyVaultCertificate certificate; + if (string.IsNullOrEmpty(_certificateVersion)) + { + Response response = await _certificateClient.GetCertificateAsync(_certificateName, cancellationToken); + certificate = response.Value; + } + else + { + Response response = + await _certificateClient.GetCertificateVersionAsync(_certificateName, _certificateVersion, cancellationToken); + certificate = response.Value; + } - _logger.LogTrace(Resources.FetchedCertificate, stopwatch.Elapsed.TotalMilliseconds); + KeyVaultKeyIdentifier keyIdentifier = GetKeyIdentifier(certificate); + X509Certificate2 x509Certificate = new(certificate.Cer); - _certificate = new X509Certificate2(response.Value.Cer); + _logger.LogTrace(Resources.FetchedCertificate, stopwatch.Elapsed.TotalMilliseconds); + _logger.LogTrace($"{Resources.CertificateDetails}{Environment.NewLine}{x509Certificate.ToString(verbose: true)}"); - //print the certificate info - _logger.LogTrace($"{Resources.CertificateDetails}{Environment.NewLine}{_certificate.ToString(verbose: true)}"); + _certificateInfo = new CertificateInfo(x509Certificate, keyIdentifier); } } finally @@ -78,15 +124,48 @@ public async Task GetCertificateAsync(CancellationToken cancel _mutex.Release(); } - return new X509Certificate2(_certificate); // clone it as it's disposable + return _certificateInfo; } - public async Task GetRsaAsync(CancellationToken cancellationToken) + private KeyVaultKeyIdentifier GetKeyIdentifier(KeyVaultCertificate certificate) { - using X509Certificate2 certificate = await GetCertificateAsync(cancellationToken); - RSAKeyVault rsaKeyVault = await _cryptographyClient.CreateRSAAsync(cancellationToken); - RSA rsaPublicKey = certificate.GetRSAPublicKey()!; - return new RSAKeyVaultWrapper(rsaKeyVault, rsaPublicKey); + Uri keyId; + + try + { + keyId = certificate.KeyId; + } + catch (Exception exception) when (exception is ArgumentNullException or UriFormatException) + { + throw new InvalidOperationException(Resources.InvalidCertificateKeyIdentifier, exception); + } + + if (!KeyVaultKeyIdentifier.TryCreate(keyId, out KeyVaultKeyIdentifier keyIdentifier) || + !string.Equals(keyId.Segments[1].TrimEnd('/'), "keys", StringComparison.OrdinalIgnoreCase) || + string.IsNullOrEmpty(keyIdentifier.Version) || + Uri.Compare( + _certificateClient.VaultUri, + keyIdentifier.VaultUri, + UriComponents.SchemeAndServer, + UriFormat.Unescaped, + StringComparison.OrdinalIgnoreCase) != 0) + { + throw new InvalidOperationException(Resources.InvalidCertificateKeyIdentifier); + } + + return keyIdentifier; + } + + private sealed class CertificateInfo + { + internal X509Certificate2 Certificate { get; } + internal KeyVaultKeyIdentifier KeyIdentifier { get; } + + internal CertificateInfo(X509Certificate2 certificate, KeyVaultKeyIdentifier keyIdentifier) + { + Certificate = certificate; + KeyIdentifier = keyIdentifier; + } } } } diff --git a/src/Sign.SignatureProviders.KeyVault/Resources.Designer.cs b/src/Sign.SignatureProviders.KeyVault/Resources.Designer.cs index 0ba23774..846408d5 100644 --- a/src/Sign.SignatureProviders.KeyVault/Resources.Designer.cs +++ b/src/Sign.SignatureProviders.KeyVault/Resources.Designer.cs @@ -86,5 +86,14 @@ internal static string FetchingCertificate { return ResourceManager.GetString("FetchingCertificate", resourceCulture); } } + + /// + /// Looks up a localized string similar to The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault.. + /// + internal static string InvalidCertificateKeyIdentifier { + get { + return ResourceManager.GetString("InvalidCertificateKeyIdentifier", resourceCulture); + } + } } } diff --git a/src/Sign.SignatureProviders.KeyVault/Resources.resx b/src/Sign.SignatureProviders.KeyVault/Resources.resx index 7ca8c68c..66c8db43 100644 --- a/src/Sign.SignatureProviders.KeyVault/Resources.resx +++ b/src/Sign.SignatureProviders.KeyVault/Resources.resx @@ -127,4 +127,7 @@ Fetching certificate from Azure Key Vault. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.cs.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.cs.xlf index 727716f1..16571a64 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.cs.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.cs.xlf @@ -17,6 +17,11 @@ Načítá se certifikát z Azure Key Vault. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.de.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.de.xlf index 5679bb7f..7196aad1 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.de.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.de.xlf @@ -17,6 +17,11 @@ Zertifikat wird von Azure Key Vault abgerufen. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.es.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.es.xlf index 7baefbe9..8b7202f7 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.es.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.es.xlf @@ -17,6 +17,11 @@ Capturando certificado de Azure Key Vault. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.fr.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.fr.xlf index a73de16f..9603017b 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.fr.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.fr.xlf @@ -17,6 +17,11 @@ Récupération du certificat à partir d’Azure Key Vault. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.it.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.it.xlf index cbc32139..fc41e6aa 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.it.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.it.xlf @@ -17,6 +17,11 @@ Recupero certificato da Azure Key Vault in corso. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ja.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ja.xlf index 338f76a3..aaa9c790 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ja.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ja.xlf @@ -17,6 +17,11 @@ Azure Key Vault から証明書をフェッチしています。 + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ko.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ko.xlf index 3d38063d..0671c0d9 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ko.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ko.xlf @@ -17,6 +17,11 @@ Azure Key Vault에서 인증서를 가져오는 중입니다. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.pl.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.pl.xlf index 21f20531..49b1d67f 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.pl.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.pl.xlf @@ -17,6 +17,11 @@ Pobieranie certyfikatu z usługi Azure Key Vault. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.pt-BR.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.pt-BR.xlf index 14b43ddd..87deaadb 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.pt-BR.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.pt-BR.xlf @@ -17,6 +17,11 @@ Buscando certificado no Azure Key Vault. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ru.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ru.xlf index a1001f7e..13bc8452 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ru.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.ru.xlf @@ -17,6 +17,11 @@ Идет получение сертификата из Azure Key Vault. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.tr.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.tr.xlf index a323a14a..cab61227 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.tr.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.tr.xlf @@ -17,6 +17,11 @@ Sertifika Azure Key Vault’tan getiriliyor. + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.zh-Hans.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.zh-Hans.xlf index 5474f55d..6bfbb0e3 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.zh-Hans.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.zh-Hans.xlf @@ -17,6 +17,11 @@ 正在从 Azure Key Vault 提取证书。 + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.zh-Hant.xlf b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.zh-Hant.xlf index bbb38b0f..8fe60865 100644 --- a/src/Sign.SignatureProviders.KeyVault/xlf/Resources.zh-Hant.xlf +++ b/src/Sign.SignatureProviders.KeyVault/xlf/Resources.zh-Hant.xlf @@ -17,6 +17,11 @@ 正在從 Azure Key Vault 擷取憑證。 + + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + The Azure Key Vault certificate does not have a valid backing key identifier for the configured vault. + + \ No newline at end of file diff --git a/test/Sign.Cli.Test/AzureKeyVaultCommandTests.cs b/test/Sign.Cli.Test/AzureKeyVaultCommandTests.cs index 3a66139f..e2905f39 100644 --- a/test/Sign.Cli.Test/AzureKeyVaultCommandTests.cs +++ b/test/Sign.Cli.Test/AzureKeyVaultCommandTests.cs @@ -3,6 +3,13 @@ // See the LICENSE.txt file in the project root for more information. using System.CommandLine; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Azure; +using Azure.Security.KeyVault.Certificates; +using Azure.Security.KeyVault.Keys; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using NSubstitute; using Sign.Core; @@ -10,6 +17,7 @@ namespace Sign.Cli.Test { public class AzureKeyVaultCommandTests { + private const string CertificateVersion = "0123456789abcdef0123456789abcdef"; private readonly AzureKeyVaultCommand _command = new(new CodeCommand(), Substitute.For()); [Fact] @@ -42,6 +50,18 @@ public void CertificateOption_Always_IsRequired() Assert.True(_command.CertificateOption.Required); } + [Fact] + public void CertificateVersionOption_Always_HasArityOfExactlyOne() + { + Assert.Equal(ArgumentArity.ExactlyOne, _command.CertificateVersionOption.Arity); + } + + [Fact] + public void CertificateVersionOption_Always_IsOptional() + { + Assert.False(_command.CertificateVersionOption.Required); + } + [Fact] public void UrlOption_Always_HasArityOfExactlyOne() { @@ -58,11 +78,12 @@ public class ParserTests { private readonly AzureKeyVaultCommand _command; private readonly RootCommand _rootCommand; + private readonly IServiceProviderFactory _serviceProviderFactory = Substitute.For(); public ParserTests() { CodeCommand codeCommand = new(); - _command = new(codeCommand, Substitute.For()); + _command = new(codeCommand, _serviceProviderFactory); _rootCommand = new RootCommand(); _rootCommand.Subcommands.Add(codeCommand); codeCommand.Subcommands.Add(_command); @@ -92,6 +113,8 @@ public void Command_WhenRequiredArgumentOrOptionsAreMissing_HasError(string comm [Theory] [InlineData("code azure-key-vault -kvu https://keyvault.test -kvc a b")] [InlineData("code azure-key-vault -kvu https://keyvault.test -kvc a -kvt b -kvi c -kvs d e")] + [InlineData($"code azure-key-vault -kvu https://keyvault.test -kvc a -kvcv {CertificateVersion} c")] + [InlineData($"code azure-key-vault -kvu https://keyvault.test -kvc a --azure-key-vault-certificate-version {CertificateVersion} c")] public void Command_WhenRequiredArgumentsArePresent_HasNoError(string command) { ParseResult result = _rootCommand.Parse(command); @@ -99,6 +122,88 @@ public void Command_WhenRequiredArgumentsArePresent_HasNoError(string command) Assert.Empty(result.Errors); } + [Theory] + [InlineData("-kvcv")] + [InlineData("--azure-key-vault-certificate-version")] + public void Command_WhenCertificateVersionIsSpecified_ParsesCorrectly(string option) + { + ParseResult result = _rootCommand.Parse($"code azure-key-vault -kvu https://keyvault.test -kvc a {option} {CertificateVersion} c"); + + Assert.Empty(result.Errors); + Assert.Equal(CertificateVersion, result.GetValue(_command.CertificateVersionOption)); + } + + [Fact] + public async Task Command_WhenCertificateVersionIsSpecified_ConfiguresServiceWithVersion() + { + Action? addServices = null; + IServiceProvider emptyServiceProvider = new ServiceCollection().BuildServiceProvider(); + + _serviceProviderFactory + .When(factory => factory.AddServices(Arg.Any>())) + .Do(call => addServices = call.Arg>()); + _serviceProviderFactory + .Create( + Arg.Any(), + Arg.Any(), + Arg.Any?>()) + .Returns(emptyServiceProvider); + + int exitCode = await _rootCommand + .Parse($"code azure-key-vault -kvu https://keyvault.test -kvc a -kvcv {CertificateVersion} missing-file") + .InvokeAsync(); + + Assert.Equal(ExitCode.NoInputsFound, exitCode); + Assert.NotNull(addServices); + + Uri keyId = new("https://keyvault.test/keys/a/key-version"); + CertificateClient certificateClient = Substitute.For(); + certificateClient.VaultUri.Returns(new Uri("https://keyvault.test/")); + using RSA rsa = RSA.Create(); + CertificateRequest certificateRequest = new("CN=test", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using X509Certificate2 selfIssuedCertificate = certificateRequest.CreateSelfSigned( + DateTimeOffset.UtcNow.AddDays(-1), + DateTimeOffset.UtcNow.AddDays(1)); + KeyVaultCertificate certificate = CertificateModelFactory.KeyVaultCertificate( + new CertificateProperties("a"), + keyId: keyId, + cer: selfIssuedCertificate.Export(X509ContentType.Cert)); + Response response = Response.FromValue(certificate, Substitute.For()); + certificateClient + .GetCertificateVersionAsync("a", CertificateVersion, Arg.Any()) + .Returns(response); + + ServiceCollection services = new(); + services.AddLogging(); + addServices(services); + services.AddSingleton(certificateClient); + + using Microsoft.Extensions.DependencyInjection.ServiceProvider serviceProvider = services.BuildServiceProvider(); + KeyClient keyClient = serviceProvider.GetRequiredService(); + Type serviceType = Type.GetType( + "Sign.SignatureProviders.KeyVault.KeyVaultService, Sign.SignatureProviders.KeyVault", + throwOnError: true)!; + ICertificateProvider service = (ICertificateProvider)serviceProvider.GetRequiredService(serviceType); + using X509Certificate2 result = await service.GetCertificateAsync(CancellationToken.None); + + await certificateClient.Received(1) + .GetCertificateVersionAsync("a", CertificateVersion, Arg.Any()); + Assert.Equal(new Uri("https://keyvault.test/"), keyClient.VaultUri); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("0123456789abcdef0123456789abcde")] + [InlineData("0123456789abcdef0123456789abcdef0")] + public void Command_WhenCertificateVersionLengthIsInvalid_HasError(string certificateVersion) + { + ParseResult result = _rootCommand.Parse( + $"code azure-key-vault -kvu https://keyvault.test -kvc a -kvcv \"{certificateVersion}\" c"); + + Assert.Contains(result.Errors, error => error.Message == AzureKeyVaultResources.InvalidCertificateVersionValue); + } + [Theory] [InlineData("code azure-key-vault -kvu \"\" -kvc a b")] [InlineData("code azure-key-vault -kvu //keyvault.test -kvc a b")] diff --git a/test/Sign.SignatureProviders.KeyVault.Test/KeyVaultServiceProviderTests.cs b/test/Sign.SignatureProviders.KeyVault.Test/KeyVaultServiceProviderTests.cs index cfe8ab4f..c137ae56 100644 --- a/test/Sign.SignatureProviders.KeyVault.Test/KeyVaultServiceProviderTests.cs +++ b/test/Sign.SignatureProviders.KeyVault.Test/KeyVaultServiceProviderTests.cs @@ -3,7 +3,7 @@ // See the LICENSE.txt file in the project root for more information. using Azure.Security.KeyVault.Certificates; -using Azure.Security.KeyVault.Keys.Cryptography; +using Azure.Security.KeyVault.Keys; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; @@ -24,8 +24,10 @@ public KeyVaultServiceProviderTests() { return new KeyVaultService( Substitute.For(), - Substitute.For(), - "a", sp.GetRequiredService>()); + Substitute.For(), + certificateName: "a", + certificateVersion: null, + sp.GetRequiredService>()); }); serviceProvider = services.BuildServiceProvider(); } diff --git a/test/Sign.SignatureProviders.KeyVault.Test/KeyVaultServiceTests.cs b/test/Sign.SignatureProviders.KeyVault.Test/KeyVaultServiceTests.cs index 83736e26..271c132f 100644 --- a/test/Sign.SignatureProviders.KeyVault.Test/KeyVaultServiceTests.cs +++ b/test/Sign.SignatureProviders.KeyVault.Test/KeyVaultServiceTests.cs @@ -2,9 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE.txt file in the project root for more information. +using System.Net; +using System.Net.Http; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using System.Text; using Azure; +using Azure.Core; +using Azure.Core.Pipeline; using Azure.Security.KeyVault.Certificates; using Azure.Security.KeyVault.Keys; using Azure.Security.KeyVault.Keys.Cryptography; @@ -17,34 +22,45 @@ namespace Sign.SignatureProviders.KeyVault.Test public class KeyVaultServiceTests { private const string CertificateName = "a"; + private const string CertificateVersion = "0123456789abcdef0123456789abcdef"; + private const string KeyName = "backing-key"; + private const string KeyVersion = "backing-key-version"; + private static readonly Uri VaultUri = new("https://keyvault.test/"); + private static readonly Uri KeyId = new($"https://keyvault.test/keys/{KeyName}/{KeyVersion}"); private static readonly ILogger Logger = Substitute.For>(); private readonly CertificateClient _certificateClient = Substitute.For(); private readonly CryptographyClient _cryptographyClient = Substitute.For(); + private readonly KeyClient _keyClient = Substitute.For(); + + public KeyVaultServiceTests() + { + _certificateClient.VaultUri.Returns(VaultUri); + } [Fact] public void Constructor_WhenCertificateClientIsNull_Throws() { ArgumentNullException exception = Assert.Throws( - () => new KeyVaultService(certificateClient: null!, _cryptographyClient, CertificateName, Logger)); + () => new KeyVaultService(certificateClient: null!, _keyClient, CertificateName, certificateVersion: null, Logger)); Assert.Equal("certificateClient", exception.ParamName); } [Fact] - public void Constructor_WhenCryptographyClientIsNull_Throws() + public void Constructor_WhenKeyClientIsNull_Throws() { ArgumentNullException exception = Assert.Throws( - () => new KeyVaultService(_certificateClient, cryptographyClient: null!, CertificateName, Logger)); + () => new KeyVaultService(_certificateClient, keyClient: null!, CertificateName, certificateVersion: null, Logger)); - Assert.Equal("cryptographyClient", exception.ParamName); + Assert.Equal("keyClient", exception.ParamName); } [Fact] public void Constructor_WhenCertificateNameIsNull_Throws() { ArgumentNullException exception = Assert.Throws( - () => new KeyVaultService(_certificateClient, _cryptographyClient, certificateName: null!, Logger)); + () => new KeyVaultService(_certificateClient, _keyClient, certificateName: null!, certificateVersion: null, Logger)); Assert.Equal("certificateName", exception.ParamName); } @@ -53,7 +69,7 @@ public void Constructor_WhenCertificateNameIsNull_Throws() public void Constructor_WhenCertificateNameIsEmpty_Throws() { ArgumentException exception = Assert.Throws( - () => new KeyVaultService(_certificateClient, _cryptographyClient, certificateName: string.Empty, Logger)); + () => new KeyVaultService(_certificateClient, _keyClient, certificateName: string.Empty, certificateVersion: null, Logger)); Assert.Equal("certificateName", exception.ParamName); } @@ -62,7 +78,7 @@ public void Constructor_WhenCertificateNameIsEmpty_Throws() public void Constructor_WhenLoggerIsNull_Throws() { ArgumentNullException exception = Assert.Throws( - () => new KeyVaultService(_certificateClient, _cryptographyClient, CertificateName, logger: null!)); + () => new KeyVaultService(_certificateClient, _keyClient, CertificateName, certificateVersion: null, logger: null!)); Assert.Equal("logger", exception.ParamName); } @@ -78,7 +94,7 @@ public async Task GetCertificateAsync_CalledTwice_CertificateRetrievedOnce() .GetCertificateAsync(CertificateName, cancellationToken) .Returns(response); - using KeyVaultService service = new(_certificateClient, _cryptographyClient, CertificateName, Logger); + using KeyVaultService service = new(_certificateClient, _keyClient, CertificateName, certificateVersion: null, Logger); using X509Certificate2 certificate1 = await service.GetCertificateAsync(cancellationToken); using X509Certificate2 certificate2 = await service.GetCertificateAsync(cancellationToken); @@ -86,6 +102,60 @@ public async Task GetCertificateAsync_CalledTwice_CertificateRetrievedOnce() await _certificateClient.Received(1).GetCertificateAsync(CertificateName, cancellationToken); } + [Fact] + public async Task GetCertificateAsync_WhenCertificateVersionIsSpecified_RetrievesVersion() + { + CancellationToken cancellationToken = CancellationToken.None; + using X509Certificate2 selfIssuedCertificate = SelfIssuedCertificateCreator.CreateCertificate(); + byte[] publicKey = selfIssuedCertificate.Export(X509ContentType.Cert); + KeyVaultCertificate certificate = CertificateModelFactory.KeyVaultCertificate( + new CertificateProperties(CertificateName), + keyId: KeyId, + cer: publicKey); + Response response = Response.FromValue(certificate, Substitute.For()); + + _certificateClient + .GetCertificateVersionAsync(CertificateName, CertificateVersion, cancellationToken) + .Returns(response); + + using KeyVaultService service = new( + _certificateClient, + _keyClient, + CertificateName, + CertificateVersion, + Logger); + + using X509Certificate2 result = await service.GetCertificateAsync(cancellationToken); + + await _certificateClient.Received(1) + .GetCertificateVersionAsync(CertificateName, CertificateVersion, cancellationToken); + } + + [Fact] + public async Task GetCertificateAsync_WhenCertificateVersionDoesNotExist_DoesNotRetrieveLatestVersion() + { + CancellationToken cancellationToken = CancellationToken.None; + RequestFailedException expectedException = new(status: 404, message: "Not found"); + + _certificateClient + .GetCertificateVersionAsync(CertificateName, CertificateVersion, cancellationToken) + .Returns(Task.FromException>(expectedException)); + + using KeyVaultService service = new( + _certificateClient, + _keyClient, + CertificateName, + CertificateVersion, + Logger); + + RequestFailedException actualException = await Assert.ThrowsAsync( + () => service.GetCertificateAsync(cancellationToken)); + + Assert.Same(expectedException, actualException); + await _certificateClient.DidNotReceiveWithAnyArgs() + .GetCertificateAsync(default!, default); + } + [Fact] public async Task GetRsaAsync_ReturnsRSAKeyVaultWrapper() { @@ -101,19 +171,151 @@ public async Task GetRsaAsync_ReturnsRSAKeyVaultWrapper() _cryptographyClient .CreateRSAAsync(cancellationToken) .Returns(rsaKeyVault); + _keyClient + .GetCryptographyClient(KeyName, KeyVersion) + .Returns(_cryptographyClient); - using KeyVaultService service = new(_certificateClient, _cryptographyClient, CertificateName, Logger); + using KeyVaultService service = new(_certificateClient, _keyClient, CertificateName, certificateVersion: null, Logger); using RSA rsa = await service.GetRsaAsync(cancellationToken); Assert.IsType(rsa); + _keyClient.Received(1).GetCryptographyClient(KeyName, KeyVersion); } - private static KeyVaultCertificateWithPolicy CreateKeyVaultCertificateWithPolicy() + [Fact] + public async Task GetRsaAsync_WhenCertificateAndKeyIdentifiersDiffer_UsesAndCachesBackingKeyIdentifier() { - byte[] publicKey = SelfIssuedCertificateCreator.CreateCertificate().Export(X509ContentType.Cert); + CancellationToken cancellationToken = CancellationToken.None; + using X509Certificate2 selfIssuedCertificate = SelfIssuedCertificateCreator.CreateCertificate(); + byte[] publicKey = selfIssuedCertificate.Export(X509ContentType.Cert); + Uri certificateId = new($"https://keyvault.test/certificates/{CertificateName}/{CertificateVersion}"); + KeyVaultCertificate certificate = CertificateModelFactory.KeyVaultCertificate( + new CertificateProperties(certificateId), + keyId: KeyId, + cer: publicKey); + Response response = Response.FromValue(certificate, Substitute.For()); + RSAKeyVault rsaKeyVault = CreateRSAKeyVault(); + + _certificateClient + .GetCertificateVersionAsync(CertificateName, CertificateVersion, cancellationToken) + .Returns(response); + _keyClient + .GetCryptographyClient(KeyName, KeyVersion) + .Returns(_cryptographyClient); + _cryptographyClient + .CreateRSAAsync(cancellationToken) + .Returns(rsaKeyVault); + + using KeyVaultService service = new( + _certificateClient, + _keyClient, + CertificateName, + CertificateVersion, + Logger); + + using RSA rsa1 = await service.GetRsaAsync(cancellationToken); + using RSA rsa2 = await service.GetRsaAsync(cancellationToken); + + _keyClient.Received(1).GetCryptographyClient(KeyName, KeyVersion); + _keyClient.DidNotReceive().GetCryptographyClient(CertificateName, CertificateVersion); + } + + [Theory] + [InlineData("https://other-keyvault.test/keys/a/key-version")] + [InlineData("https://keyvault.test/certificates/a/key-version")] + [InlineData("https://keyvault.test/keys/a")] + public async Task GetCertificateAsync_WhenKeyIdIsInvalid_Throws(string keyId) + { + CancellationToken cancellationToken = CancellationToken.None; + KeyVaultCertificateWithPolicy certificate = CreateKeyVaultCertificateWithPolicy( + keyId: new Uri(keyId)); + Response response = Response.FromValue(certificate, Substitute.For()); + + _certificateClient + .GetCertificateAsync(CertificateName, cancellationToken) + .Returns(response); + + using KeyVaultService service = new( + _certificateClient, + _keyClient, + CertificateName, + certificateVersion: null, + Logger); + + InvalidOperationException exception = await Assert.ThrowsAsync( + () => service.GetCertificateAsync(cancellationToken)); + + Assert.Equal(Resources.InvalidCertificateKeyIdentifier, exception.Message); + _keyClient.DidNotReceiveWithAnyArgs().GetCryptographyClient(default!, default!); + } + + [Fact] + public async Task GetCertificateAsync_WhenKeyIdIsMissing_Throws() + { + CancellationToken cancellationToken = CancellationToken.None; + using X509Certificate2 selfIssuedCertificate = SelfIssuedCertificateCreator.CreateCertificate(); + byte[] publicKey = selfIssuedCertificate.Export(X509ContentType.Cert); + KeyVaultCertificateWithPolicy certificate = CertificateModelFactory.KeyVaultCertificateWithPolicy( + new CertificateProperties("test"), + keyId: null, + cer: publicKey); + Response response = Response.FromValue(certificate, Substitute.For()); + + _certificateClient + .GetCertificateAsync(CertificateName, cancellationToken) + .Returns(response); + + using KeyVaultService service = new( + _certificateClient, + _keyClient, + CertificateName, + certificateVersion: null, + Logger); + + InvalidOperationException exception = await Assert.ThrowsAsync( + () => service.GetCertificateAsync(cancellationToken)); + + Assert.Equal(Resources.InvalidCertificateKeyIdentifier, exception.Message); + Assert.IsType(exception.InnerException); + _keyClient.DidNotReceiveWithAnyArgs().GetCryptographyClient(default!, default!); + } + + [Fact] + public async Task GetCertificateAsync_WhenKeyIdIsMalformed_Throws() + { + using X509Certificate2 selfIssuedCertificate = SelfIssuedCertificateCreator.CreateCertificate(); + string certificate = Convert.ToBase64String(selfIssuedCertificate.Export(X509ContentType.Cert)); + string responseContent = + $$"""{"id":"https://keyvault.test/certificates/a/{{CertificateVersion}}","kid":"https://[bad","cer":"{{certificate}}"}"""; + CertificateClientOptions options = new() + { + Transport = new HttpClientTransport(new ResponseMessageHandler(responseContent)) + }; + CertificateClient certificateClient = new(VaultUri, new TestTokenCredential(), options); + + using KeyVaultService service = new( + certificateClient, + _keyClient, + CertificateName, + CertificateVersion, + Logger); + + InvalidOperationException exception = await Assert.ThrowsAsync( + () => service.GetCertificateAsync(CancellationToken.None)); + + Assert.Equal(Resources.InvalidCertificateKeyIdentifier, exception.Message); + Assert.IsType(exception.InnerException); + _keyClient.DidNotReceiveWithAnyArgs().GetCryptographyClient(default!, default!); + } + + private static KeyVaultCertificateWithPolicy CreateKeyVaultCertificateWithPolicy(Uri? keyId = null) + { + using X509Certificate2 selfIssuedCertificate = SelfIssuedCertificateCreator.CreateCertificate(); + byte[] publicKey = selfIssuedCertificate.Export(X509ContentType.Cert); return CertificateModelFactory.KeyVaultCertificateWithPolicy( new CertificateProperties("test"), + keyId: keyId ?? KeyId, cer: publicKey); } @@ -129,5 +331,45 @@ private static RSAKeyVault CreateRSAKeyVault() keyMaterial); #pragma warning restore NS2001 } + + private sealed class ResponseMessageHandler : HttpMessageHandler + { + private readonly string _content; + + internal ResponseMessageHandler(string content) + { + _content = content; + } + + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + HttpResponseMessage response = new(HttpStatusCode.OK) + { + Content = new StringContent(_content, Encoding.UTF8, "application/json"), + RequestMessage = request + }; + + return Task.FromResult(response); + } + } + + private sealed class TestTokenCredential : TokenCredential + { + public override AccessToken GetToken( + TokenRequestContext requestContext, + CancellationToken cancellationToken) + { + return new AccessToken("token", DateTimeOffset.MaxValue); + } + + public override ValueTask GetTokenAsync( + TokenRequestContext requestContext, + CancellationToken cancellationToken) + { + return ValueTask.FromResult(GetToken(requestContext, cancellationToken)); + } + } } }