Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
9002c67
fix(sync): resolve 'Order Fulfilled | Pending for Approver' report ro…
spbsoluble Nov 14, 2026
f806c4d
fix(dcv): look each SSL.com-candidate domain up once per V2 sync pass
spbsoluble Nov 14, 2026
0ab574d
fix(enroll): bound the in-call pickup wait by a deadline from Enroll …
spbsoluble Nov 14, 2026
f37a6e9
docs: auto-generate README and documentation [skip ci]
github-actions[bot] Nov 14, 2026
33681ec
test(live): run the V2 sync for one 'Order Fulfilled | Pending for Ap…
spbsoluble Nov 15, 2026
507d42f
fix(sync): keep 'Order Fulfilled | Pending for Approver' pending when…
spbsoluble Nov 16, 2026
f7d0775
docs: auto-generate README and documentation [skip ci]
github-actions[bot] Nov 16, 2026
3dd45f0
fix(v2): GetSingleRecord returns pending for an issued order with no …
spbsoluble Nov 16, 2026
fcdb49d
docs: auto-generate README and documentation [skip ci]
github-actions[bot] Nov 16, 2026
410d305
test(live): GetSingleRecord returns pending for issued orders with no…
spbsoluble Nov 16, 2026
ed2ceba
docs(v2): CertificateState comment reflects its one use in GetSingleR…
spbsoluble Nov 16, 2026
e993294
fix(sync): report the product name as ProductID so the gateway can as…
spbsoluble Nov 16, 2026
e31b3f9
test(live): probe an order's report row, mapping and Track status (re…
spbsoluble Nov 16, 2026
42f70d8
fix(sync): emit a cancelled/rejected order as failed when the gateway…
spbsoluble Nov 16, 2026
187841a
docs: auto-generate README and documentation [skip ci]
github-actions[bot] Nov 16, 2026
9a42f07
fix(v2): resolve a Wildcard UCC product for a wildcard SAN on a non-w…
spbsoluble Nov 17, 2026
ceb2187
docs: auto-generate README and documentation [skip ci]
github-actions[bot] Nov 17, 2026
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
2 changes: 2 additions & 0 deletions CERTInext.IntegrationTests/IntegrationTestFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ public sealed class IntegrationTestFixture : IDisposable
"CERTINEXT_V2_INLINE_CSR_EXPERIMENT",
// V2 certificate-lifetime probe (V2ValidityProbeTests) — places real sandbox orders.
"CERTINEXT_PROBE_VALIDITY",
// Wildcard-in-the-SANs shape probe (V2WildcardSanShapeTests) — places real sandbox orders.
"CERTINEXT_V2_WILDCARD_SAN_PROBE",
};

// ---------------------------------------------------------------------------
Expand Down
126 changes: 126 additions & 0 deletions CERTInext.IntegrationTests/SyncProductIdLiveTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// 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.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Keyfactor.Extensions.CAPlugin.CERTInext.API;
using Keyfactor.Extensions.CAPlugin.CERTInext.Client;
using Xunit;
using Xunit.Abstractions;

namespace Keyfactor.Extensions.CAPlugin.CERTInext.IntegrationTests
{
/// <summary>
/// Issue 0097: the sync's <c>ProductID</c> must be a product name the gateway's templates use. These read-only
/// probes show how each account catalog maps product codes to <c>productTypeID</c>, which the plugin resolves
/// to a name. Opt-in: <c>CERTINEXT_SYNC_PRODUCTID_PROBE=1</c>.
/// </summary>
public class SyncProductIdLiveTests : IClassFixture<IntegrationTestFixture>
{
private readonly IntegrationTestFixture _fixture;
private readonly ITestOutputHelper _output;
private readonly Dictionary<string, string> _env;

public SyncProductIdLiveTests(IntegrationTestFixture fixture, ITestOutputHelper output)
{
_fixture = fixture;
_output = output;
_env = V2EnvHelper.LoadAndPromote();
}

private void Print(string api, List<ProductDetail> products)
{
_output.WriteLine($"{api} catalog: {products?.Count ?? 0} products");
foreach (var p in (products ?? new List<ProductDetail>()).OrderBy(p => p.ProductTypeId).ThenBy(p => p.ProductCode))
{
string name = CERTInextCAPlugin.ProductNameForTypeId(p.ProductTypeId) ?? "(no plugin product)";
_output.WriteLine($" code={p.ProductCode,-6} typeId={p.ProductTypeId,-4} active={p.Active,-5} " +
$"-> {name,-36} catalogName='{p.ProductName}'");
}
}

[SkippableFact]
public async Task Probe_CatalogCodeToTypeId_V1AndV2_ReadOnly()
{
Skip.If(V2EnvHelper.GetEnv(_env, "CERTINEXT_SYNC_PRODUCTID_PROBE") != "1",
"Requires CERTINEXT_SYNC_PRODUCTID_PROBE=1.");

if (_fixture.IsConfigured)
Print("V1", await _fixture.Client.GetProductDetailsAsync(CancellationToken.None));
else
_output.WriteLine("V1 not configured; skipped.");

string apiUrl = V2EnvHelper.GetEnv(_env, "CERTINEXT_API_URL");
string clientId = V2EnvHelper.GetEnv(_env, "CERTINEXT_CLIENT_ID");
string clientSecret = V2EnvHelper.GetEnv(_env, "CERTINEXT_CLIENT_SECRET");
if (string.IsNullOrWhiteSpace(apiUrl) || string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret))
{
_output.WriteLine("V2 not configured; skipped.");
return;
}
using var v2 = new CERTInextClient(new CERTInextConfig
{
ApiUrl = apiUrl, UseV2Api = true, OAuthClientId = clientId, OAuthClientSecret = clientSecret
});
Print("V2", await v2.GetProductDetailsV2Async(CancellationToken.None));
}

/// <summary>
/// Why a gateway row never gets re-saved by the sync: for each order in
/// <c>CERTINEXT_PROBE_ORDERS</c> (comma-separated), prints its <c>/reports/orders</c> row (or that the report
/// doesn't list it), the plugin's mapping of that row, and Track Order's status. Read-only.
/// </summary>
[SkippableFact]
public async Task Probe_OrderReportAndTrackStatus_ReadOnly()
{
string ids = V2EnvHelper.GetEnv(_env, "CERTINEXT_PROBE_ORDERS");
Skip.If(V2EnvHelper.GetEnv(_env, "CERTINEXT_SYNC_PRODUCTID_PROBE") != "1" || string.IsNullOrWhiteSpace(ids),
"Requires CERTINEXT_SYNC_PRODUCTID_PROBE=1 and CERTINEXT_PROBE_ORDERS.");
var wanted = new HashSet<string>(ids.Split(',', System.StringSplitOptions.RemoveEmptyEntries | System.StringSplitOptions.TrimEntries));

using var v2 = new CERTInextClient(new CERTInextConfig
{
ApiUrl = V2EnvHelper.GetEnv(_env, "CERTINEXT_API_URL"), UseV2Api = true,
OAuthClientId = V2EnvHelper.GetEnv(_env, "CERTINEXT_CLIENT_ID"),
OAuthClientSecret = V2EnvHelper.GetEnv(_env, "CERTINEXT_CLIENT_SECRET")
});

var rows = new Dictionary<string, API.V2.OrderReportEntryV2>();
int total = 0;
await foreach (var row in v2.ListOrdersV2Async())
{
total++;
if (wanted.Contains(row.OrderNumber)) rows[row.OrderNumber] = row;
}
_output.WriteLine($"Report rows read: {total}");

foreach (string id in wanted.OrderBy(x => x))
{
string report = "not listed by /reports/orders";
if (rows.TryGetValue(id, out var r))
{
int? mapped = CERTInextCAPlugin.MapV2ReportStatusToDisposition(r.OrderStatus, r.CertificateStatus);
report = $"'{r.OrderStatus} | {r.CertificateStatus}' product={r.ProductCode} orderDate={r.OrderDate} " +
$"mapped={(mapped?.ToString() ?? "null (Track fallback)")}";
}
string track;
try
{
var (family, st) = await v2.ResolveAndTrackOrderV2WithFamilyAsync(id);
track = $"family={family}, status={st.Status}, orderState={st.OrderState}, certificateState={st.CertificateState}";
}
catch (System.Exception ex)
{
track = $"{ex.GetType().Name}: {ex.Message}";
}
_output.WriteLine($"{id}: report {report} -> Track: {track}");
}
}
}
}
203 changes: 203 additions & 0 deletions CERTInext.IntegrationTests/V2FulfilledPendingSyncLiveTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// 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 System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
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 Keyfactor.PKI.Enums.EJBCA;
using Org.BouncyCastle.X509;
using Xunit;
using Xunit.Abstractions;

namespace Keyfactor.Extensions.CAPlugin.CERTInext.IntegrationTests
{
/// <summary>
/// Plan 0096 item 2, live: a <c>/reports/orders</c> row reading <c>Order Fulfilled | Pending for Approver</c>
/// must go through Track Order and have its certificate download tried: issued with the certificate when
/// one exists, pending (as the row's certificate status says) when the download answers EMS-1165.
/// Runs the real <c>Synchronize</c> code against the live API, with the report listing narrowed to one
/// order by a forwarding proxy; every other call goes to the real client unchanged. Read-only at
/// CERTInext (list, track, download), DCV off. Opt-in: <c>CERTINEXT_V2_FULFILLED_PENDING_SYNC=1</c>;
/// order from <c>CERTINEXT_V2_FULFILLED_PENDING_ORDER</c> (default 1125823297).
/// </summary>
public class V2FulfilledPendingSyncLiveTests : IClassFixture<IntegrationTestFixture>
{
private readonly ITestOutputHelper _output;
private readonly Dictionary<string, string> _env;

public V2FulfilledPendingSyncLiveTests(IntegrationTestFixture fixture, ITestOutputHelper output)
{
_output = output;
_env = V2EnvHelper.LoadAndPromote();
}

/// <summary>Forwards every call to <see cref="Inner"/>; the report listing yields only <see cref="OrderId"/>.</summary>
public class OneOrderListingProxy : DispatchProxy
{
internal ICERTInextClient Inner;
internal string OrderId;
internal readonly ConcurrentQueue<string> Calls = new ConcurrentQueue<string>();
internal int RowsListed;

protected override object Invoke(MethodInfo targetMethod, object[] args)
{
Calls.Enqueue(targetMethod.Name);
object result;
try { result = targetMethod.Invoke(Inner, args); }
catch (TargetInvocationException tie) when (tie.InnerException != null)
{
ExceptionDispatchInfo.Capture(tie.InnerException).Throw();
throw;
}
return targetMethod.Name == nameof(ICERTInextClient.ListOrdersV2Async)
? OnlyTarget((IAsyncEnumerable<OrderReportEntryV2>)result)
: result;
}

private async IAsyncEnumerable<OrderReportEntryV2> OnlyTarget(
IAsyncEnumerable<OrderReportEntryV2> rows, [EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var row in rows.WithCancellation(ct))
{
RowsListed++;
if (string.Equals(row.OrderNumber, OrderId, StringComparison.Ordinal))
yield return row;
}
}
}

[SkippableFact]
public async Task Sync_OrderFulfilledPendingForApprover_TracksAndDownloads()
{
string apiUrl = V2EnvHelper.GetEnv(_env, "CERTINEXT_API_URL");
string clientId = V2EnvHelper.GetEnv(_env, "CERTINEXT_CLIENT_ID");
string clientSecret = V2EnvHelper.GetEnv(_env, "CERTINEXT_CLIENT_SECRET");
Skip.If(string.IsNullOrWhiteSpace(V2EnvHelper.GetEnv(_env, "CERTINEXT_USE_V2_API"))
|| string.IsNullOrWhiteSpace(apiUrl) || string.IsNullOrWhiteSpace(clientId)
|| string.IsNullOrWhiteSpace(clientSecret)
|| V2EnvHelper.GetEnv(_env, "CERTINEXT_V2_FULFILLED_PENDING_SYNC") != "1",
"Requires CERTINEXT_USE_V2_API + V2 credentials and CERTINEXT_V2_FULFILLED_PENDING_SYNC=1.");
string orderId = V2EnvHelper.GetEnv(_env, "CERTINEXT_V2_FULFILLED_PENDING_ORDER", "1125823297");

var config = new CERTInextConfig
{
ApiUrl = apiUrl, UseV2Api = true, OAuthClientId = clientId, OAuthClientSecret = clientSecret,
SignerPlace = "Gateway Lab", PageSize = 100, DcvEnabled = false
};
var restoreLogging = TestOutputLogging.RouteTo(_output);
try
{
using var real = new CERTInextClient(config);
var proxy = DispatchProxy.Create<ICERTInextClient, OneOrderListingProxy>();
var p = (OneOrderListingProxy)(object)proxy;
p.Inner = real;
p.OrderId = orderId;

using var plugin = new CERTInextCAPlugin(proxy, config);
var buffer = new BlockingCollection<AnyCAPluginCertificate>(10);
await plugin.Synchronize(buffer, null, true, CancellationToken.None);

var calls = p.Calls.ToList();
_output.WriteLine($"Report rows read: {p.RowsListed}; passed to sync: order {orderId} only.");
_output.WriteLine("Client calls: " + string.Join(", ", calls.GroupBy(c => c).Select(g => $"{g.Key} x{g.Count()}")));

var record = buffer.ToArray().Should().ContainSingle(r => r.CARequestID == orderId,
"the order must be emitted (it is not recent, failed, or untrackable)").Subject;
_output.WriteLine($"Emitted: CARequestID={record.CARequestID}, Status={record.Status}, ProductID={record.ProductID}, " +
$"HasCertificate={!string.IsNullOrWhiteSpace(record.Certificate)}");
if (!string.IsNullOrWhiteSpace(record.Certificate))
{
var cert = new X509CertificateParser().ReadCertificate(System.Text.Encoding.ASCII.GetBytes(record.Certificate));
_output.WriteLine($"Certificate: Subject={cert.SubjectDN}, Serial={cert.SerialNumber.ToString(16).ToUpperInvariant()}, " +
$"NotBefore={cert.NotBefore:u}, NotAfter={cert.NotAfter:u}");
}

// Issue 0097: ProductID is the product name the gateway's templates use, named through the catalog.
plugin.GetProductIds().Should().Contain(record.ProductID,
"the gateway gives a synced record a template only when ProductID equals a template's product name");
calls.Should().Contain(nameof(ICERTInextClient.ResolveAndTrackOrderV2WithFamilyAsync),
"the Fulfilled/Pending-for-Approver pair must defer to Track Order");
calls.Should().Contain(nameof(ICERTInextClient.ResolveAndDownloadCertificateV2Async),
"Track Order reports the order issued, so its certificate download is tried");
// Whether a body comes back is CA state. Live 2026-11-15: 1125823297 answered 422 EMS-1165
// (never generated; Finding 35 update). With a certificate the order is issued; without one it
// stays pending, as the report's "Pending for Approver" says.
if (string.IsNullOrWhiteSpace(record.Certificate))
{
record.Status.Should().Be((int)EndEntityStatus.EXTERNALVALIDATION,
"no certificate was generated, so the report's pending certificate status stands");
_output.WriteLine("No certificate body: download answered EMS-1165; emitted pending.");
}
else
{
record.Status.Should().Be((int)EndEntityStatus.GENERATED);
}
}
finally
{
restoreLogging();
}
}

/// <summary>
/// The same rule through <c>GetSingleRecord</c>, which reads Track Order's <c>certificateState</c>
/// instead of the report. Read-only, DCV off. Orders from <c>CERTINEXT_V2_SINGLE_RECORD_ORDERS</c>
/// (comma-separated; default 1125823297). For each: issued with a certificate, or pending without one
/// when the certificate state says pending.
/// </summary>
[SkippableFact]
public async Task GetSingleRecord_IssuedWithoutCertificate_PendingCertificateState_ReturnsPending()
{
string apiUrl = V2EnvHelper.GetEnv(_env, "CERTINEXT_API_URL");
string clientId = V2EnvHelper.GetEnv(_env, "CERTINEXT_CLIENT_ID");
string clientSecret = V2EnvHelper.GetEnv(_env, "CERTINEXT_CLIENT_SECRET");
Skip.If(string.IsNullOrWhiteSpace(V2EnvHelper.GetEnv(_env, "CERTINEXT_USE_V2_API"))
|| string.IsNullOrWhiteSpace(apiUrl) || string.IsNullOrWhiteSpace(clientId)
|| string.IsNullOrWhiteSpace(clientSecret)
|| V2EnvHelper.GetEnv(_env, "CERTINEXT_V2_FULFILLED_PENDING_SYNC") != "1",
"Requires CERTINEXT_USE_V2_API + V2 credentials and CERTINEXT_V2_FULFILLED_PENDING_SYNC=1.");
var orderIds = V2EnvHelper.GetEnv(_env, "CERTINEXT_V2_SINGLE_RECORD_ORDERS", "1125823297")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);

var config = new CERTInextConfig
{
ApiUrl = apiUrl, UseV2Api = true, OAuthClientId = clientId, OAuthClientSecret = clientSecret,
SignerPlace = "Gateway Lab", DcvEnabled = false
};
var restoreLogging = TestOutputLogging.RouteTo(_output);
try
{
using var plugin = new CERTInextCAPlugin(new CERTInextClient(config), config);
foreach (string id in orderIds)
{
var record = await plugin.GetSingleRecord(id);
bool hasBody = !string.IsNullOrWhiteSpace(record.Certificate);
_output.WriteLine($"GetSingleRecord {id}: Status={record.Status}, HasCertificate={hasBody}, ProductID={record.ProductID}");
if (hasBody)
record.Status.Should().Be((int)EndEntityStatus.GENERATED, $"order {id} has a certificate");
else
record.Status.Should().NotBe((int)EndEntityStatus.GENERATED,
$"order {id} has no certificate; a pending certificate state must be reported pending");
}
}
finally
{
restoreLogging();
}
}
}
}
Loading