Skip to content
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
92 changes: 92 additions & 0 deletions CERTInext.Tests/PluginVersionLoggingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright 2026 Keyfactor
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
// and limitations under the License.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentAssertions;
using Keyfactor.AnyGateway.Extensions;
using Keyfactor.Logging;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;

namespace Keyfactor.Extensions.CAPlugin.CERTInext.Tests
{
/// <summary>
/// Pins the "CERTInext CA plugin version" line <see cref="CERTInextCAPlugin.Initialize"/> logs, so a
/// customer log names the build that wrote it. Swaps <see cref="LogHandler.Factory"/> the same way as
/// <see cref="CERTInextCAPluginAuditLoggingTests"/>, so it runs in the shared logging collection.
/// </summary>
[Collection(LoggingStateCollection.Name)]
public class PluginVersionLoggingTests
{
private sealed class CapturingLoggerProvider : ILoggerProvider
{
public ConcurrentQueue<string> Messages { get; } = new();
public ILogger CreateLogger(string categoryName) => new CapturingLogger(Messages);
public void Dispose() { }

private sealed class CapturingLogger : ILogger
{
private readonly ConcurrentQueue<string> _messages;
public CapturingLogger(ConcurrentQueue<string> messages) => _messages = messages;
public IDisposable BeginScope<TState>(TState state) => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter)
=> _messages.Enqueue(formatter(state, exception));
}
}

[Fact]
public void PluginVersion_IsTheAssemblyInformationalVersion()
{
string expected = typeof(CERTInextCAPlugin).Assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;

expected.Should().NotBeNullOrWhiteSpace("the SDK stamps an informational version on every build");
CERTInextCAPlugin.PluginVersion.Should().Be(expected);
CERTInextCAPlugin.PluginTargetFramework.Should().StartWith(".NETCoreApp,Version=v");
}

[Fact]
public void Initialize_LogsVersion_EvenWhenConfigValidationThrows()
{
var provider = new CapturingLoggerProvider();
var factory = LoggerFactory.Create(b => b.AddProvider(provider).SetMinimumLevel(LogLevel.Trace));
try
{
LogHandler.Factory = factory;

var configProvider = new Mock<IAnyCAPluginConfigProvider>(MockBehavior.Strict);
// Cleartext, non-loopback ApiUrl: Initialize rejects it.
configProvider.Setup(p => p.CAConnectionData)
.Returns(new Dictionary<string, object> { ["ApiUrl"] = "http://ca.example.com" });

// Constructed AFTER the factory swap so its _logger field resolves through it.
var plugin = new CERTInextCAPlugin();
Action act = () => plugin.Initialize(configProvider.Object, new Mock<ICertificateDataReader>().Object);

act.Should().Throw<InvalidOperationException>();
}
finally
{
LogHandler.Factory = Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory.Instance;
factory.Dispose();
}

string line = provider.Messages.FirstOrDefault(m => m.StartsWith("CERTInext CA plugin version "));
line.Should().NotBeNull("Initialize logs the version before it validates the config");
line.Should().Contain(CERTInextCAPlugin.PluginVersion);
line.Should().Contain($"DcvSupport={CERTInextCAPlugin.PluginDcvSupport}");
line.Should().Contain($"TargetFramework={CERTInextCAPlugin.PluginTargetFramework}");
}
}
}
49 changes: 48 additions & 1 deletion CERTInext.Tests/SyncProductIdTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ namespace Keyfactor.Extensions.CAPlugin.CERTInext.Tests
/// Issue 0097: the gateway gives a synced record a template only when its <c>ProductID</c> exactly equals a
/// template's ProductID, a product name from <c>GetProductIds()</c>. Both syncs must name the CERTInext product
/// code through the account catalog (code -> productTypeID -> name), and keep the code when they can't.
/// Catalog values are the sandbox's (V1 and V2 identical, 2026-11-16).
/// Catalog values are the sandbox's (V1 and V2 identical, 2026-11-16), plus an SSL.com-category catalog.
/// </summary>
[Collection(LoggingStateCollection.Name)]
public class SyncProductIdTests
Expand All @@ -40,12 +40,34 @@ public class SyncProductIdTests
new ProductDetail { ProductCode = "149", ProductTypeId = "39", Active = true }, // Intranet SSL (no plugin product)
};

// An account issuing through SSL.com: the "SSL.com" catalog category (2026-11-17).
private static List<ProductDetail> SslComCatalog() => new List<ProductDetail>
{
new ProductDetail { ProductCode = "1011", ProductTypeId = "47", Active = true }, // SSL.com DV SSL
new ProductDetail { ProductCode = "1012", ProductTypeId = "48", Active = true }, // SSL.com DV SSL Wildcard
new ProductDetail { ProductCode = "1013", ProductTypeId = "49", Active = true }, // SSL.com DV SSL UCC
new ProductDetail { ProductCode = "1014", ProductTypeId = "50", Active = true }, // SSL.com DV SSL Wildcard UCC
new ProductDetail { ProductCode = "1015", ProductTypeId = "51", Active = true }, // SSL.com OV SSL
new ProductDetail { ProductCode = "1020", ProductTypeId = "56", Active = true }, // SSL.com EV SSL UCC
new ProductDetail { ProductCode = "149", ProductTypeId = "39", Active = true }, // Intranet SSL (no plugin product)
};

[Theory]
[InlineData("13", Constants.Products.DvSsl)]
[InlineData("17", Constants.Products.OvSslWildcard)]
[InlineData("21", Constants.Products.DvSslWildcardUcc)]
[InlineData("20", Constants.Products.EvSslUcc)]
[InlineData(" 16 ", Constants.Products.OvSsl)]
[InlineData("47", Constants.Products.DvSsl)]
[InlineData("48", Constants.Products.DvSslWildcard)]
[InlineData("49", Constants.Products.DvSslUcc)]
[InlineData("50", Constants.Products.DvSslWildcardUcc)]
[InlineData("51", Constants.Products.OvSsl)]
[InlineData("52", Constants.Products.OvSslWildcard)]
[InlineData("53", Constants.Products.OvSslUcc)]
[InlineData("54", Constants.Products.OvSslWildcardUcc)]
[InlineData("55", Constants.Products.EvSsl)]
[InlineData("56", Constants.Products.EvSslUcc)]
[InlineData("39", null)]
[InlineData("", null)]
[InlineData(null, null)]
Expand All @@ -62,6 +84,8 @@ public void EveryAdvertisedProductHasATypeId_AndMapsBackToItself()
{
Constants.Products.ProductTypeIdsV2.Should().ContainKey(name);
CERTInextCAPlugin.ProductNameForTypeId(Constants.Products.ProductTypeIdsV2[name]).Should().Be(name);
Constants.Products.SslComProductTypeIdsV2.Should().ContainKey(name);
CERTInextCAPlugin.ProductNameForTypeId(Constants.Products.SslComProductTypeIdsV2[name]).Should().Be(name);
}
}

Expand Down Expand Up @@ -121,6 +145,29 @@ public async Task V2Sync_NamesProductCodesThroughTheCatalog_ReadOnce_KeepsUnknow
capture.Entries.Where(e => e.Level >= LogLevel.Warning).Should().BeEmpty();
}

[Fact]
public async Task V2Sync_SslComCatalog_NamesSslComProductCodes()
{
using var capture = new PluginLogCapture();
var (mock, plugin) = V2(IssuedRow("a", "1011"), IssuedRow("b", "1012"), IssuedRow("c", "1013"),
IssuedRow("d", "1020"), IssuedRow("e", "149"));
mock.Setup(c => c.GetProductDetailsV2Async(It.IsAny<CancellationToken>())).ReturnsAsync(SslComCatalog());
var buffer = new BlockingCollection<AnyCAPluginCertificate>(10);

await plugin.Synchronize(buffer, null, true, CancellationToken.None);

buffer.ToArray().ToDictionary(r => r.CARequestID, r => r.ProductID).Should().Equal(new Dictionary<string, string>
{
["a"] = Constants.Products.DvSsl,
["b"] = Constants.Products.DvSslWildcard,
["c"] = Constants.Products.DvSslUcc,
["d"] = Constants.Products.EvSslUcc,
["e"] = "149", // Private PKI: no plugin product of that type
});
capture.Lines(LogLevel.Information, "synchronization complete").Should().ContainSingle()
.Which.Should().Contain("ProductNames: Resolved=4, Unresolved=1");
}

[Fact]
public async Task V2Sync_CatalogFails_KeepsCodes_OneWarning_SyncCompletes()
{
Expand Down
153 changes: 153 additions & 0 deletions CERTInext.Tests/V2NoCnEnrollmentTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// Copyright 2026 Keyfactor
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Keyfactor.AnyGateway.Extensions;
using Keyfactor.Extensions.CAPlugin.CERTInext.API.V2;
using Keyfactor.Extensions.CAPlugin.CERTInext.Client;
using Moq;
using Xunit;

namespace Keyfactor.Extensions.CAPlugin.CERTInext.Tests
{
/// <summary>
/// V2 SSL requests whose subject has no CN, with the names only in the SANs. The V2 spec requires
/// <c>certificate.domain</c> but not a CSR CN, so the plugin takes the domain from the SANs: the first
/// non-wildcard DNS name, else the first wildcard.
/// </summary>
public class V2NoCnEnrollmentTests
{
private static CERTInextCAPlugin BuildV2Plugin(ICERTInextClient client) =>
new CERTInextCAPlugin(client, new CERTInextConfig
{
UseV2Api = true,
ApiUrl = "https://v2.certinext.io",
OAuthClientId = "my-client",
OAuthClientSecret = "my-secret",
RequestorName = "Test User",
RequestorEmail = "[email protected]",
SignerPlace = "New York",
PickupRetries = 0
});

private static EnrollmentProductInfo DvProductInfo(string productId, string family = "ssl", string variant = null)
{
var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { ["ProductFamily"] = family };
if (variant != null) parameters["ProductVariant"] = variant;
return new EnrollmentProductInfo { ProductID = productId, ProductParameters = parameters };
}

/// <summary>Runs Enroll with an empty subject and returns the create request sent to CERTInext.</summary>
private static async Task<V2CreateSslOrderRequest> EnrollWithoutCnAsync(string[] dnsSans, string productId)
{
var mock = new Mock<ICERTInextClient>(MockBehavior.Loose);
V2CreateSslOrderRequest sent = null;
mock.Setup(c => c.PlaceOrderV2Async(
It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<V2CreateSslOrderRequest>(), It.IsAny<CancellationToken>()))
.Callback<string, string, V2CreateSslOrderRequest, CancellationToken>((_, _, r, _) => sent = r)
.ReturnsAsync(new V2CreateOrderResponse { OrderId = "ord_nocn_001", Status = "pending-dcv" });

await BuildV2Plugin(mock.Object).Enroll(
csr: MockCertificateData.FakeCsrPem,
subject: string.Empty,
san: new Dictionary<string, string[]> { ["dnsname"] = dnsSans },
productInfo: DvProductInfo(productId),
requestFormat: RequestFormat.PKCS10,
enrollmentType: EnrollmentType.New);

sent.Should().NotBeNull("the order must be placed");
return sent;
}

[Fact]
public async Task Enroll_V2_NoCn_WildcardOnlySan_OrdersTheWildcard()
{
var sent = await EnrollWithoutCnAsync(new[] { "*.example.com" }, Constants.Products.DvSslWildcard);

sent.Certificate.Domain.Should().Be("*.example.com");
sent.Certificate.AdditionalDomains.Should().BeNullOrEmpty();
}

[Fact]
public async Task Enroll_V2_NoCn_WildcardFirstThenApex_OrdersTheApexWithTheWildcardAsExtra()
{
var sent = await EnrollWithoutCnAsync(new[] { "*.example.com", "example.com" }, Constants.Products.DvSsl);

sent.Certificate.Domain.Should().Be("example.com",
"a plain name is preferred, so both names are issued as with CN = example.com");
sent.Certificate.AdditionalDomains.Should().Equal("*.example.com");
}

[Fact]
public async Task Enroll_V2_NoCn_NoDnsSan_Throws()
{
var mock = new Mock<ICERTInextClient>(MockBehavior.Loose);

Func<Task> act = () => BuildV2Plugin(mock.Object).Enroll(
csr: MockCertificateData.FakeCsrPem,
subject: string.Empty,
san: new Dictionary<string, string[]>(),
productInfo: DvProductInfo(Constants.Products.DvSsl),
requestFormat: RequestFormat.PKCS10,
enrollmentType: EnrollmentType.New);

await act.Should().ThrowAsync<Exception>()
.WithMessage("Cannot determine primary domain for V2 order*DNS SAN*");
mock.Verify(c => c.PlaceOrderV2Async(
It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<V2CreateSslOrderRequest>(), It.IsAny<CancellationToken>()), Times.Never);
}

[Fact]
public async Task Enroll_V2_PrivatePki_NoCn_StillRequiresACn()
{
var mock = new Mock<ICERTInextClient>(MockBehavior.Loose);

Func<Task> act = () => BuildV2Plugin(mock.Object).Enroll(
csr: MockCertificateData.FakeCsrPem,
subject: string.Empty,
san: new Dictionary<string, string[]> { ["dnsname"] = new[] { "host.example.local" } },
productInfo: DvProductInfo(Constants.Products.DvSsl, family: "private-pki", variant: "intranet-ssl"),
requestFormat: RequestFormat.PKCS10,
enrollmentType: EnrollmentType.New);

await act.Should().ThrowAsync<Exception>()
.WithMessage("Cannot determine the primary hostname for V2 private-pki order*");
}

[Theory]
[InlineData(new[] { "*.example.com" }, "*.example.com")]
[InlineData(new[] { "*.example.com", "example.com" }, "example.com")]
[InlineData(new[] { "a.example.com", "b.example.com" }, "a.example.com")]
public void PrimaryDomainFromSans_PrefersAPlainName(string[] dnsSans, string expected)
{
CERTInextCAPlugin.PrimaryDomainFromSans(
new Dictionary<string, string[]> { ["dnsname"] = dnsSans }, MockCertificateData.FakeCsrPem)
.Should().Be(expected);
}

[Fact]
public void PrimaryDomainFromSans_IgnoresNonDnsSans()
{
CERTInextCAPlugin.PrimaryDomainFromSans(
new Dictionary<string, string[]> { ["ipaddress"] = new[] { "10.0.0.1" } }, MockCertificateData.FakeCsrPem)
.Should().BeNull();
}
}
}
Loading