From a1c23f6dff86951e7288b9bf1a4f04bf5d385d64 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Tue, 7 Apr 2026 16:04:44 -0400 Subject: [PATCH 01/29] 200 day renewal fixes --- .claude/settings.json | 8 ++++ cscglobal-caplugin/CSCGlobalCAPlugin.cs | 59 ++++++++++++++++++++++--- cscglobal-caplugin/Constants.cs | 1 + 3 files changed, 61 insertions(+), 7 deletions(-) create mode 100644 .claude/settings.json diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..c64f0fd --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,8 @@ +{ + "permissions": { + "allow": [ + "Bash(git fetch:*)", + "Bash(git checkout:*)" + ] + } +} diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index e1af2f0..7e6be8a 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -39,6 +39,8 @@ public CSCGlobalCAPlugin() public int SyncFilterDays { get; set; } + public int RenewalWindowDays { get; set; } + //done public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDataReader certificateDataReader) { @@ -57,6 +59,15 @@ public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDa Logger.LogDebug($"SyncFilterDays configured to {SyncFilterDays} days"); } } + + RenewalWindowDays = 30; // default + if (configProvider.CAConnectionData.TryGetValue(Constants.RenewalWindowDays, out var renewalWindowObj)) + { + if (int.TryParse(renewalWindowObj?.ToString(), out var renewalWindowDays) && renewalWindowDays > 0) + RenewalWindowDays = renewalWindowDays; + } + Logger.LogDebug("RenewalWindowDays configured to {Days} days", RenewalWindowDays); + Logger.MethodExit(LogLevel.Debug); } @@ -252,17 +263,44 @@ public async Task Enroll(string csr, string subject, Dictionar return _requestManager.GetEnrollmentResult(enrollmentResponse); case EnrollmentType.RenewOrReissue: Logger.LogTrace("Entering Renew Enrollment"); - //Logic to determine renew vs reissue - var renewal = false; var order_id = await _certificateDataReader.GetRequestIDBySerialNumber(priorSn); - var expirationDate = _certificateDataReader.GetExpirationDateByRequestId(order_id); - if (expirationDate == null) + + // Determine renew vs reissue based on order expiry window. + // Fetch the live cert record from CSC to get the orderDate, then compute + // orderExpiry = orderDate + 1 year (annual subscription assumption). + // If today falls within RenewalWindowDays of orderExpiry → Renewal (new paid order). + // Otherwise → Reissue (free reissue under the same active order). + var renewal = false; + try + { + var liveCert = await CscGlobalClient.SubmitGetCertificateAsync(order_id[..36]); + if (liveCert != null && DateTime.TryParse(liveCert.OrderDate, out var orderDate)) + { + var orderExpiry = orderDate.AddYears(1); + var daysUntilOrderExpiry = (orderExpiry - DateTime.UtcNow).TotalDays; + renewal = daysUntilOrderExpiry <= RenewalWindowDays; + Logger.LogDebug( + "RenewOrReissue: orderDate={OrderDate}, orderExpiry={OrderExpiry}, daysRemaining={Days}, renewalWindow={Window}, isRenewal={IsRenewal}", + liveCert.OrderDate, orderExpiry.ToString("dd-MMM-yyyy"), + (int)daysUntilOrderExpiry, RenewalWindowDays, renewal); + } + else + { + // Fallback: if we can't parse orderDate, use cert expiration as before + var expirationDate = _certificateDataReader.GetExpirationDateByRequestId(order_id) + ?? (await GetSingleRecord(order_id)).RevocationDate; + renewal = expirationDate < DateTime.Now; + Logger.LogDebug("RenewOrReissue: falling back to cert expiry check, isRenewal={IsRenewal}", renewal); + } + } + catch (Exception ex) { - var localcert = await GetSingleRecord(order_id); - expirationDate = localcert.RevocationDate; + Logger.LogWarning("RenewOrReissue: failed to fetch live cert for order decision, falling back to cert expiry. Error: {Error}", ex.Message); + var expirationDate = _certificateDataReader.GetExpirationDateByRequestId(order_id) + ?? (await GetSingleRecord(order_id)).RevocationDate; + renewal = expirationDate < DateTime.Now; } - if (expirationDate < DateTime.Now) renewal = true; if (renewal) { //One click won't work for this implementation b/c we are missing enrollment params @@ -401,6 +439,13 @@ public Dictionary GetCAConnectorAnnotations() Hidden = false, DefaultValue = "5", Type = "Number" + }, + [Constants.RenewalWindowDays] = new() + { + Comments = "Number of days before the annual order expiry within which a RenewOrReissue triggers a paid Renewal rather than a free Reissue. Default is 30.", + Hidden = false, + DefaultValue = "30", + Type = "Number" } }; } diff --git a/cscglobal-caplugin/Constants.cs b/cscglobal-caplugin/Constants.cs index 4d6b4da..aede084 100644 --- a/cscglobal-caplugin/Constants.cs +++ b/cscglobal-caplugin/Constants.cs @@ -15,6 +15,7 @@ public class Constants public static string DefaultPageSize = "DefaultPageSize"; public static string TemplateSync = "TemplateSync"; public static string SyncFilterDays = "SyncFilterDays"; + public static string RenewalWindowDays = "RenewalWindowDays"; } public class ProductIDs From ea18abf3bdcbc3471868792976bb4a0e22989714 Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Tue, 7 Apr 2026 20:07:31 +0000 Subject: [PATCH 02/29] Update generated docs --- README.md | 13 +++++++------ integration-manifest.json | 4 ++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b7fb319..a83d582 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- CSCGlobal CA Gateway AnyCA Gateway REST Plugin + CSCGlobal CAPlugin AnyCA Gateway REST Plugin

@@ -38,10 +38,10 @@ This integration allows for the Synchronization, Enrollment, and Revocation of c ## Compatibility -The CSCGlobal CA Gateway AnyCA Gateway REST plugin is compatible with the Keyfactor AnyCA Gateway REST 24.2.0 and later. +The CSCGlobal CAPlugin AnyCA Gateway REST plugin is compatible with the Keyfactor AnyCA Gateway REST 24.2.0 and later. ## Support -The CSCGlobal CA Gateway AnyCA Gateway REST plugin is supported by Keyfactor for Keyfactor customers. If you have a support issue, please open a support ticket with your Keyfactor representative. If you have a support issue, please open a support ticket via the Keyfactor Support Portal at https://support.keyfactor.com. +The CSCGlobal CAPlugin AnyCA Gateway REST plugin is supported by Keyfactor for Keyfactor customers. If you have a support issue, please open a support ticket with your Keyfactor representative. If you have a support issue, please open a support ticket via the Keyfactor Support Portal at https://support.keyfactor.com. > To report a problem or suggest a new feature, use the **[Issues](../../issues)** tab. If you want to contribute actual bug fixes or proposed enhancements, use the **[Pull requests](../../pulls)** tab. @@ -53,7 +53,7 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and 1. Install the AnyCA Gateway REST per the [official Keyfactor documentation](https://software.keyfactor.com/Guides/AnyCAGatewayREST/Content/AnyCAGatewayREST/InstallIntroduction.htm). -2. On the server hosting the AnyCA Gateway REST, download and unzip the latest [CSCGlobal CA Gateway AnyCA Gateway REST plugin](https://github.com/Keyfactor/cscglobal-caplugin/releases/latest) from GitHub. +2. On the server hosting the AnyCA Gateway REST, download and unzip the latest [CSCGlobal CAPlugin AnyCA Gateway REST plugin](https://github.com/Keyfactor/cscglobal-caplugin/releases/latest) from GitHub. 3. Copy the unzipped directory (usually called `net6.0` or `net8.0`) to the Extensions directory: @@ -64,11 +64,11 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and Program Files\Keyfactor\AnyCA Gateway\AnyGatewayREST\net8.0\Extensions ``` - > The directory containing the CSCGlobal CA Gateway AnyCA Gateway REST plugin DLLs (`net6.0` or `net8.0`) can be named anything, as long as it is unique within the `Extensions` directory. + > The directory containing the CSCGlobal CAPlugin AnyCA Gateway REST plugin DLLs (`net6.0` or `net8.0`) can be named anything, as long as it is unique within the `Extensions` directory. 4. Restart the AnyCA Gateway REST service. -5. Navigate to the AnyCA Gateway REST portal and verify that the Gateway recognizes the CSCGlobal CA Gateway plugin by hovering over the ⓘ symbol to the right of the Gateway on the top left of the portal. +5. Navigate to the AnyCA Gateway REST portal and verify that the Gateway recognizes the CSCGlobal CAPlugin plugin by hovering over the ⓘ symbol to the right of the Gateway on the top left of the portal. ## Configuration @@ -88,6 +88,7 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and * **DefaultPageSize** - Default page size for use with the API. Default is 100 * **TemplateSync** - Enable template sync. * **SyncFilterDays** - Number of days from today to filter certificates by expiration date during incremental sync. + * **RenewalWindowDays** - Number of days before the annual order expiry within which a RenewOrReissue triggers a paid Renewal rather than a free Reissue. Default is 30. 2. PLEASE NOTE, AT THIS TIME THE RAPID_SSL TEMPLATE IS NOT SUPPORTED BY THE CSC API AND WILL NOT WORK WITH THIS INTEGRATION diff --git a/integration-manifest.json b/integration-manifest.json index 2b4b8c4..9237eab 100644 --- a/integration-manifest.json +++ b/integration-manifest.json @@ -36,6 +36,10 @@ { "name": "SyncFilterDays", "description": "Number of days from today to filter certificates by expiration date during incremental sync." + }, + { + "name": "RenewalWindowDays", + "description": "Number of days before the annual order expiry within which a RenewOrReissue triggers a paid Renewal rather than a free Reissue. Default is 30." } ], "enrollment_config": [ From a742e039bf66653eb51c38a5fa0bcede8063c794 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Wed, 8 Apr 2026 10:44:23 -0400 Subject: [PATCH 03/29] Improved logging .net 10 support --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 861 +++++++++++++++---- cscglobal-caplugin/CSCGlobalCAPlugin.csproj | 8 +- cscglobal-caplugin/Client/CscGlobalClient.cs | 269 ++++-- cscglobal-caplugin/FlowLogger.cs | 241 ++++++ cscglobal-caplugin/RequestManager.cs | 440 ++++++++-- 5 files changed, 1521 insertions(+), 298 deletions(-) create mode 100644 cscglobal-caplugin/FlowLogger.cs diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index 7e6be8a..e0c67ed 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -44,29 +44,94 @@ public CSCGlobalCAPlugin() //done public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDataReader certificateDataReader) { + using var flow = new FlowLogger(Logger, "Initialize"); Logger.MethodEntry(LogLevel.Debug); + Logger.LogTrace("Initialize called. configProvider is {Null}, certificateDataReader is {Null2}", + configProvider == null ? "NULL" : "present", + certificateDataReader == null ? "NULL" : "present"); + + flow.Step("ValidateInputs", () => + { + if (configProvider == null) + throw new ArgumentNullException(nameof(configProvider), "configProvider cannot be null in Initialize"); + if (certificateDataReader == null) + throw new ArgumentNullException(nameof(certificateDataReader), "certificateDataReader cannot be null in Initialize"); + }); + _certificateDataReader = certificateDataReader; - CscGlobalClient = new CscGlobalClient(configProvider); - var templateSync = configProvider.CAConnectionData["TemplateSync"].ToString(); - if (templateSync.ToUpper() == "ON") EnableTemplateSync = true; - if (configProvider.CAConnectionData.ContainsKey(Constants.SyncFilterDays)) + flow.Step("CreateCscGlobalClient", () => + { + Logger.LogTrace("Creating CscGlobalClient from configProvider..."); + CscGlobalClient = new CscGlobalClient(configProvider); + Logger.LogTrace("CscGlobalClient created successfully."); + }); + + flow.Step("ValidateConnectionData", () => { - var syncFilterDaysStr = configProvider.CAConnectionData[Constants.SyncFilterDays]?.ToString(); - if (int.TryParse(syncFilterDaysStr, out var syncFilterDays)) + if (configProvider.CAConnectionData == null) { - SyncFilterDays = syncFilterDays; - Logger.LogDebug($"SyncFilterDays configured to {SyncFilterDays} days"); + Logger.LogError("CAConnectionData is null. Cannot read configuration."); + throw new InvalidOperationException("CAConnectionData is null on configProvider."); } - } + Logger.LogTrace("CAConnectionData keys: {Keys}", string.Join(", ", configProvider.CAConnectionData.Keys)); + }); - RenewalWindowDays = 30; // default - if (configProvider.CAConnectionData.TryGetValue(Constants.RenewalWindowDays, out var renewalWindowObj)) + flow.Step("ReadTemplateSync", () => { - if (int.TryParse(renewalWindowObj?.ToString(), out var renewalWindowDays) && renewalWindowDays > 0) - RenewalWindowDays = renewalWindowDays; - } - Logger.LogDebug("RenewalWindowDays configured to {Days} days", RenewalWindowDays); + if (configProvider.CAConnectionData.ContainsKey("TemplateSync")) + { + var templateSync = configProvider.CAConnectionData["TemplateSync"]?.ToString(); + Logger.LogTrace("TemplateSync raw value: '{Value}'", templateSync ?? "(null)"); + if (!string.IsNullOrEmpty(templateSync) && templateSync.ToUpper() == "ON") + EnableTemplateSync = true; + } + else + { + Logger.LogTrace("TemplateSync key not found in CAConnectionData, defaulting to disabled."); + } + Logger.LogTrace("EnableTemplateSync = {Value}", EnableTemplateSync); + }, $"EnableTemplateSync={EnableTemplateSync}"); + + flow.Step("ReadSyncFilterDays", () => + { + if (configProvider.CAConnectionData.ContainsKey(Constants.SyncFilterDays)) + { + var syncFilterDaysStr = configProvider.CAConnectionData[Constants.SyncFilterDays]?.ToString(); + Logger.LogTrace("SyncFilterDays raw value: '{Value}'", syncFilterDaysStr ?? "(null)"); + if (int.TryParse(syncFilterDaysStr, out var syncFilterDays)) + { + SyncFilterDays = syncFilterDays; + Logger.LogDebug("SyncFilterDays configured to {Days} days", SyncFilterDays); + } + else + { + Logger.LogWarning("SyncFilterDays value '{Value}' could not be parsed as int, using default 0.", syncFilterDaysStr); + } + } + else + { + Logger.LogTrace("SyncFilterDays key not found in CAConnectionData, using default 0."); + } + }); + + flow.Step("ReadRenewalWindowDays", () => + { + RenewalWindowDays = 30; // default + if (configProvider.CAConnectionData.TryGetValue(Constants.RenewalWindowDays, out var renewalWindowObj)) + { + Logger.LogTrace("RenewalWindowDays raw value: '{Value}'", renewalWindowObj?.ToString() ?? "(null)"); + if (int.TryParse(renewalWindowObj?.ToString(), out var renewalWindowDays) && renewalWindowDays > 0) + RenewalWindowDays = renewalWindowDays; + else + Logger.LogWarning("RenewalWindowDays value '{Value}' could not be parsed or was <= 0, using default 30.", renewalWindowObj); + } + else + { + Logger.LogTrace("RenewalWindowDays key not found in CAConnectionData, using default 30."); + } + Logger.LogDebug("RenewalWindowDays configured to {Days} days", RenewalWindowDays); + }, $"RenewalWindowDays={RenewalWindowDays}"); Logger.MethodExit(LogLevel.Debug); } @@ -74,40 +139,97 @@ public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDa //done public async Task GetSingleRecord(string caRequestID) { + using var flow = new FlowLogger(Logger, $"GetSingleRecord({caRequestID ?? "null"})"); + Logger.MethodEntry(LogLevel.Debug); + Logger.LogTrace("GetSingleRecord called with caRequestID='{CaRequestId}'", caRequestID ?? "(null)"); + + flow.Step("ValidateInput", () => + { + if (string.IsNullOrEmpty(caRequestID)) + throw new ArgumentNullException(nameof(caRequestID), "caRequestID cannot be null or empty."); + if (caRequestID.Length < 36) + throw new ArgumentException($"caRequestID '{caRequestID}' is too short to extract a UUID (need at least 36 chars).", nameof(caRequestID)); + }); + try { - Logger.MethodEntry(LogLevel.Debug); - var keyfactorCaId = caRequestID?.Substring(0, 36); //todo fix to use pipe delimiter - Logger.LogTrace($"Keyfactor Ca Id: {keyfactorCaId}"); - var certificateResponse = - Task.Run(async () => await CscGlobalClient.SubmitGetCertificateAsync(keyfactorCaId)) - .Result; + var keyfactorCaId = caRequestID.Substring(0, 36); + flow.Step("ExtractUUID", $"keyfactorCaId={keyfactorCaId}"); - Logger.LogTrace($"Single Cert JSON: {JsonConvert.SerializeObject(certificateResponse)}"); + CertificateResponse certificateResponse = null; + await flow.StepAsync("FetchCertFromCSC", async () => + { + certificateResponse = await CscGlobalClient.SubmitGetCertificateAsync(keyfactorCaId); + }); - var fileContent = - Encoding.ASCII.GetString( - Convert.FromBase64String(certificateResponse?.Certificate ?? string.Empty)); + if (certificateResponse == null) + { + flow.Fail("ParseResponse", "API returned null"); + Logger.LogWarning("GetSingleRecord: SubmitGetCertificateAsync returned null for keyfactorCaId='{KeyfactorCaId}'", keyfactorCaId); + return new AnyCAPluginCertificate + { + CARequestID = keyfactorCaId, + Certificate = string.Empty, + Status = _requestManager.MapReturnStatus(null) + }; + } + + flow.Step("ParseResponse", $"Status={certificateResponse.Status ?? "(null)"}"); + Logger.LogTrace("Single Cert JSON: {Json}", JsonConvert.SerializeObject(certificateResponse)); + + var rawCert = certificateResponse.Certificate ?? string.Empty; + string fileContent = string.Empty; + flow.Step("DecodeBase64", () => + { + try + { + fileContent = Encoding.ASCII.GetString(Convert.FromBase64String(rawCert)); + } + catch (FormatException fex) + { + Logger.LogError(fex, "GetSingleRecord: Failed to decode Base64 certificate content for keyfactorCaId='{KeyfactorCaId}'", keyfactorCaId); + fileContent = string.Empty; + } + }, $"length={rawCert.Length}"); - Logger.LogTrace($"File Content {fileContent}"); - var certData = fileContent?.Replace("\r\n", string.Empty); + var certData = fileContent.Replace("\r\n", string.Empty); var certString = string.Empty; if (!string.IsNullOrEmpty(certData)) - certString = GetEndEntityCertificate(certData); - Logger.LogTrace($"Cert String Content {certString}"); + { + flow.Step("ExtractLeafCert", () => + { + certString = GetEndEntityCertificate(certData); + }, $"inputLength={certData.Length}"); + } + else + { + flow.Skip("ExtractLeafCert", "certData empty after cleanup"); + } + + var mappedStatus = _requestManager.MapReturnStatus(certificateResponse.Status); + flow.Step("MapStatus", $"{certificateResponse.Status ?? "(null)"} -> {mappedStatus}"); Logger.MethodExit(LogLevel.Debug); return new AnyCAPluginCertificate { CARequestID = keyfactorCaId, - Certificate = certString, - Status = _requestManager.MapReturnStatus(certificateResponse?.Status) + Certificate = certString ?? string.Empty, + Status = mappedStatus }; } + catch (AggregateException ae) + { + var inner = ae.Flatten().InnerException; + flow.Fail("UNHANDLED", inner?.Message ?? ae.Message); + Logger.LogError(inner, "GetSingleRecord: AggregateException for caRequestID='{CaRequestId}': {Message}", caRequestID, inner?.Message ?? ae.Message); + throw new Exception($"Error Occurred getting single cert for '{caRequestID}': {inner?.Message ?? ae.Message}", inner ?? ae); + } catch (Exception e) { - throw new Exception($"Error Occurred getting single cert {e.Message}"); + flow.Fail("UNHANDLED", e.Message); + Logger.LogError(e, "GetSingleRecord: Exception for caRequestID='{CaRequestId}': {Message}", caRequestID, e.Message); + throw new Exception($"Error Occurred getting single cert for '{caRequestID}': {e.Message}", e); } } @@ -115,31 +237,56 @@ public async Task GetSingleRecord(string caRequestID) public async Task Synchronize(BlockingCollection blockingBuffer, DateTime? lastSync, bool fullSync, CancellationToken cancelToken) { - Logger.LogTrace($"Full Sync? {fullSync.ToString()}"); + var syncType = fullSync ? "Full" : "Incremental"; + using var flow = new FlowLogger(Logger, $"Synchronize-{syncType}"); Logger.MethodEntry(); + Logger.LogTrace("Synchronize called. fullSync={FullSync}, lastSync={LastSync}, blockingBuffer is {Null}", + fullSync, lastSync?.ToString("o") ?? "(null)", + blockingBuffer == null ? "NULL" : "present"); + + if (blockingBuffer == null) + throw new ArgumentNullException(nameof(blockingBuffer), "blockingBuffer cannot be null in Synchronize"); + try { if (fullSync) { - Logger.LogDebug("Performing full sync - no date filter applied"); - await SyncCertificates(blockingBuffer, cancelToken, null); + flow.Step("DetermineFilter", "Full sync - no date filter"); + await flow.StepAsync("FetchAndProcessCerts", async () => + { + await SyncCertificates(blockingBuffer, cancelToken, null); + }); } else { var filterDays = SyncFilterDays > 0 ? SyncFilterDays : 5; var filterDate = DateTime.Today.Subtract(TimeSpan.FromDays(filterDays)); var dateFilter = filterDate.ToString("yyyy/MM/dd"); - Logger.LogDebug($"Performing incremental sync with expiration date filter: {dateFilter}"); - await SyncCertificates(blockingBuffer, cancelToken, dateFilter); + flow.Step("DetermineFilter", $"Incremental, filterDays={filterDays}, cutoff={dateFilter}"); + await flow.StepAsync("FetchAndProcessCerts", async () => + { + await SyncCertificates(blockingBuffer, cancelToken, dateFilter); + }); } + flow.Step("CompleteAdding"); blockingBuffer.CompleteAdding(); } + catch (OperationCanceledException) + { + flow.Fail("Cancelled", "operation was cancelled"); + Logger.LogWarning("Synchronize: operation was cancelled."); + if (!blockingBuffer.IsAddingCompleted) + blockingBuffer.CompleteAdding(); + throw; + } catch (Exception e) { - Logger.LogError($"Csc Global Synchronize Task failed! {LogHandler.FlattenException(e)}"); + flow.Fail("SyncError", e.Message); + Logger.LogError(e, "Csc Global Synchronize Task failed! {FlatException}", LogHandler.FlattenException(e)); + if (!blockingBuffer.IsAddingCompleted) + blockingBuffer.CompleteAdding(); Logger.MethodExit(); - blockingBuffer.CompleteAdding(); throw; } @@ -149,70 +296,183 @@ public async Task Synchronize(BlockingCollection blockin private async Task SyncCertificates(BlockingCollection blockingBuffer, CancellationToken cancelToken, string? dateFilter) { + Logger.LogTrace("SyncCertificates: calling SubmitCertificateListRequestAsync with dateFilter='{DateFilter}'", dateFilter ?? "(null)"); var certs = await CscGlobalClient.SubmitCertificateListRequestAsync(dateFilter); + if (certs == null) + { + Logger.LogWarning("SyncCertificates: SubmitCertificateListRequestAsync returned null."); + return; + } + + if (certs.Results == null) + { + Logger.LogWarning("SyncCertificates: certificate list response Results collection is null."); + return; + } + + Logger.LogTrace("SyncCertificates: received {Count} certificate results.", certs.Results.Count); + var processedCount = 0; + var skippedCount = 0; + foreach (var currentResponseItem in certs.Results) { cancelToken.ThrowIfCancellationRequested(); - Logger.LogTrace($"Took Certificate ID {currentResponseItem?.Uuid} from Queue"); - var certStatus = _requestManager.MapReturnStatus(currentResponseItem?.Status); - //Keyfactor sync only seems to work when there is a valid cert and I can only get Active valid certs from Csc Global + if (currentResponseItem == null) + { + Logger.LogTrace("SyncCertificates: skipping null result item."); + skippedCount++; + continue; + } + + Logger.LogTrace("SyncCertificates: processing certificate UUID={Uuid}, Status='{Status}', CertificateType='{CertType}'", + currentResponseItem.Uuid ?? "(null)", + currentResponseItem.Status ?? "(null)", + currentResponseItem.CertificateType ?? "(null)"); + + var certStatus = _requestManager.MapReturnStatus(currentResponseItem.Status); + Logger.LogTrace("SyncCertificates: mapped status for UUID={Uuid}: {MappedStatus}", currentResponseItem.Uuid ?? "(null)", certStatus); + if (certStatus == Convert.ToInt32(EndEntityStatus.GENERATED) || certStatus == Convert.ToInt32(EndEntityStatus.REVOKED)) { - //One click renewal/reissue won't work for this implementation so there is an option to disable it by not syncing back template var productId = "CscGlobal"; - if (EnableTemplateSync) productId = currentResponseItem?.CertificateType; + if (EnableTemplateSync) + productId = currentResponseItem.CertificateType ?? "CscGlobal"; - var fileContent = - PreparePemTextFromApi( - currentResponseItem?.Certificate ?? string.Empty); + Logger.LogTrace("SyncCertificates: UUID={Uuid} qualifies for sync. ProductId='{ProductId}'", currentResponseItem.Uuid, productId); + + string fileContent; + try + { + fileContent = PreparePemTextFromApi(currentResponseItem.Certificate ?? string.Empty); + } + catch (Exception ex) + { + Logger.LogError(ex, "SyncCertificates: PreparePemTextFromApi failed for UUID={Uuid}", currentResponseItem.Uuid); + skippedCount++; + continue; + } if (fileContent.Length > 0) { - Logger.LogTrace($"File Content {fileContent}"); + Logger.LogTrace("SyncCertificates: fileContent length={Length} for UUID={Uuid}", fileContent.Length, currentResponseItem.Uuid); var certData = fileContent.Replace("\r\n", string.Empty); - var certString = GetEndEntityCertificate(certData); - if (certString.Length > 0) + string certString; + try + { + certString = GetEndEntityCertificate(certData); + } + catch (Exception ex) + { + Logger.LogError(ex, "SyncCertificates: GetEndEntityCertificate failed for UUID={Uuid}", currentResponseItem.Uuid); + skippedCount++; + continue; + } + + if (!string.IsNullOrEmpty(certString)) + { blockingBuffer.Add(new AnyCAPluginCertificate { - CARequestID = $"{currentResponseItem?.Uuid}", + CARequestID = $"{currentResponseItem.Uuid}", Certificate = certString, Status = certStatus, ProductID = productId }, cancelToken); + processedCount++; + Logger.LogTrace("SyncCertificates: added UUID={Uuid} to buffer.", currentResponseItem.Uuid); + } + else + { + Logger.LogTrace("SyncCertificates: certString was empty for UUID={Uuid}, skipping.", currentResponseItem.Uuid); + skippedCount++; + } } + else + { + Logger.LogTrace("SyncCertificates: fileContent was empty for UUID={Uuid}, skipping.", currentResponseItem.Uuid); + skippedCount++; + } + } + else + { + Logger.LogTrace("SyncCertificates: UUID={Uuid} status {Status} not eligible for sync, skipping.", currentResponseItem.Uuid, certStatus); + skippedCount++; } } + + Logger.LogDebug("SyncCertificates: completed. Processed={Processed}, Skipped={Skipped}, Total={Total}", + processedCount, skippedCount, certs.Results.Count); } //done public async Task Revoke(string caRequestID, string hexSerialNumber, uint revocationReason) { + using var flow = new FlowLogger(Logger, $"Revoke({caRequestID ?? "null"})"); + Logger.MethodEntry(LogLevel.Debug); + Logger.LogTrace("Revoke called with caRequestID='{CaRequestId}', hexSerialNumber='{SerialNumber}', revocationReason={Reason}", + caRequestID ?? "(null)", hexSerialNumber ?? "(null)", revocationReason); + + flow.Step("ValidateInput", () => + { + if (string.IsNullOrEmpty(caRequestID)) + throw new ArgumentNullException(nameof(caRequestID), "caRequestID cannot be null or empty for Revoke."); + if (caRequestID.Length < 36) + throw new ArgumentException($"caRequestID '{caRequestID}' is too short to extract a UUID.", nameof(caRequestID)); + }); + try { - Logger.LogTrace("Staring Revoke Method"); - var revokeResponse = - Task.Run(async () => - await CscGlobalClient.SubmitRevokeCertificateAsync(caRequestID.Substring(0, 36))).Result - ; //todo fix to use pipe delimiter + var uuid = caRequestID.Substring(0, 36); + flow.Step("ExtractUUID", $"uuid={uuid}"); - Logger.LogTrace($"Revoke Response JSON: {JsonConvert.SerializeObject(revokeResponse)}"); - Logger.MethodExit(LogLevel.Debug); + RevokeResponse revokeResponse = null; + await flow.StepAsync("SubmitRevokeToCSC", async () => + { + revokeResponse = await CscGlobalClient.SubmitRevokeCertificateAsync(uuid); + }); + + if (revokeResponse == null) + { + flow.Fail("ParseResponse", "API returned null"); + throw new InvalidOperationException($"Revoke received null response for UUID '{uuid}'."); + } + + Logger.LogTrace("Revoke Response JSON: {Json}", JsonConvert.SerializeObject(revokeResponse)); var revokeResult = _requestManager.GetRevokeResult(revokeResponse); + flow.Step("MapResult", $"result={revokeResult}"); if (revokeResult == (int)EndEntityStatus.FAILED) - if (!string.IsNullOrEmpty(revokeResponse?.RegistrationError?.Description)) - throw new HttpRequestException( - $"Revoke Failed with message {revokeResponse?.RegistrationError?.Description}"); + { + var errorDesc = revokeResponse.RegistrationError?.Description; + flow.Fail("RevokeResult", errorDesc ?? "(no description)"); + Logger.LogError("Revoke: failed for UUID='{Uuid}'. Error description: '{ErrorDesc}'", + uuid, errorDesc ?? "(no description)"); + if (!string.IsNullOrEmpty(errorDesc)) + throw new HttpRequestException($"Revoke Failed with message {errorDesc}"); + } + Logger.MethodExit(LogLevel.Debug); return revokeResult; } + catch (AggregateException ae) + { + var inner = ae.Flatten().InnerException; + flow.Fail("UNHANDLED", inner?.Message ?? ae.Message); + Logger.LogError(inner, "Revoke: AggregateException for caRequestID='{CaRequestId}': {Message}", caRequestID, inner?.Message ?? ae.Message); + throw new Exception($"Revoke Failed for '{caRequestID}' with message {inner?.Message ?? ae.Message}", inner ?? ae); + } + catch (HttpRequestException) + { + throw; // already logged in flow above + } catch (Exception e) { - throw new Exception($"Revoke Failed with message {e?.Message}"); + flow.Fail("UNHANDLED", e.Message); + Logger.LogError(e, "Revoke: Exception for caRequestID='{CaRequestId}': {Message}", caRequestID, e.Message); + throw new Exception($"Revoke Failed for '{caRequestID}' with message {e.Message}", e); } } @@ -220,155 +480,382 @@ await CscGlobalClient.SubmitRevokeCertificateAsync(caRequestID.Substring(0, 36)) public async Task Enroll(string csr, string subject, Dictionary san, EnrollmentProductInfo productInfo, RequestFormat requestFormat, EnrollmentType enrollmentType) { + using var flow = new FlowLogger(Logger, $"Enroll-{enrollmentType}"); Logger.MethodEntry(LogLevel.Debug); + Logger.LogTrace("Enroll called. enrollmentType={EnrollmentType}, subject='{Subject}', productId='{ProductId}', requestFormat={RequestFormat}", + enrollmentType, subject ?? "(null)", + productInfo?.ProductID ?? "(null)", requestFormat); + Logger.LogTrace("Enroll: csr is {CsrStatus}, san has {SanCount} entries, productInfo is {PiStatus}", + string.IsNullOrEmpty(csr) ? "empty/null" : $"present ({csr.Length} chars)", + san?.Count ?? 0, + productInfo == null ? "NULL" : "present"); + + flow.Step("ValidateInputs", () => + { + if (productInfo == null) + throw new ArgumentNullException(nameof(productInfo), "productInfo cannot be null for Enroll."); + if (productInfo.ProductParameters == null) + throw new ArgumentNullException(nameof(productInfo), "productInfo.ProductParameters cannot be null for Enroll."); + if (string.IsNullOrEmpty(csr)) + throw new ArgumentNullException(nameof(csr), "CSR cannot be null or empty for Enroll."); + }); + + Logger.LogTrace("Enroll: ProductParameters keys: [{Keys}]", + string.Join(", ", productInfo.ProductParameters.Keys)); RegistrationRequest enrollmentRequest; var priorSn = ""; ReissueRequest reissueRequest; RenewalRequest renewRequest; - if (productInfo.ProductParameters.ContainsKey("priorcertsn")) - { - priorSn = productInfo.ProductParameters["PriorCertSN"]; - Logger.LogDebug($"Prior cert sn: {priorSn}"); - } - - string uUId; - var customFields = await CscGlobalClient.SubmitGetCustomFields(); - switch (enrollmentType) + flow.Step("CheckPriorCertSN", () => { - case EnrollmentType.New: - Logger.LogTrace("Entering New Enrollment"); - //If they renewed an expired cert it gets here and this will not be supported - IRegistrationResponse enrollmentResponse; - if (!productInfo.ProductParameters.ContainsKey("PriorCertSN")) + if (productInfo.ProductParameters.ContainsKey("priorcertsn")) + { + if (productInfo.ProductParameters.ContainsKey("PriorCertSN")) { - enrollmentRequest = _requestManager.GetRegistrationRequest(productInfo, csr, san, customFields); - Logger.LogTrace($"Enrollment Request JSON: {JsonConvert.SerializeObject(enrollmentRequest)}"); - enrollmentResponse = - Task.Run(async () => await CscGlobalClient.SubmitRegistrationAsync(enrollmentRequest)) - .Result; - Logger.LogTrace($"Enrollment Response JSON: {JsonConvert.SerializeObject(enrollmentResponse)}"); + priorSn = productInfo.ProductParameters["PriorCertSN"]; + Logger.LogDebug("Enroll: Prior cert SN: '{PriorSn}'", priorSn ?? "(null)"); } else { - return new EnrollmentResult - { - Status = 30, //failure - StatusMessage = "You cannot renew an expired cert please perform an new enrollment." - }; + Logger.LogWarning("Enroll: 'priorcertsn' key exists but 'PriorCertSN' (case-sensitive) not found."); } + } + }, string.IsNullOrEmpty(priorSn) ? "none" : $"SN={priorSn}"); - Logger.MethodExit(LogLevel.Debug); - return _requestManager.GetEnrollmentResult(enrollmentResponse); - case EnrollmentType.RenewOrReissue: - Logger.LogTrace("Entering Renew Enrollment"); - var order_id = await _certificateDataReader.GetRequestIDBySerialNumber(priorSn); - - // Determine renew vs reissue based on order expiry window. - // Fetch the live cert record from CSC to get the orderDate, then compute - // orderExpiry = orderDate + 1 year (annual subscription assumption). - // If today falls within RenewalWindowDays of orderExpiry → Renewal (new paid order). - // Otherwise → Reissue (free reissue under the same active order). - var renewal = false; - try - { - var liveCert = await CscGlobalClient.SubmitGetCertificateAsync(order_id[..36]); - if (liveCert != null && DateTime.TryParse(liveCert.OrderDate, out var orderDate)) + string uUId; + List customFields = null; + await flow.StepAsync("FetchCustomFields", async () => + { + customFields = await CscGlobalClient.SubmitGetCustomFields(); + }, $"count={customFields?.Count ?? 0}"); + + if (customFields == null) + { + Logger.LogWarning("Enroll: SubmitGetCustomFields returned null, using empty list."); + customFields = new List(); + } + + try + { + switch (enrollmentType) + { + case EnrollmentType.New: + flow.Step("SelectPath", "New Enrollment"); + IRegistrationResponse enrollmentResponse; + if (!productInfo.ProductParameters.ContainsKey("PriorCertSN")) { - var orderExpiry = orderDate.AddYears(1); - var daysUntilOrderExpiry = (orderExpiry - DateTime.UtcNow).TotalDays; - renewal = daysUntilOrderExpiry <= RenewalWindowDays; - Logger.LogDebug( - "RenewOrReissue: orderDate={OrderDate}, orderExpiry={OrderExpiry}, daysRemaining={Days}, renewalWindow={Window}, isRenewal={IsRenewal}", - liveCert.OrderDate, orderExpiry.ToString("dd-MMM-yyyy"), - (int)daysUntilOrderExpiry, RenewalWindowDays, renewal); + enrollmentRequest = null; + flow.Step("BuildRegistrationRequest", () => + { + enrollmentRequest = _requestManager.GetRegistrationRequest(productInfo, csr, san, customFields); + }); + Logger.LogTrace("Enrollment Request JSON: {Json}", JsonConvert.SerializeObject(enrollmentRequest)); + + RegistrationResponse regResponse = null; + await flow.StepAsync("SubmitRegistrationToCSC", async () => + { + regResponse = await CscGlobalClient.SubmitRegistrationAsync(enrollmentRequest); + }); + enrollmentResponse = regResponse; + + if (enrollmentResponse == null) + { + flow.Fail("ParseResponse", "API returned null"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = "Enrollment failed: CSC API returned a null response." + }; + } + flow.Step("ParseResponse", $"error={enrollmentResponse.RegistrationError != null}"); + Logger.LogTrace("Enrollment Response JSON: {Json}", JsonConvert.SerializeObject(enrollmentResponse)); } else { - // Fallback: if we can't parse orderDate, use cert expiration as before - var expirationDate = _certificateDataReader.GetExpirationDateByRequestId(order_id) - ?? (await GetSingleRecord(order_id)).RevocationDate; - renewal = expirationDate < DateTime.Now; - Logger.LogDebug("RenewOrReissue: falling back to cert expiry check, isRenewal={IsRenewal}", renewal); + flow.Fail("RejectExpiredRenew", "PriorCertSN present on New enrollment"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = "You cannot renew an expired cert please perform an new enrollment." + }; } - } - catch (Exception ex) - { - Logger.LogWarning("RenewOrReissue: failed to fetch live cert for order decision, falling back to cert expiry. Error: {Error}", ex.Message); - var expirationDate = _certificateDataReader.GetExpirationDateByRequestId(order_id) - ?? (await GetSingleRecord(order_id)).RevocationDate; - renewal = expirationDate < DateTime.Now; - } - if (renewal) - { - //One click won't work for this implementation b/c we are missing enrollment params + var enrollResult = _requestManager.GetEnrollmentResult(enrollmentResponse); + flow.Step("MapResult", $"Status={enrollResult?.Status}, ID={enrollResult?.CARequestID ?? "(null)"}"); + Logger.MethodExit(LogLevel.Debug); + return enrollResult; + + case EnrollmentType.RenewOrReissue: + flow.Step("SelectPath", "RenewOrReissue"); + + if (string.IsNullOrEmpty(priorSn)) + { + flow.Fail("ValidatePriorSN", "PriorCertSN is empty"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = "RenewOrReissue failed: PriorCertSN is required but was not provided." + }; + } + + string order_id = null; + await flow.StepAsync("LookupOrderId", async () => + { + order_id = await _certificateDataReader.GetRequestIDBySerialNumber(priorSn); + }, $"orderId={order_id ?? "(null)"}"); + + if (string.IsNullOrEmpty(order_id)) + { + flow.Fail("ValidateOrderId", $"no order found for SN={priorSn}"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = $"RenewOrReissue failed: could not find order ID for serial number '{priorSn}'." + }; + } + + if (order_id.Length < 36) + { + flow.Fail("ValidateOrderId", $"order_id too short ({order_id.Length} chars)"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = $"RenewOrReissue failed: order ID '{order_id}' is too short to extract a UUID." + }; + } + flow.Step("ValidateOrderId", $"orderId={order_id}"); + + // Determine renew vs reissue based on order expiry window. + var renewal = false; + try + { + CertificateResponse liveCert = null; + await flow.StepAsync("FetchLiveCertForDecision", async () => + { + liveCert = await CscGlobalClient.SubmitGetCertificateAsync(order_id[..36]); + }); + + if (liveCert != null && DateTime.TryParse(liveCert.OrderDate, out var orderDate)) + { + var orderExpiry = orderDate.AddYears(1); + var daysUntilOrderExpiry = (orderExpiry - DateTime.UtcNow).TotalDays; + renewal = daysUntilOrderExpiry <= RenewalWindowDays; + flow.Step("ComputeRenewalDecision", + $"orderDate={liveCert.OrderDate}, expiry={orderExpiry:dd-MMM-yyyy}, daysLeft={(int)daysUntilOrderExpiry}, window={RenewalWindowDays}, isRenewal={renewal}"); + } + else + { + flow.Skip("ComputeRenewalDecision", "orderDate unavailable, falling back to cert expiry"); + var expirationDate = _certificateDataReader.GetExpirationDateByRequestId(order_id) + ?? (await GetSingleRecord(order_id)).RevocationDate; + renewal = expirationDate < DateTime.Now; + flow.Step("FallbackExpiryCheck", $"expirationDate={expirationDate?.ToString("o") ?? "(null)"}, isRenewal={renewal}"); + } + } + catch (Exception ex) + { + flow.Fail("FetchLiveCertForDecision", $"falling back: {ex.Message}"); + Logger.LogWarning(ex, "RenewOrReissue: failed to fetch live cert, falling back to cert expiry."); + try + { + var expirationDate = _certificateDataReader.GetExpirationDateByRequestId(order_id) + ?? (await GetSingleRecord(order_id)).RevocationDate; + renewal = expirationDate < DateTime.Now; + flow.Step("FallbackExpiryCheck", $"isRenewal={renewal}"); + } + catch (Exception fallbackEx) + { + flow.Fail("FallbackExpiryCheck", fallbackEx.Message); + return new EnrollmentResult + { + Status = 30, + StatusMessage = $"RenewOrReissue failed: unable to determine renewal status for order '{order_id}'. {fallbackEx.Message}" + }; + } + } + + flow.Step("RenewalDecision", renewal ? "RENEWAL (paid order)" : "REISSUE (free under active order)"); + + if (renewal) + { + if (productInfo.ProductParameters.ContainsKey("Applicant Last Name")) + { + uUId = null; + await flow.StepAsync("LookupRenewalUUID", async () => + { + uUId = await _certificateDataReader.GetRequestIDBySerialNumber( + productInfo.ProductParameters["PriorCertSN"]); + }); + + if (string.IsNullOrEmpty(uUId)) + { + flow.Fail("ValidateRenewalUUID", "could not resolve PriorCertSN"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = "Renewal failed: could not resolve prior certificate serial number to a request ID." + }; + } + flow.Step("ValidateRenewalUUID", $"uuid={uUId}"); + + RenewalRequest builtRenewRequest = null; + flow.Step("BuildRenewalRequest", () => + { + builtRenewRequest = _requestManager.GetRenewalRequest(productInfo, uUId, csr, san, customFields); + }); + renewRequest = builtRenewRequest; + Logger.LogTrace("Renewal Request JSON: {Json}", JsonConvert.SerializeObject(renewRequest)); + + RenewalResponse renewResponse = null; + await flow.StepAsync("SubmitRenewalToCSC", async () => + { + renewResponse = await CscGlobalClient.SubmitRenewalAsync(renewRequest); + }); + + if (renewResponse == null) + { + flow.Fail("ParseRenewalResponse", "API returned null"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = "Renewal failed: CSC API returned a null response." + }; + } + + Logger.LogTrace("Renewal Response JSON: {Json}", JsonConvert.SerializeObject(renewResponse)); + var renewResult = _requestManager.GetRenewResponse(renewResponse); + flow.Step("MapRenewalResult", $"Status={renewResult?.Status}, Message={renewResult?.StatusMessage ?? "(null)"}"); + Logger.MethodExit(LogLevel.Debug); + return renewResult; + } + + flow.Fail("MissingEnrollmentParams", "Applicant Last Name not present — one-click renew unavailable"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = + "One click Renew Is Not Available for this Certificate Type. Use the configure button instead." + }; + } + + // Reissue path if (productInfo.ProductParameters.ContainsKey("Applicant Last Name")) { - //priorCert = _certificateDataReader.get( - //DataConversion.HexToBytes(productInfo.ProductParameters["PriorCertSN"])); - //uUId = priorCert.CARequestID.Substring(0, 36); //uUId is a GUID - uUId = await _certificateDataReader.GetRequestIDBySerialNumber( - productInfo.ProductParameters["PriorCertSN"]); - Logger.LogTrace($"Renew uUId: {uUId}"); - renewRequest = _requestManager.GetRenewalRequest(productInfo, uUId, csr, san, customFields); - Logger.LogTrace($"Renewal Request JSON: {JsonConvert.SerializeObject(renewRequest)}"); - var renewResponse = Task.Run(async () => await CscGlobalClient.SubmitRenewalAsync(renewRequest)) - .Result; - Logger.LogTrace($"Renewal Response JSON: {JsonConvert.SerializeObject(renewResponse)}"); + string requestid = null; + await flow.StepAsync("LookupReissueRequestId", async () => + { + requestid = await _certificateDataReader.GetRequestIDBySerialNumber( + productInfo.ProductParameters["PriorCertSN"]); + }); + + if (string.IsNullOrEmpty(requestid)) + { + flow.Fail("ValidateReissueRequestId", "could not resolve PriorCertSN"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = "Reissue failed: could not resolve prior certificate serial number to a request ID." + }; + } + + if (requestid.Length < 36) + { + flow.Fail("ValidateReissueRequestId", $"requestid too short ({requestid.Length} chars)"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = $"Reissue failed: request ID '{requestid}' is too short to extract a UUID." + }; + } + + uUId = requestid.Substring(0, 36); + flow.Step("ExtractReissueUUID", $"uuid={uUId}"); + + ReissueRequest builtReissueRequest = null; + flow.Step("BuildReissueRequest", () => + { + builtReissueRequest = _requestManager.GetReissueRequest(productInfo, uUId, csr, san, customFields); + }); + reissueRequest = builtReissueRequest; + Logger.LogTrace("Reissue JSON: {Json}", JsonConvert.SerializeObject(reissueRequest)); + + ReissueResponse reissueResponse = null; + await flow.StepAsync("SubmitReissueToCSC", async () => + { + reissueResponse = await CscGlobalClient.SubmitReissueAsync(reissueRequest); + }); + + if (reissueResponse == null) + { + flow.Fail("ParseReissueResponse", "API returned null"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = "Reissue failed: CSC API returned a null response." + }; + } + + Logger.LogTrace("Reissue Response JSON: {Json}", JsonConvert.SerializeObject(reissueResponse)); + var reissueResult = _requestManager.GetReIssueResult(reissueResponse); + flow.Step("MapReissueResult", $"Status={reissueResult?.Status}, Message={reissueResult?.StatusMessage ?? "(null)"}"); Logger.MethodExit(LogLevel.Debug); - return _requestManager.GetRenewResponse(renewResponse); + return reissueResult; } + flow.Fail("MissingEnrollmentParams", "Applicant Last Name not present — one-click reissue unavailable"); return new EnrollmentResult { - Status = 30, //failure + Status = 30, StatusMessage = "One click Renew Is Not Available for this Certificate Type. Use the configure button instead." }; - } - - Logger.LogTrace("Entering Reissue Enrollment"); - //One click won't work for this implementation b/c we are missing enrollment params - if (productInfo.ProductParameters.ContainsKey("Applicant Last Name")) - { - var requestid = await _certificateDataReader.GetRequestIDBySerialNumber( - productInfo.ProductParameters["PriorCertSN"]); - uUId = requestid.Substring(0, 36); //uUId is a GUID - Logger.LogTrace($"Reissue uUId: {uUId}"); - reissueRequest = _requestManager.GetReissueRequest(productInfo, uUId, csr, san, customFields); - Logger.LogTrace($"Reissue JSON: {JsonConvert.SerializeObject(reissueRequest)}"); - var reissueResponse = Task.Run(async () => await CscGlobalClient.SubmitReissueAsync(reissueRequest)) - .Result; - Logger.LogTrace($"Reissue Response JSON: {JsonConvert.SerializeObject(reissueResponse)}"); - Logger.MethodExit(LogLevel.Debug); - return _requestManager.GetReIssueResult(reissueResponse); - } - return new EnrollmentResult - { - Status = 30, //failure - StatusMessage = - "One click Renew Is Not Available for this Certificate Type. Use the configure button instead." - }; + default: + flow.Fail("UnhandledType", $"enrollmentType={enrollmentType}"); + return new EnrollmentResult + { + Status = 30, + StatusMessage = $"Enroll failed: unhandled enrollment type '{enrollmentType}'." + }; + } + } + catch (AggregateException ae) + { + var inner = ae.Flatten().InnerException; + flow.Fail("UNHANDLED", inner?.Message ?? ae.Message); + Logger.LogError(inner, "Enroll: AggregateException during {EnrollmentType}: {Message}", enrollmentType, inner?.Message ?? ae.Message); + return new EnrollmentResult + { + Status = 30, + StatusMessage = $"Enrollment failed with error: {inner?.Message ?? ae.Message}" + }; + } + catch (Exception ex) + { + flow.Fail("UNHANDLED", ex.Message); + Logger.LogError(ex, "Enroll: unhandled exception during {EnrollmentType}: {Message}", enrollmentType, ex.Message); + return new EnrollmentResult + { + Status = 30, + StatusMessage = $"Enrollment failed with error: {ex.Message}" + }; } - - Logger.MethodExit(LogLevel.Debug); - return null; } //done public async Task Ping() { Logger.MethodEntry(); + Logger.LogTrace("Ping: CscGlobalClient is {Null}", CscGlobalClient == null ? "NULL" : "present"); try { Logger.LogInformation("Ping request received"); } catch (Exception e) { - Logger.LogError($"There was an error contacting CSCGlobal: {e.Message}."); + Logger.LogError(e, "There was an error contacting CSCGlobal: {Message}", e.Message); throw new Exception($"Error attempting to ping CSCGlobal: {e.Message}.", e); } @@ -378,19 +865,53 @@ public async Task Ping() //do public async Task ValidateCAConnectionInfo(Dictionary connectionInfo) { + Logger.MethodEntry(LogLevel.Debug); + Logger.LogTrace("ValidateCAConnectionInfo called. connectionInfo is {Null}, keys=[{Keys}]", + connectionInfo == null ? "NULL" : "present", + connectionInfo != null ? string.Join(", ", connectionInfo.Keys) : ""); + + if (connectionInfo == null) + { + Logger.LogError("ValidateCAConnectionInfo: connectionInfo is null."); + throw new ArgumentNullException(nameof(connectionInfo), "connectionInfo cannot be null."); + } + + Logger.MethodExit(LogLevel.Debug); } //do public async Task ValidateProductInfo(EnrollmentProductInfo productInfo, Dictionary connectionInfo) { + Logger.MethodEntry(LogLevel.Debug); + Logger.LogTrace("ValidateProductInfo called. productInfo is {Null}, productId='{ProductId}'", + productInfo == null ? "NULL" : "present", + productInfo?.ProductID ?? "(null)"); + + if (productInfo == null) + { + Logger.LogError("ValidateProductInfo: productInfo is null."); + throw new ArgumentNullException(nameof(productInfo), "productInfo cannot be null."); + } + + if (string.IsNullOrEmpty(productInfo.ProductID)) + { + Logger.LogError("ValidateProductInfo: productInfo.ProductID is null or empty."); + throw new ArgumentException("ProductID cannot be null or empty.", nameof(productInfo)); + } + var certType = ProductIDs.productIds.Find(x => x.Equals(productInfo.ProductID, StringComparison.InvariantCultureIgnoreCase)); - if (certType == null) throw new ArgumentException($"Cannot find {productInfo.ProductID}", "ProductId"); - - Logger.LogInformation($"Validated {certType} ({certType})configured for AnyGateway"); + if (certType == null) + { + Logger.LogError("ValidateProductInfo: cannot find product ID '{ProductId}'. Known IDs: [{KnownIds}]", + productInfo.ProductID, string.Join(", ", ProductIDs.productIds)); + throw new ArgumentException($"Cannot find {productInfo.ProductID}", "ProductId"); + } + Logger.LogInformation("Validated {CertType} configured for AnyGateway", certType); + Logger.MethodExit(LogLevel.Debug); } //done diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.csproj b/cscglobal-caplugin/CSCGlobalCAPlugin.csproj index 5118677..4d71ec5 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.csproj +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.csproj @@ -3,7 +3,7 @@ true - net6.0;net8.0 + net6.0;net8.0;net10.0 Keyfactor.Extensions.CAPlugin.CSCGlobal true enable @@ -23,6 +23,12 @@ + + + + + + diff --git a/cscglobal-caplugin/Client/CscGlobalClient.cs b/cscglobal-caplugin/Client/CscGlobalClient.cs index 0a5c7c5..032f535 100644 --- a/cscglobal-caplugin/Client/CscGlobalClient.cs +++ b/cscglobal-caplugin/Client/CscGlobalClient.cs @@ -23,13 +23,58 @@ public sealed class CscGlobalClient : ICscGlobalClient public CscGlobalClient(IAnyCAPluginConfigProvider config) { - Logger = LogHandler.GetClassLogger(); + Logger = LogHandler.GetClassLogger(); + + if (config == null) + throw new ArgumentNullException(nameof(config), "config cannot be null in CscGlobalClient constructor."); + + if (config.CAConnectionData == null) + throw new InvalidOperationException("CAConnectionData is null on config provider."); + + Logger.LogTrace("CscGlobalClient: CAConnectionData keys=[{Keys}]", string.Join(", ", config.CAConnectionData.Keys)); + if (config.CAConnectionData.ContainsKey(Constants.CscGlobalApiKey)) { - BaseUrl = new Uri(config.CAConnectionData[Constants.CscGlobalUrl].ToString()); - ApiKey = config.CAConnectionData[Constants.CscGlobalApiKey].ToString(); - Authorization = config.CAConnectionData[Constants.BearerToken].ToString(); + var rawUrl = config.CAConnectionData.ContainsKey(Constants.CscGlobalUrl) + ? config.CAConnectionData[Constants.CscGlobalUrl]?.ToString() + : null; + if (string.IsNullOrEmpty(rawUrl)) + { + Logger.LogError("CscGlobalClient: CscGlobalUrl is missing or empty in CAConnectionData."); + throw new InvalidOperationException("CscGlobalUrl is required but was not configured."); + } + + Logger.LogTrace("CscGlobalClient: BaseUrl='{BaseUrl}'", rawUrl); + BaseUrl = new Uri(rawUrl); + + ApiKey = config.CAConnectionData[Constants.CscGlobalApiKey]?.ToString(); + if (string.IsNullOrEmpty(ApiKey)) + { + Logger.LogError("CscGlobalClient: ApiKey is empty or null."); + throw new InvalidOperationException("ApiKey is required but was not configured."); + } + Logger.LogTrace("CscGlobalClient: ApiKey is present (length={Length}).", ApiKey.Length); + + if (!config.CAConnectionData.ContainsKey(Constants.BearerToken)) + { + Logger.LogError("CscGlobalClient: BearerToken key not found in CAConnectionData."); + throw new InvalidOperationException("BearerToken is required but was not configured."); + } + Authorization = config.CAConnectionData[Constants.BearerToken]?.ToString(); + if (string.IsNullOrEmpty(Authorization)) + { + Logger.LogError("CscGlobalClient: BearerToken is empty or null."); + throw new InvalidOperationException("BearerToken is required but was empty."); + } + Logger.LogTrace("CscGlobalClient: BearerToken is present (length={Length}).", Authorization.Length); + RestClient = ConfigureRestClient(); + Logger.LogTrace("CscGlobalClient: RestClient configured successfully."); + } + else + { + Logger.LogError("CscGlobalClient: ApiKey key '{Key}' not found in CAConnectionData. Client will not be functional.", Constants.CscGlobalApiKey); + throw new InvalidOperationException($"Required key '{Constants.CscGlobalApiKey}' not found in CAConnectionData."); } } @@ -41,25 +86,42 @@ public CscGlobalClient(IAnyCAPluginConfigProvider config) public async Task SubmitRegistrationAsync( RegistrationRequest registerRequest) { + Logger.LogTrace("SubmitRegistrationAsync: sending registration request..."); + if (registerRequest == null) + throw new ArgumentNullException(nameof(registerRequest)); + + var requestJson = JsonConvert.SerializeObject(registerRequest); + Logger.LogTrace("SubmitRegistrationAsync: request JSON: {Json}", requestJson); + using (var resp = await RestClient.PostAsync("/dbs/api/v2/tls/registration", new StringContent( - JsonConvert.SerializeObject(registerRequest), Encoding.ASCII, "application/json"))) + requestJson, Encoding.ASCII, "application/json"))) { - Logger.LogTrace(JsonConvert.SerializeObject(registerRequest)); + var rawBody = await resp.Content.ReadAsStringAsync(); + Logger.LogTrace("SubmitRegistrationAsync: HTTP {StatusCode}, body length={Length}", (int)resp.StatusCode, rawBody?.Length ?? 0); + Logger.LogTrace("SubmitRegistrationAsync: response body: {Body}", rawBody ?? "(null)"); + var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; - if (resp.StatusCode == HttpStatusCode.BadRequest) //Csc Sends Errors back in 400 Json Response + if (resp.StatusCode == HttpStatusCode.BadRequest) { - var errorResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync(), - settings); + Logger.LogWarning("SubmitRegistrationAsync: received 400 BadRequest."); + var errorResponse = JsonConvert.DeserializeObject(rawBody ?? "{}", settings); + Logger.LogTrace("SubmitRegistrationAsync: error description='{Desc}'", errorResponse?.Description ?? "(null)"); var response = new RegistrationResponse(); response.RegistrationError = errorResponse; response.Result = null; return response; } - var registrationResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync(), - settings); + if (!resp.IsSuccessStatusCode) + { + Logger.LogError("SubmitRegistrationAsync: unexpected HTTP {StatusCode}: {Body}", (int)resp.StatusCode, rawBody); + throw new HttpRequestException($"SubmitRegistrationAsync failed with HTTP {(int)resp.StatusCode}: {rawBody}"); + } + + var registrationResponse = JsonConvert.DeserializeObject(rawBody ?? "{}", settings); + Logger.LogTrace("SubmitRegistrationAsync: deserialized response. Result is {Null}, RegistrationError is {Null2}", + registrationResponse?.Result == null ? "null" : "present", + registrationResponse?.RegistrationError == null ? "null" : "present"); return registrationResponse; } } @@ -67,31 +129,42 @@ public async Task SubmitRegistrationAsync( public async Task SubmitRenewalAsync( RenewalRequest renewalRequest) { + Logger.LogTrace("SubmitRenewalAsync: sending renewal request..."); + if (renewalRequest == null) + throw new ArgumentNullException(nameof(renewalRequest)); + + var requestJson = JsonConvert.SerializeObject(renewalRequest); + Logger.LogTrace("SubmitRenewalAsync: request JSON: {Json}", requestJson); + using (var resp = await RestClient.PostAsync("/dbs/api/v2/tls/renewal", new StringContent( - JsonConvert.SerializeObject(renewalRequest), Encoding.ASCII, "application/json"))) + requestJson, Encoding.ASCII, "application/json"))) { - Logger.LogTrace(JsonConvert.SerializeObject(renewalRequest)); + var rawBody = await resp.Content.ReadAsStringAsync(); + Logger.LogTrace("SubmitRenewalAsync: HTTP {StatusCode}, body length={Length}", (int)resp.StatusCode, rawBody?.Length ?? 0); + Logger.LogTrace("SubmitRenewalAsync: response body: {Body}", rawBody ?? "(null)"); var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; - if (resp.StatusCode == HttpStatusCode.BadRequest) //Csc Sends Errors back in 400 Json Response - { - var rawErrorResponse = await resp.Content.ReadAsStringAsync(); - Logger.LogTrace("Logging Error Response Raw"); - Logger.LogTrace(rawErrorResponse); - var errorResponse = - JsonConvert.DeserializeObject(rawErrorResponse, - settings); + if (resp.StatusCode == HttpStatusCode.BadRequest) + { + Logger.LogWarning("SubmitRenewalAsync: received 400 BadRequest."); + var errorResponse = JsonConvert.DeserializeObject(rawBody ?? "{}", settings); + Logger.LogTrace("SubmitRenewalAsync: error description='{Desc}'", errorResponse?.Description ?? "(null)"); var response = new RenewalResponse(); response.RegistrationError = errorResponse; response.Result = null; return response; } - var rawRenewResponse = await resp.Content.ReadAsStringAsync(); - Logger.LogTrace("Logging Success Response Raw"); - Logger.LogTrace(rawRenewResponse); - var renewalResponse = - JsonConvert.DeserializeObject(rawRenewResponse); + if (!resp.IsSuccessStatusCode) + { + Logger.LogError("SubmitRenewalAsync: unexpected HTTP {StatusCode}: {Body}", (int)resp.StatusCode, rawBody); + throw new HttpRequestException($"SubmitRenewalAsync failed with HTTP {(int)resp.StatusCode}: {rawBody}"); + } + + var renewalResponse = JsonConvert.DeserializeObject(rawBody ?? "{}"); + Logger.LogTrace("SubmitRenewalAsync: deserialized response. Result is {Null}, RegistrationError is {Null2}", + renewalResponse?.Result == null ? "null" : "present", + renewalResponse?.RegistrationError == null ? "null" : "present"); return renewalResponse; } } @@ -99,69 +172,145 @@ public async Task SubmitRenewalAsync( public async Task SubmitReissueAsync( ReissueRequest reissueRequest) { + Logger.LogTrace("SubmitReissueAsync: sending reissue request..."); + if (reissueRequest == null) + throw new ArgumentNullException(nameof(reissueRequest)); + + var requestJson = JsonConvert.SerializeObject(reissueRequest); + Logger.LogTrace("SubmitReissueAsync: request JSON: {Json}", requestJson); + using (var resp = await RestClient.PostAsync("/dbs/api/v2/tls/reissue", new StringContent( - JsonConvert.SerializeObject(reissueRequest), Encoding.ASCII, "application/json"))) + requestJson, Encoding.ASCII, "application/json"))) { - Logger.LogTrace(JsonConvert.SerializeObject(reissueRequest)); + var rawBody = await resp.Content.ReadAsStringAsync(); + Logger.LogTrace("SubmitReissueAsync: HTTP {StatusCode}, body length={Length}", (int)resp.StatusCode, rawBody?.Length ?? 0); + Logger.LogTrace("SubmitReissueAsync: response body: {Body}", rawBody ?? "(null)"); var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; - if (resp.StatusCode == HttpStatusCode.BadRequest) //Csc Sends Errors back in 400 Json Response + if (resp.StatusCode == HttpStatusCode.BadRequest) { - var errorResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync(), - settings); + Logger.LogWarning("SubmitReissueAsync: received 400 BadRequest."); + var errorResponse = JsonConvert.DeserializeObject(rawBody ?? "{}", settings); + Logger.LogTrace("SubmitReissueAsync: error description='{Desc}'", errorResponse?.Description ?? "(null)"); var response = new ReissueResponse(); response.RegistrationError = errorResponse; response.Result = null; return response; } - var reissueResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync()); + if (!resp.IsSuccessStatusCode) + { + Logger.LogError("SubmitReissueAsync: unexpected HTTP {StatusCode}: {Body}", (int)resp.StatusCode, rawBody); + throw new HttpRequestException($"SubmitReissueAsync failed with HTTP {(int)resp.StatusCode}: {rawBody}"); + } + + var reissueResponse = JsonConvert.DeserializeObject(rawBody ?? "{}"); + Logger.LogTrace("SubmitReissueAsync: deserialized response. Result is {Null}, RegistrationError is {Null2}", + reissueResponse?.Result == null ? "null" : "present", + reissueResponse?.RegistrationError == null ? "null" : "present"); return reissueResponse; } } public async Task SubmitGetCertificateAsync(string certificateId) { + Logger.LogTrace("SubmitGetCertificateAsync: fetching certificate for id='{CertificateId}'", certificateId ?? "(null)"); + + if (string.IsNullOrEmpty(certificateId)) + throw new ArgumentNullException(nameof(certificateId), "certificateId cannot be null or empty."); + using (var resp = await RestClient.GetAsync($"/dbs/api/v2/tls/certificate/{certificateId}")) { - resp.EnsureSuccessStatusCode(); - var getCertificateResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync()); + var rawBody = await resp.Content.ReadAsStringAsync(); + Logger.LogTrace("SubmitGetCertificateAsync: HTTP {StatusCode}, body length={Length}", (int)resp.StatusCode, rawBody?.Length ?? 0); + + if (!resp.IsSuccessStatusCode) + { + Logger.LogError("SubmitGetCertificateAsync: HTTP {StatusCode} for certificateId='{CertificateId}': {Body}", + (int)resp.StatusCode, certificateId, rawBody); + resp.EnsureSuccessStatusCode(); // will throw + } + + Logger.LogTrace("SubmitGetCertificateAsync: response body: {Body}", rawBody ?? "(null)"); + var getCertificateResponse = JsonConvert.DeserializeObject(rawBody ?? "{}"); + Logger.LogTrace("SubmitGetCertificateAsync: deserialized. Status='{Status}', OrderDate='{OrderDate}', Certificate is {Null}", + getCertificateResponse?.Status ?? "(null)", + getCertificateResponse?.OrderDate ?? "(null)", + string.IsNullOrEmpty(getCertificateResponse?.Certificate) ? "empty/null" : "present"); return getCertificateResponse; } } public async Task> SubmitGetCustomFields() { + Logger.LogTrace("SubmitGetCustomFields: fetching custom fields..."); + using (var resp = await RestClient.GetAsync("/dbs/api/v2/admin/customfields")) { - resp.EnsureSuccessStatusCode(); - var getCustomFieldsResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync()); + var rawBody = await resp.Content.ReadAsStringAsync(); + Logger.LogTrace("SubmitGetCustomFields: HTTP {StatusCode}, body length={Length}", (int)resp.StatusCode, rawBody?.Length ?? 0); + + if (!resp.IsSuccessStatusCode) + { + Logger.LogError("SubmitGetCustomFields: HTTP {StatusCode}: {Body}", (int)resp.StatusCode, rawBody); + resp.EnsureSuccessStatusCode(); // will throw + } + + Logger.LogTrace("SubmitGetCustomFields: response body: {Body}", rawBody ?? "(null)"); + var getCustomFieldsResponse = JsonConvert.DeserializeObject(rawBody ?? "{}"); + + if (getCustomFieldsResponse == null) + { + Logger.LogWarning("SubmitGetCustomFields: deserialized response is null, returning empty list."); + return new List(); + } + + if (getCustomFieldsResponse.CustomFields == null) + { + Logger.LogWarning("SubmitGetCustomFields: CustomFields property is null, returning empty list."); + return new List(); + } + + Logger.LogTrace("SubmitGetCustomFields: received {Count} custom fields.", getCustomFieldsResponse.CustomFields.Count); return getCustomFieldsResponse.CustomFields; } } public async Task SubmitRevokeCertificateAsync(string uuId) { + Logger.LogTrace("SubmitRevokeCertificateAsync: revoking certificate UUID='{Uuid}'", uuId ?? "(null)"); + + if (string.IsNullOrEmpty(uuId)) + throw new ArgumentNullException(nameof(uuId), "uuId cannot be null or empty."); + using (var resp = await RestClient.PutAsync($"/dbs/api/v2/tls/revoke/{uuId}", new StringContent(""))) { + var rawBody = await resp.Content.ReadAsStringAsync(); + Logger.LogTrace("SubmitRevokeCertificateAsync: HTTP {StatusCode}, body length={Length}", (int)resp.StatusCode, rawBody?.Length ?? 0); + Logger.LogTrace("SubmitRevokeCertificateAsync: response body: {Body}", rawBody ?? "(null)"); + var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; - if (resp.StatusCode == HttpStatusCode.BadRequest) //Csc Sends Errors back in 400 Json Response + if (resp.StatusCode == HttpStatusCode.BadRequest) { - var errorResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync(), - settings); + Logger.LogWarning("SubmitRevokeCertificateAsync: received 400 BadRequest for UUID='{Uuid}'.", uuId); + var errorResponse = JsonConvert.DeserializeObject(rawBody ?? "{}", settings); + Logger.LogTrace("SubmitRevokeCertificateAsync: error description='{Desc}'", errorResponse?.Description ?? "(null)"); var response = new RevokeResponse(); response.RegistrationError = errorResponse; response.RevokeSuccess = null; return response; } - var getRevokeResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync()); + if (!resp.IsSuccessStatusCode) + { + Logger.LogError("SubmitRevokeCertificateAsync: unexpected HTTP {StatusCode} for UUID='{Uuid}': {Body}", (int)resp.StatusCode, uuId, rawBody); + throw new HttpRequestException($"SubmitRevokeCertificateAsync failed with HTTP {(int)resp.StatusCode}: {rawBody}"); + } + + var getRevokeResponse = JsonConvert.DeserializeObject(rawBody ?? "{}"); + Logger.LogTrace("SubmitRevokeCertificateAsync: deserialized. RevokeSuccess is {Null}, RegistrationError is {Null2}", + getRevokeResponse?.RevokeSuccess == null ? "null" : "present", + getRevokeResponse?.RegistrationError == null ? "null" : "present"); return getRevokeResponse; } } @@ -169,23 +318,37 @@ public async Task SubmitRevokeCertificateAsync(string uuId) public async Task SubmitCertificateListRequestAsync(string? dateFilter = null) { Logger.MethodEntry(LogLevel.Debug); + Logger.LogTrace("SubmitCertificateListRequestAsync: dateFilter='{DateFilter}'", dateFilter ?? "(null)"); + var filterQuery = "filter=status=in=(ACTIVE,REVOKED)"; if (!string.IsNullOrEmpty(dateFilter)) { filterQuery += $";effectiveDate=ge={dateFilter}"; } - Logger.LogTrace($"Certificate list filter query: {filterQuery}"); + Logger.LogTrace("SubmitCertificateListRequestAsync: filter query: {FilterQuery}", filterQuery); + var resp = RestClient.GetAsync($"/dbs/api/v2/tls/certificate?{filterQuery}").Result; + var rawBody = await resp.Content.ReadAsStringAsync(); + Logger.LogTrace("SubmitCertificateListRequestAsync: HTTP {StatusCode}, body length={Length}", (int)resp.StatusCode, rawBody?.Length ?? 0); if (!resp.IsSuccessStatusCode) { - var responseMessage = resp.Content.ReadAsStringAsync().Result; Logger.LogError( - $"Failed Request to Keyfactor. Retrying request. Status Code {resp.StatusCode} | Message: {responseMessage}"); + "SubmitCertificateListRequestAsync: failed request. StatusCode={StatusCode}, Body={Body}", + (int)resp.StatusCode, rawBody); + } + + var certificateListResponse = JsonConvert.DeserializeObject(rawBody ?? "{}"); + + if (certificateListResponse == null) + { + Logger.LogWarning("SubmitCertificateListRequestAsync: deserialized response is null."); + return new CertificateListResponse(); } - var certificateListResponse = - JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync()); + Logger.LogTrace("SubmitCertificateListRequestAsync: Results count={Count}", + certificateListResponse.Results?.Count ?? 0); + Logger.MethodExit(LogLevel.Debug); return certificateListResponse; } diff --git a/cscglobal-caplugin/FlowLogger.cs b/cscglobal-caplugin/FlowLogger.cs new file mode 100644 index 0000000..5696fcd --- /dev/null +++ b/cscglobal-caplugin/FlowLogger.cs @@ -0,0 +1,241 @@ +// Copyright 2021 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.Diagnostics; +using System.Text; +using Microsoft.Extensions.Logging; + +namespace Keyfactor.Extensions.CAPlugin.CSCGlobal; + +public enum FlowStepStatus +{ + Success, + Failed, + Skipped, + InProgress +} + +public class FlowStep +{ + public string Name { get; set; } + public FlowStepStatus Status { get; set; } + public string Detail { get; set; } + public long ElapsedMs { get; set; } + public List Children { get; } = new(); +} + +///

+/// Tracks high-level operation flow and renders a visual step diagram to Trace logs. +/// Usage: +/// using var flow = new FlowLogger(logger, "Enroll-New"); +/// flow.Step("ParseCSR"); +/// flow.Step("ValidateCSR", () => { ... }); +/// flow.Fail("CreateOrder", "API returned 400"); +/// // flow renders automatically on Dispose +/// +public sealed class FlowLogger : IDisposable +{ + private readonly ILogger _logger; + private readonly string _flowName; + private readonly Stopwatch _totalTimer; + private readonly List _steps = new(); + private FlowStep _currentParent; + private bool _disposed; + + public FlowLogger(ILogger logger, string flowName) + { + _logger = logger; + _flowName = flowName; + _totalTimer = Stopwatch.StartNew(); + _logger.LogTrace("===== FLOW START: {FlowName} =====", _flowName); + } + + /// Record a completed step. + public FlowLogger Step(string name, string detail = null) + { + var step = new FlowStep { Name = name, Status = FlowStepStatus.Success, Detail = detail }; + AddStep(step); + _logger.LogTrace(" [{FlowName}] {StepName} ... OK{Detail}", + _flowName, name, detail != null ? $" ({detail})" : ""); + return this; + } + + /// Record a step that executes an action and times it. + public FlowLogger Step(string name, Action action, string detail = null) + { + var sw = Stopwatch.StartNew(); + var step = new FlowStep { Name = name, Detail = detail }; + try + { + _logger.LogTrace(" [{FlowName}] {StepName} ...", _flowName, name); + action(); + sw.Stop(); + step.Status = FlowStepStatus.Success; + step.ElapsedMs = sw.ElapsedMilliseconds; + AddStep(step); + _logger.LogTrace(" [{FlowName}] {StepName} ... OK ({Elapsed}ms){Detail}", + _flowName, name, sw.ElapsedMilliseconds, detail != null ? $" {detail}" : ""); + } + catch (Exception ex) + { + sw.Stop(); + step.Status = FlowStepStatus.Failed; + step.ElapsedMs = sw.ElapsedMilliseconds; + step.Detail = ex.Message; + AddStep(step); + _logger.LogTrace(" [{FlowName}] {StepName} ... FAILED ({Elapsed}ms): {Error}", + _flowName, name, sw.ElapsedMilliseconds, ex.Message); + throw; + } + return this; + } + + /// Record an async step that executes and times it. + public async Task StepAsync(string name, Func action, string detail = null) + { + var sw = Stopwatch.StartNew(); + var step = new FlowStep { Name = name, Detail = detail }; + try + { + _logger.LogTrace(" [{FlowName}] {StepName} ...", _flowName, name); + await action(); + sw.Stop(); + step.Status = FlowStepStatus.Success; + step.ElapsedMs = sw.ElapsedMilliseconds; + AddStep(step); + _logger.LogTrace(" [{FlowName}] {StepName} ... OK ({Elapsed}ms){Detail}", + _flowName, name, sw.ElapsedMilliseconds, detail != null ? $" {detail}" : ""); + } + catch (Exception ex) + { + sw.Stop(); + step.Status = FlowStepStatus.Failed; + step.ElapsedMs = sw.ElapsedMilliseconds; + step.Detail = ex.Message; + AddStep(step); + _logger.LogTrace(" [{FlowName}] {StepName} ... FAILED ({Elapsed}ms): {Error}", + _flowName, name, sw.ElapsedMilliseconds, ex.Message); + throw; + } + return this; + } + + /// Record a failed step without throwing. + public FlowLogger Fail(string name, string reason = null) + { + var step = new FlowStep { Name = name, Status = FlowStepStatus.Failed, Detail = reason }; + AddStep(step); + _logger.LogTrace(" [{FlowName}] {StepName} ... FAILED{Reason}", + _flowName, name, reason != null ? $": {reason}" : ""); + return this; + } + + /// Record a skipped step. + public FlowLogger Skip(string name, string reason = null) + { + var step = new FlowStep { Name = name, Status = FlowStepStatus.Skipped, Detail = reason }; + AddStep(step); + _logger.LogTrace(" [{FlowName}] {StepName} ... SKIPPED{Reason}", + _flowName, name, reason != null ? $": {reason}" : ""); + return this; + } + + /// Start a branch (group of child steps). + public FlowLogger Branch(string name) + { + var step = new FlowStep { Name = name, Status = FlowStepStatus.InProgress }; + AddStep(step); + _currentParent = step; + _logger.LogTrace(" [{FlowName}] >> Branch: {BranchName}", _flowName, name); + return this; + } + + /// End the current branch. + public FlowLogger EndBranch() + { + _currentParent = null; + return this; + } + + private void AddStep(FlowStep step) + { + if (_currentParent != null) + _currentParent.Children.Add(step); + else + _steps.Add(step); + } + + /// Render the visual flow diagram to Trace log. + private string RenderFlow() + { + var sb = new StringBuilder(); + sb.AppendLine(); + sb.AppendLine($" ===== FLOW: {_flowName} ({_totalTimer.ElapsedMilliseconds}ms total) ====="); + sb.AppendLine(); + + for (var i = 0; i < _steps.Count; i++) + { + var step = _steps[i]; + var icon = GetStatusIcon(step.Status); + var elapsed = step.ElapsedMs > 0 ? $" ({step.ElapsedMs}ms)" : ""; + var detail = !string.IsNullOrEmpty(step.Detail) ? $" [{step.Detail}]" : ""; + + sb.AppendLine($" {icon} {step.Name}{elapsed}{detail}"); + + // Render children (branch) + if (step.Children.Count > 0) + { + for (var j = 0; j < step.Children.Count; j++) + { + var child = step.Children[j]; + var childIcon = GetStatusIcon(child.Status); + var childElapsed = child.ElapsedMs > 0 ? $" ({child.ElapsedMs}ms)" : ""; + var childDetail = !string.IsNullOrEmpty(child.Detail) ? $" [{child.Detail}]" : ""; + var connector = j < step.Children.Count - 1 ? "| " : " "; + sb.AppendLine($" |"); + sb.AppendLine($" +-- {childIcon} {child.Name}{childElapsed}{childDetail}"); + } + } + + // Connector between top-level steps + if (i < _steps.Count - 1) + { + sb.AppendLine(" |"); + sb.AppendLine(" v"); + } + } + + sb.AppendLine(); + + // Final status line + var finalStatus = _steps.Count > 0 && _steps.Last().Status == FlowStepStatus.Failed + ? "FAILED" : _steps.Any(s => s.Status == FlowStepStatus.Failed) ? "PARTIAL FAILURE" : "SUCCESS"; + sb.AppendLine($" ===== FLOW RESULT: {finalStatus} ====="); + + return sb.ToString(); + } + + private static string GetStatusIcon(FlowStepStatus status) + { + return status switch + { + FlowStepStatus.Success => "[OK]", + FlowStepStatus.Failed => "[FAIL]", + FlowStepStatus.Skipped => "[SKIP]", + FlowStepStatus.InProgress => "[...]", + _ => "[?]" + }; + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _totalTimer.Stop(); + _logger.LogTrace(RenderFlow()); + } +} diff --git a/cscglobal-caplugin/RequestManager.cs b/cscglobal-caplugin/RequestManager.cs index aa19b1e..b930083 100644 --- a/cscglobal-caplugin/RequestManager.cs +++ b/cscglobal-caplugin/RequestManager.cs @@ -10,19 +10,48 @@ using Keyfactor.AnyGateway.Extensions; using Keyfactor.Extensions.CAPlugin.CSCGlobal.Client.Models; using Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces; +using Keyfactor.Logging; using Keyfactor.PKI.Enums.EJBCA; +using Microsoft.Extensions.Logging; namespace Keyfactor.Extensions.CAPlugin.CSCGlobal; public class RequestManager { + private readonly ILogger Logger = LogHandler.GetClassLogger(); public static Func Pemify = ss => ss.Length <= 64 ? ss : ss.Substring(0, 64) + "\n" + Pemify(ss.Substring(64)); private List GetCustomFields(EnrollmentProductInfo productInfo, List customFields) { + Logger.LogTrace("GetCustomFields: productInfo is {Null}, customFields count={Count}", + productInfo == null ? "NULL" : "present", + customFields?.Count ?? 0); + var customFieldList = new List(); + if (customFields == null || productInfo?.ProductParameters == null) + { + Logger.LogTrace("GetCustomFields: returning empty list (null customFields or ProductParameters)."); + return customFieldList; + } + foreach (var field in customFields) + { + if (field == null) + { + Logger.LogTrace("GetCustomFields: skipping null field entry."); + continue; + } + + Logger.LogTrace("GetCustomFields: checking field Label='{Label}', Mandatory={Mandatory}", + field.Label ?? "(null)", field.Mandatory); + + if (string.IsNullOrEmpty(field.Label)) + { + Logger.LogTrace("GetCustomFields: skipping field with null/empty label."); + continue; + } + if (productInfo.ProductParameters.ContainsKey(field.Label)) { var newField = new CustomField @@ -30,32 +59,58 @@ private List GetCustomFields(EnrollmentProductInfo productInfo, Lis Name = field.Label, Value = productInfo.ProductParameters[field.Label] }; + Logger.LogTrace("GetCustomFields: matched field '{Label}' = '{Value}'", field.Label, newField.Value ?? "(null)"); customFieldList.Add(newField); } else if (field.Mandatory) { + Logger.LogError("GetCustomFields: mandatory field '{Label}' was not supplied. Available keys: [{Keys}]", + field.Label, string.Join(", ", productInfo.ProductParameters.Keys)); throw new Exception( $"Custom field {field.Label} is marked as mandatory, but was not supplied in the request."); } + else + { + Logger.LogTrace("GetCustomFields: optional field '{Label}' not found in ProductParameters, skipping.", field.Label); + } + } + Logger.LogTrace("GetCustomFields: returning {Count} custom fields.", customFieldList.Count); return customFieldList; } public EnrollmentResult GetRenewResponse(RenewalResponse renewResponse) { + Logger.LogTrace("GetRenewResponse: renewResponse is {Null}", renewResponse == null ? "NULL" : "present"); + + if (renewResponse == null) + { + Logger.LogError("GetRenewResponse: renewResponse is null."); + return new EnrollmentResult + { + Status = (int)EndEntityStatus.FAILED, + StatusMessage = "Renewal failed: received null response from CSC." + }; + } + if (renewResponse.RegistrationError != null) + { + Logger.LogWarning("GetRenewResponse: RegistrationError present. Description='{Desc}'", + renewResponse.RegistrationError.Description ?? "(null)"); return new EnrollmentResult { - Status = (int)EndEntityStatus.FAILED, //failure - CARequestID = renewResponse?.Result?.Status?.Uuid, - StatusMessage = renewResponse.RegistrationError.Description + Status = (int)EndEntityStatus.FAILED, + CARequestID = renewResponse.Result?.Status?.Uuid, + StatusMessage = renewResponse.RegistrationError.Description ?? "Renewal failed with unknown error." }; + } + var commonName = renewResponse.Result?.CommonName ?? "(unknown)"; + Logger.LogTrace("GetRenewResponse: renewal succeeded for CommonName='{CommonName}'", commonName); return new EnrollmentResult { - Status = (int)EndEntityStatus.GENERATED, //success - - StatusMessage = $"Renewal Successfully Completed For {renewResponse.Result.CommonName}" + Status = (int)EndEntityStatus.GENERATED, + StatusMessage = $"Renewal Successfully Completed For {commonName}" }; } @@ -64,77 +119,210 @@ public EnrollmentResult GetEnrollmentResult( IRegistrationResponse registrationResponse) { + Logger.LogTrace("GetEnrollmentResult: registrationResponse is {Null}", registrationResponse == null ? "NULL" : "present"); + + if (registrationResponse == null) + { + Logger.LogError("GetEnrollmentResult: registrationResponse is null."); + return new EnrollmentResult + { + Status = (int)EndEntityStatus.FAILED, + StatusMessage = "Enrollment failed: received null response from CSC." + }; + } + if (registrationResponse.RegistrationError != null) + { + Logger.LogWarning("GetEnrollmentResult: RegistrationError present. Description='{Desc}'", + registrationResponse.RegistrationError.Description ?? "(null)"); + return new EnrollmentResult + { + Status = (int)EndEntityStatus.FAILED, + StatusMessage = registrationResponse.RegistrationError.Description ?? "Enrollment failed with unknown error." + }; + } + + if (registrationResponse.Result == null) + { + Logger.LogError("GetEnrollmentResult: Result is null but no RegistrationError present."); return new EnrollmentResult { - Status = (int)EndEntityStatus.FAILED, //failure - StatusMessage = registrationResponse.RegistrationError.Description + Status = (int)EndEntityStatus.FAILED, + StatusMessage = "Enrollment failed: response Result is null." }; + } var cnames = new Dictionary(); if (registrationResponse.Result.DcvDetails != null && registrationResponse.Result.DcvDetails.Count > 0) + { + Logger.LogTrace("GetEnrollmentResult: processing {Count} DcvDetails.", registrationResponse.Result.DcvDetails.Count); foreach (var dcv in registrationResponse.Result.DcvDetails) { + if (dcv == null) + { + Logger.LogTrace("GetEnrollmentResult: skipping null DcvDetail."); + continue; + } + if (dcv.CName != null && !string.IsNullOrEmpty(dcv.CName.Name) && !string.IsNullOrEmpty(dcv.CName.Value)) { - cnames.Add(dcv.CName.Name, dcv.CName.Value); + if (!cnames.ContainsKey(dcv.CName.Name)) + { + Logger.LogTrace("GetEnrollmentResult: adding CName '{Name}'='{Value}'", dcv.CName.Name, dcv.CName.Value); + cnames.Add(dcv.CName.Name, dcv.CName.Value); + } + else + { + Logger.LogTrace("GetEnrollmentResult: duplicate CName key '{Name}', skipping.", dcv.CName.Name); + } } - if (string.IsNullOrEmpty(dcv.Email)) + if (!string.IsNullOrEmpty(dcv.Email)) { - cnames.Add(dcv.Email, dcv.Email); + if (!cnames.ContainsKey(dcv.Email)) + { + Logger.LogTrace("GetEnrollmentResult: adding DCV email '{Email}'", dcv.Email); + cnames.Add(dcv.Email, dcv.Email); + } + else + { + Logger.LogTrace("GetEnrollmentResult: duplicate email key '{Email}', skipping.", dcv.Email); + } } } - + } + else + { + Logger.LogTrace("GetEnrollmentResult: no DcvDetails to process."); + } + + var uuid = registrationResponse.Result.Status?.Uuid; + var commonName = registrationResponse.Result.CommonName ?? "(unknown)"; + Logger.LogTrace("GetEnrollmentResult: success. UUID='{Uuid}', CommonName='{CommonName}', cnames count={Count}", + uuid ?? "(null)", commonName, cnames.Count); + return new EnrollmentResult { - Status = (int)EndEntityStatus.EXTERNALVALIDATION, //success - CARequestID = registrationResponse.Result.Status.Uuid, + Status = (int)EndEntityStatus.EXTERNALVALIDATION, + CARequestID = uuid, StatusMessage = - $"Order Successfully Created With Order Number {registrationResponse.Result.CommonName}", + $"Order Successfully Created With Order Number {commonName}", EnrollmentContext = cnames.Count > 0 ? cnames : null }; } public int GetRevokeResult(IRevokeResponse revokeResponse) { + Logger.LogTrace("GetRevokeResult: revokeResponse is {Null}", revokeResponse == null ? "NULL" : "present"); + + if (revokeResponse == null) + { + Logger.LogError("GetRevokeResult: revokeResponse is null, returning FAILED."); + return (int)EndEntityStatus.FAILED; + } + if (revokeResponse.RegistrationError != null) + { + Logger.LogWarning("GetRevokeResult: RegistrationError present. Description='{Desc}'", + revokeResponse.RegistrationError.Description ?? "(null)"); return (int)EndEntityStatus.FAILED; + } + Logger.LogTrace("GetRevokeResult: returning REVOKED."); return (int)EndEntityStatus.REVOKED; } public EnrollmentResult GetReIssueResult(IReissueResponse reissueResponse) { + Logger.LogTrace("GetReIssueResult: reissueResponse is {Null}", reissueResponse == null ? "NULL" : "present"); + + if (reissueResponse == null) + { + Logger.LogError("GetReIssueResult: reissueResponse is null."); + return new EnrollmentResult + { + Status = (int)EndEntityStatus.FAILED, + StatusMessage = "Reissue failed: received null response from CSC." + }; + } + if (reissueResponse.RegistrationError != null) + { + Logger.LogWarning("GetReIssueResult: RegistrationError present. Description='{Desc}'", + reissueResponse.RegistrationError.Description ?? "(null)"); return new EnrollmentResult { - Status = (int)EndEntityStatus.FAILED, //failure - StatusMessage = reissueResponse.RegistrationError.Description + Status = (int)EndEntityStatus.FAILED, + StatusMessage = reissueResponse.RegistrationError.Description ?? "Reissue failed with unknown error." }; + } + + if (reissueResponse.Result == null) + { + Logger.LogError("GetReIssueResult: Result is null but no RegistrationError present."); + return new EnrollmentResult + { + Status = (int)EndEntityStatus.FAILED, + StatusMessage = "Reissue failed: response Result is null." + }; + } + + var uuid = reissueResponse.Result.Status?.Uuid; + var commonName = reissueResponse.Result.CommonName ?? "(unknown)"; + Logger.LogTrace("GetReIssueResult: success. UUID='{Uuid}', CommonName='{CommonName}'", uuid ?? "(null)", commonName); return new EnrollmentResult { - Status = (int)EndEntityStatus.GENERATED, //success - CARequestID = reissueResponse.Result.Status.Uuid, - StatusMessage = $"Reissue Successfully Completed For {reissueResponse.Result.CommonName}" + Status = (int)EndEntityStatus.GENERATED, + CARequestID = uuid, + StatusMessage = $"Reissue Successfully Completed For {commonName}" }; } public DomainControlValidation GetDomainControlValidation(string methodType, string[] emailAddress, string domainName) { + Logger.LogTrace("GetDomainControlValidation(array): methodType='{MethodType}', domainName='{DomainName}', emailAddress count={Count}", + methodType ?? "(null)", domainName ?? "(null)", emailAddress?.Length ?? 0); + + if (emailAddress == null || emailAddress.Length == 0) + { + Logger.LogTrace("GetDomainControlValidation(array): no email addresses provided, returning null."); + return null; + } + foreach (var address in emailAddress) { - var email = new MailAddress(address); - if (domainName.Contains(email.Host.Split('.')[0])) - return new DomainControlValidation + if (string.IsNullOrEmpty(address)) + { + Logger.LogTrace("GetDomainControlValidation(array): skipping null/empty email address."); + continue; + } + + try + { + var email = new MailAddress(address); + var hostPart = email.Host?.Split('.')[0] ?? ""; + Logger.LogTrace("GetDomainControlValidation(array): checking email='{Email}', hostPart='{HostPart}' against domain='{Domain}'", + address, hostPart, domainName); + + if (!string.IsNullOrEmpty(domainName) && domainName.Contains(hostPart)) { - MethodType = methodType, - EmailAddress = email.ToString() - }; + Logger.LogTrace("GetDomainControlValidation(array): matched! Returning email='{Email}'", email.ToString()); + return new DomainControlValidation + { + MethodType = methodType, + EmailAddress = email.ToString() + }; + } + } + catch (FormatException fex) + { + Logger.LogWarning("GetDomainControlValidation(array): invalid email address '{Address}': {Message}", address, fex.Message); + } } + Logger.LogTrace("GetDomainControlValidation(array): no matching email found, returning null."); return null; } @@ -150,32 +338,42 @@ public DomainControlValidation GetDomainControlValidation(string methodType, str public RegistrationRequest GetRegistrationRequest(EnrollmentProductInfo productInfo, string csr, Dictionary sans, List customFields) { - //var cert = "-----BEGIN CERTIFICATE REQUEST-----\r\n"; - var cert = Pemify(csr); - //cert = cert + "\r\n-----END CERTIFICATE REQUEST-----"; + Logger.LogTrace("GetRegistrationRequest: building registration request. ProductID='{ProductId}'", productInfo?.ProductID ?? "(null)"); + if (productInfo?.ProductParameters == null) + throw new ArgumentNullException(nameof(productInfo), "productInfo or ProductParameters cannot be null."); + if (string.IsNullOrEmpty(csr)) + throw new ArgumentNullException(nameof(csr), "CSR cannot be null or empty."); + var cert = Pemify(csr); var bytes = Encoding.UTF8.GetBytes(cert); var encodedString = Convert.ToBase64String(bytes); - var commonNameValidationEmail = productInfo.ProductParameters["CN DCV Email"]; - var methodType = productInfo.ProductParameters["Domain Control Validation Method"]; + Logger.LogTrace("GetRegistrationRequest: CSR encoded, length={Length}", encodedString.Length); + + var commonNameValidationEmail = productInfo.ProductParameters.ContainsKey("CN DCV Email") + ? productInfo.ProductParameters["CN DCV Email"] : null; + var methodType = productInfo.ProductParameters.ContainsKey("Domain Control Validation Method") + ? productInfo.ProductParameters["Domain Control Validation Method"] : null; var certificateType = GetCertificateType(productInfo.ProductID); + Logger.LogTrace("GetRegistrationRequest: cnDcvEmail='{Email}', methodType='{Method}', certType='{CertType}'", + commonNameValidationEmail ?? "(null)", methodType ?? "(null)", certificateType); + return new RegistrationRequest { Csr = encodedString, - ServerSoftware = "-1", //Just default to other, user does not need to fill this in + ServerSoftware = "-1", CertificateType = certificateType, - Term = productInfo.ProductParameters["Term"], - ApplicantFirstName = productInfo.ProductParameters["Applicant First Name"], - ApplicantLastName = productInfo.ProductParameters["Applicant Last Name"], - ApplicantEmailAddress = productInfo.ProductParameters["Applicant Email Address"], - ApplicantPhoneNumber = productInfo.ProductParameters["Applicant Phone"], + Term = productInfo.ProductParameters.ContainsKey("Term") ? productInfo.ProductParameters["Term"] : null, + ApplicantFirstName = productInfo.ProductParameters.ContainsKey("Applicant First Name") ? productInfo.ProductParameters["Applicant First Name"] : null, + ApplicantLastName = productInfo.ProductParameters.ContainsKey("Applicant Last Name") ? productInfo.ProductParameters["Applicant Last Name"] : null, + ApplicantEmailAddress = productInfo.ProductParameters.ContainsKey("Applicant Email Address") ? productInfo.ProductParameters["Applicant Email Address"] : null, + ApplicantPhoneNumber = productInfo.ProductParameters.ContainsKey("Applicant Phone") ? productInfo.ProductParameters["Applicant Phone"] : null, DomainControlValidation = GetDomainControlValidation(methodType, commonNameValidationEmail), Notifications = GetNotifications(productInfo), - OrganizationContact = productInfo.ProductParameters["Organization Contact"], - BusinessUnit = productInfo.ProductParameters["Business Unit"], - ShowPrice = true, //User should not have to fill this out + OrganizationContact = productInfo.ProductParameters.ContainsKey("Organization Contact") ? productInfo.ProductParameters["Organization Contact"] : null, + BusinessUnit = productInfo.ProductParameters.ContainsKey("Business Unit") ? productInfo.ProductParameters["Business Unit"] : null, + ShowPrice = true, CustomFields = GetCustomFields(productInfo, customFields), SubjectAlternativeNames = certificateType == "2" ? GetSubjectAlternativeNames(productInfo, sans) : null, EvCertificateDetails = certificateType == "3" ? GetEvCertificateDetails(productInfo) : null @@ -213,42 +411,68 @@ private string GetCertificateType(string productId) public Notifications GetNotifications(EnrollmentProductInfo productInfo) { + Logger.LogTrace("GetNotifications: building notifications."); + var emailsRaw = productInfo?.ProductParameters != null + && productInfo.ProductParameters.ContainsKey("Notification Email(s) Comma Separated") + ? productInfo.ProductParameters["Notification Email(s) Comma Separated"] + : null; + + Logger.LogTrace("GetNotifications: raw notification emails='{Emails}'", emailsRaw ?? "(null)"); + + var emailList = !string.IsNullOrEmpty(emailsRaw) + ? emailsRaw.Split(',').Where(e => !string.IsNullOrWhiteSpace(e)).ToList() + : new List(); + + Logger.LogTrace("GetNotifications: parsed {Count} notification emails.", emailList.Count); + return new Notifications { Enabled = true, - AdditionalNotificationEmails = productInfo.ProductParameters["Notification Email(s) Comma Separated"] - .Split(',').ToList() + AdditionalNotificationEmails = emailList }; } public RenewalRequest GetRenewalRequest(EnrollmentProductInfo productInfo, string uUId, string csr, Dictionary sans, List customFields) { - //var cert = "-----BEGIN CERTIFICATE REQUEST-----\r\n"; - var cert = Pemify(csr); - //cert = cert + "\r\n-----END CERTIFICATE REQUEST-----"; + Logger.LogTrace("GetRenewalRequest: building renewal request. UUID='{Uuid}', ProductID='{ProductId}'", + uUId ?? "(null)", productInfo?.ProductID ?? "(null)"); + + if (productInfo?.ProductParameters == null) + throw new ArgumentNullException(nameof(productInfo), "productInfo or ProductParameters cannot be null."); + if (string.IsNullOrEmpty(csr)) + throw new ArgumentNullException(nameof(csr), "CSR cannot be null or empty."); + if (string.IsNullOrEmpty(uUId)) + throw new ArgumentNullException(nameof(uUId), "uUId cannot be null or empty."); + var cert = Pemify(csr); var bytes = Encoding.UTF8.GetBytes(cert); var encodedString = Convert.ToBase64String(bytes); - var commonNameValidationEmail = productInfo.ProductParameters["CN DCV Email"]; - var methodType = productInfo.ProductParameters["Domain Control Validation Method"]; + + var commonNameValidationEmail = productInfo.ProductParameters.ContainsKey("CN DCV Email") + ? productInfo.ProductParameters["CN DCV Email"] : null; + var methodType = productInfo.ProductParameters.ContainsKey("Domain Control Validation Method") + ? productInfo.ProductParameters["Domain Control Validation Method"] : null; var certificateType = GetCertificateType(productInfo.ProductID); + Logger.LogTrace("GetRenewalRequest: cnDcvEmail='{Email}', methodType='{Method}', certType='{CertType}'", + commonNameValidationEmail ?? "(null)", methodType ?? "(null)", certificateType); + return new RenewalRequest { Uuid = uUId, Csr = encodedString, ServerSoftware = "-1", CertificateType = certificateType, - Term = productInfo.ProductParameters["Term"], - ApplicantFirstName = productInfo.ProductParameters["Applicant First Name"], - ApplicantLastName = productInfo.ProductParameters["Applicant Last Name"], - ApplicantEmailAddress = productInfo.ProductParameters["Applicant Email Address"], - ApplicantPhoneNumber = productInfo.ProductParameters["Applicant Phone"], + Term = productInfo.ProductParameters.ContainsKey("Term") ? productInfo.ProductParameters["Term"] : null, + ApplicantFirstName = productInfo.ProductParameters.ContainsKey("Applicant First Name") ? productInfo.ProductParameters["Applicant First Name"] : null, + ApplicantLastName = productInfo.ProductParameters.ContainsKey("Applicant Last Name") ? productInfo.ProductParameters["Applicant Last Name"] : null, + ApplicantEmailAddress = productInfo.ProductParameters.ContainsKey("Applicant Email Address") ? productInfo.ProductParameters["Applicant Email Address"] : null, + ApplicantPhoneNumber = productInfo.ProductParameters.ContainsKey("Applicant Phone") ? productInfo.ProductParameters["Applicant Phone"] : null, DomainControlValidation = GetDomainControlValidation(methodType, commonNameValidationEmail), Notifications = GetNotifications(productInfo), - OrganizationContact = productInfo.ProductParameters["Organization Contact"], - BusinessUnit = productInfo.ProductParameters["Business Unit"], + OrganizationContact = productInfo.ProductParameters.ContainsKey("Organization Contact") ? productInfo.ProductParameters["Organization Contact"] : null, + BusinessUnit = productInfo.ProductParameters.ContainsKey("Business Unit") ? productInfo.ProductParameters["Business Unit"] : null, ShowPrice = true, SubjectAlternativeNames = certificateType == "2" ? GetSubjectAlternativeNames(productInfo, sans) : null, CustomFields = GetCustomFields(productInfo, customFields), @@ -259,54 +483,107 @@ public RenewalRequest GetRenewalRequest(EnrollmentProductInfo productInfo, strin private List GetSubjectAlternativeNames(EnrollmentProductInfo productInfo, Dictionary sans) { + Logger.LogTrace("GetSubjectAlternativeNames: building SANs."); var subjectNameList = new List(); - var methodType = productInfo.ProductParameters["Domain Control Validation Method"]; - foreach (var v in sans["dnsname"]) + if (sans == null || !sans.ContainsKey("dnsname")) + { + Logger.LogTrace("GetSubjectAlternativeNames: no 'dnsname' key in SANs dictionary, returning empty list."); + return subjectNameList; + } + + var dnsNames = sans["dnsname"]; + if (dnsNames == null || dnsNames.Length == 0) { + Logger.LogTrace("GetSubjectAlternativeNames: 'dnsname' array is null or empty, returning empty list."); + return subjectNameList; + } + + var methodType = productInfo?.ProductParameters != null + && productInfo.ProductParameters.ContainsKey("Domain Control Validation Method") + ? productInfo.ProductParameters["Domain Control Validation Method"] + : null; + + Logger.LogTrace("GetSubjectAlternativeNames: processing {Count} DNS names, methodType='{MethodType}'", + dnsNames.Length, methodType ?? "(null)"); + + foreach (var v in dnsNames) + { + if (string.IsNullOrEmpty(v)) + { + Logger.LogTrace("GetSubjectAlternativeNames: skipping null/empty DNS name."); + continue; + } + var domainName = v; var san = new SubjectAlternativeName(); san.DomainName = domainName; - var emailAddresses = productInfo.ProductParameters["Addtl Sans Comma Separated DVC Emails"].Split(','); - if (methodType.ToUpper() == "EMAIL") + Logger.LogTrace("GetSubjectAlternativeNames: processing domain='{Domain}'", domainName); + + if (!string.IsNullOrEmpty(methodType) && methodType.ToUpper() == "EMAIL") + { + var emailsRaw = productInfo.ProductParameters.ContainsKey("Addtl Sans Comma Separated DVC Emails") + ? productInfo.ProductParameters["Addtl Sans Comma Separated DVC Emails"] + : null; + var emailAddresses = !string.IsNullOrEmpty(emailsRaw) ? emailsRaw.Split(',') : Array.Empty(); + Logger.LogTrace("GetSubjectAlternativeNames: EMAIL validation, {Count} email addresses for domain='{Domain}'", + emailAddresses.Length, domainName); san.DomainControlValidation = GetDomainControlValidation(methodType, emailAddresses, domainName); - else //it is a CNAME validation so no email is needed + } + else + { + Logger.LogTrace("GetSubjectAlternativeNames: CNAME/other validation for domain='{Domain}'", domainName); san.DomainControlValidation = GetDomainControlValidation(methodType, ""); + } subjectNameList.Add(san); } + Logger.LogTrace("GetSubjectAlternativeNames: returning {Count} SANs.", subjectNameList.Count); return subjectNameList; } public ReissueRequest GetReissueRequest(EnrollmentProductInfo productInfo, string uUId, string csr, Dictionary sans, List customFields) { - //var cert = "-----BEGIN CERTIFICATE REQUEST-----\r\n"; - var cert = Pemify(csr); - //cert = cert + "\r\n-----END CERTIFICATE REQUEST-----"; + Logger.LogTrace("GetReissueRequest: building reissue request. UUID='{Uuid}', ProductID='{ProductId}'", + uUId ?? "(null)", productInfo?.ProductID ?? "(null)"); + if (productInfo?.ProductParameters == null) + throw new ArgumentNullException(nameof(productInfo), "productInfo or ProductParameters cannot be null."); + if (string.IsNullOrEmpty(csr)) + throw new ArgumentNullException(nameof(csr), "CSR cannot be null or empty."); + if (string.IsNullOrEmpty(uUId)) + throw new ArgumentNullException(nameof(uUId), "uUId cannot be null or empty."); + + var cert = Pemify(csr); var bytes = Encoding.UTF8.GetBytes(cert); var encodedString = Convert.ToBase64String(bytes); - var commonNameValidationEmail = productInfo.ProductParameters["CN DCV Email"]; - var methodType = productInfo.ProductParameters["Domain Control Validation Method"]; + + var commonNameValidationEmail = productInfo.ProductParameters.ContainsKey("CN DCV Email") + ? productInfo.ProductParameters["CN DCV Email"] : null; + var methodType = productInfo.ProductParameters.ContainsKey("Domain Control Validation Method") + ? productInfo.ProductParameters["Domain Control Validation Method"] : null; var certificateType = GetCertificateType(productInfo.ProductID); + Logger.LogTrace("GetReissueRequest: cnDcvEmail='{Email}', methodType='{Method}', certType='{CertType}'", + commonNameValidationEmail ?? "(null)", methodType ?? "(null)", certificateType); + return new ReissueRequest { Uuid = uUId, Csr = encodedString, ServerSoftware = "-1", - CertificateType = GetCertificateType(productInfo.ProductID), - Term = productInfo.ProductParameters["Term"], - ApplicantFirstName = productInfo.ProductParameters["Applicant First Name"], - ApplicantLastName = productInfo.ProductParameters["Applicant Last Name"], - ApplicantEmailAddress = productInfo.ProductParameters["Applicant Email Address"], - ApplicantPhoneNumber = productInfo.ProductParameters["Applicant Phone"], + CertificateType = certificateType, + Term = productInfo.ProductParameters.ContainsKey("Term") ? productInfo.ProductParameters["Term"] : null, + ApplicantFirstName = productInfo.ProductParameters.ContainsKey("Applicant First Name") ? productInfo.ProductParameters["Applicant First Name"] : null, + ApplicantLastName = productInfo.ProductParameters.ContainsKey("Applicant Last Name") ? productInfo.ProductParameters["Applicant Last Name"] : null, + ApplicantEmailAddress = productInfo.ProductParameters.ContainsKey("Applicant Email Address") ? productInfo.ProductParameters["Applicant Email Address"] : null, + ApplicantPhoneNumber = productInfo.ProductParameters.ContainsKey("Applicant Phone") ? productInfo.ProductParameters["Applicant Phone"] : null, DomainControlValidation = GetDomainControlValidation(methodType, commonNameValidationEmail), Notifications = GetNotifications(productInfo), - OrganizationContact = productInfo.ProductParameters["Organization Contact"], - BusinessUnit = productInfo.ProductParameters["Business Unit"], + OrganizationContact = productInfo.ProductParameters.ContainsKey("Organization Contact") ? productInfo.ProductParameters["Organization Contact"] : null, + BusinessUnit = productInfo.ProductParameters.ContainsKey("Business Unit") ? productInfo.ProductParameters["Business Unit"] : null, ShowPrice = true, SubjectAlternativeNames = certificateType == "2" ? GetSubjectAlternativeNames(productInfo, sans) : null, CustomFields = GetCustomFields(productInfo, customFields), @@ -316,15 +593,28 @@ public ReissueRequest GetReissueRequest(EnrollmentProductInfo productInfo, strin private EvCertificateDetails GetEvCertificateDetails(EnrollmentProductInfo productInfo) { + Logger.LogTrace("GetEvCertificateDetails: building EV details."); + var country = productInfo?.ProductParameters != null + && productInfo.ProductParameters.ContainsKey("Organization Country") + ? productInfo.ProductParameters["Organization Country"] + : null; + Logger.LogTrace("GetEvCertificateDetails: country='{Country}'", country ?? "(null)"); var evDetails = new EvCertificateDetails(); - evDetails.Country = productInfo.ProductParameters["Organization Country"]; + evDetails.Country = country; return evDetails; } public int MapReturnStatus(string cscGlobalStatus) { - var returnStatus = 0; + Logger.LogTrace("MapReturnStatus: input status='{Status}'", cscGlobalStatus ?? "(null)"); + + if (string.IsNullOrEmpty(cscGlobalStatus)) + { + Logger.LogWarning("MapReturnStatus: status is null or empty, returning FAILED."); + return (int)EndEntityStatus.FAILED; + } + int returnStatus; switch (cscGlobalStatus) { case "ACTIVE": @@ -340,10 +630,12 @@ public int MapReturnStatus(string cscGlobalStatus) returnStatus = (int)EndEntityStatus.REVOKED; break; default: + Logger.LogWarning("MapReturnStatus: unrecognized status '{Status}', returning FAILED.", cscGlobalStatus); returnStatus = (int)EndEntityStatus.FAILED; break; } + Logger.LogTrace("MapReturnStatus: mapped '{Status}' to {Result}", cscGlobalStatus, returnStatus); return returnStatus; } } \ No newline at end of file From fba58ac0fa3980e556f48a6ab852c806ce5e04b8 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Wed, 8 Apr 2026 12:23:02 -0400 Subject: [PATCH 04/29] Removed Template Sync Logic --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 29 +------------------------ cscglobal-caplugin/Constants.cs | 1 - 2 files changed, 1 insertion(+), 29 deletions(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index e0c67ed..a4bcb47 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -35,8 +35,6 @@ public CSCGlobalCAPlugin() private ICscGlobalClient CscGlobalClient { get; set; } - public bool EnableTemplateSync { get; set; } - public int SyncFilterDays { get; set; } public int RenewalWindowDays { get; set; } @@ -77,22 +75,6 @@ public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDa Logger.LogTrace("CAConnectionData keys: {Keys}", string.Join(", ", configProvider.CAConnectionData.Keys)); }); - flow.Step("ReadTemplateSync", () => - { - if (configProvider.CAConnectionData.ContainsKey("TemplateSync")) - { - var templateSync = configProvider.CAConnectionData["TemplateSync"]?.ToString(); - Logger.LogTrace("TemplateSync raw value: '{Value}'", templateSync ?? "(null)"); - if (!string.IsNullOrEmpty(templateSync) && templateSync.ToUpper() == "ON") - EnableTemplateSync = true; - } - else - { - Logger.LogTrace("TemplateSync key not found in CAConnectionData, defaulting to disabled."); - } - Logger.LogTrace("EnableTemplateSync = {Value}", EnableTemplateSync); - }, $"EnableTemplateSync={EnableTemplateSync}"); - flow.Step("ReadSyncFilterDays", () => { if (configProvider.CAConnectionData.ContainsKey(Constants.SyncFilterDays)) @@ -337,9 +319,7 @@ private async Task SyncCertificates(BlockingCollection b if (certStatus == Convert.ToInt32(EndEntityStatus.GENERATED) || certStatus == Convert.ToInt32(EndEntityStatus.REVOKED)) { - var productId = "CscGlobal"; - if (EnableTemplateSync) - productId = currentResponseItem.CertificateType ?? "CscGlobal"; + var productId = currentResponseItem.CertificateType ?? "CscGlobal"; Logger.LogTrace("SyncCertificates: UUID={Uuid} qualifies for sync. ProductId='{ProductId}'", currentResponseItem.Uuid, productId); @@ -947,13 +927,6 @@ public Dictionary GetCAConnectorAnnotations() DefaultValue = "100", Type = "String" }, - [Constants.TemplateSync] = new() - { - Comments = "Enable template sync.", - Hidden = false, - DefaultValue = "false", - Type = "Bool" - }, [Constants.SyncFilterDays] = new() { Comments = "Number of days from today to filter certificates by expiration date during incremental sync.", diff --git a/cscglobal-caplugin/Constants.cs b/cscglobal-caplugin/Constants.cs index aede084..d53fa61 100644 --- a/cscglobal-caplugin/Constants.cs +++ b/cscglobal-caplugin/Constants.cs @@ -13,7 +13,6 @@ public class Constants public static string CscGlobalApiKey = "ApiKey"; public static string BearerToken = "BearerToken"; public static string DefaultPageSize = "DefaultPageSize"; - public static string TemplateSync = "TemplateSync"; public static string SyncFilterDays = "SyncFilterDays"; public static string RenewalWindowDays = "RenewalWindowDays"; } From 58177dffc314efaa6fef26148b10dadf85c4b75d Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Wed, 8 Apr 2026 16:24:46 +0000 Subject: [PATCH 05/29] Update generated docs --- README.md | 1 - integration-manifest.json | 4 ---- 2 files changed, 5 deletions(-) diff --git a/README.md b/README.md index a83d582..10b6189 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,6 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and * **ApiKey** - CSCGlobal API Key * **BearerToken** - CSCGlobal Bearer Token * **DefaultPageSize** - Default page size for use with the API. Default is 100 - * **TemplateSync** - Enable template sync. * **SyncFilterDays** - Number of days from today to filter certificates by expiration date during incremental sync. * **RenewalWindowDays** - Number of days before the annual order expiry within which a RenewOrReissue triggers a paid Renewal rather than a free Reissue. Default is 30. diff --git a/integration-manifest.json b/integration-manifest.json index 9237eab..bab6aae 100644 --- a/integration-manifest.json +++ b/integration-manifest.json @@ -29,10 +29,6 @@ "name": "DefaultPageSize", "description": "Default page size for use with the API. Default is 100" }, - { - "name": "TemplateSync", - "description": "Enable template sync." - }, { "name": "SyncFilterDays", "description": "Number of days from today to filter certificates by expiration date during incremental sync." From b8d74db5017c2ea2d9a43f5b22cdb95f60c0040d Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Wed, 8 Apr 2026 14:25:32 -0400 Subject: [PATCH 06/29] fixed template mapping issue --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 5 +- cscglobal-caplugin/RequestManager.cs | 89 +++++++++++++++++++------ 2 files changed, 70 insertions(+), 24 deletions(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index a4bcb47..5449f64 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -319,9 +319,10 @@ private async Task SyncCertificates(BlockingCollection b if (certStatus == Convert.ToInt32(EndEntityStatus.GENERATED) || certStatus == Convert.ToInt32(EndEntityStatus.REVOKED)) { - var productId = currentResponseItem.CertificateType ?? "CscGlobal"; + var productId = _requestManager.MapCertificateTypeToProductId(currentResponseItem.CertificateType); - Logger.LogTrace("SyncCertificates: UUID={Uuid} qualifies for sync. ProductId='{ProductId}'", currentResponseItem.Uuid, productId); + Logger.LogTrace("SyncCertificates: UUID={Uuid} qualifies for sync. CertificateType='{CertType}' -> ProductId='{ProductId}'", + currentResponseItem.Uuid, currentResponseItem.CertificateType ?? "(null)", productId); string fileContent; try diff --git a/cscglobal-caplugin/RequestManager.cs b/cscglobal-caplugin/RequestManager.cs index b930083..85e9b38 100644 --- a/cscglobal-caplugin/RequestManager.cs +++ b/cscglobal-caplugin/RequestManager.cs @@ -380,35 +380,80 @@ public RegistrationRequest GetRegistrationRequest(EnrollmentProductInfo productI }; } + // Maps Keyfactor product ID -> CSC API certificate type code (used for enrollment requests) + private static readonly Dictionary ProductIdToCodeMap = new(StringComparer.OrdinalIgnoreCase) + { + ["CSC TrustedSecure Premium Certificate"] = "0", + ["CSC TrustedSecure Premium Wildcard Certificate"] = "1", + ["CSC TrustedSecure UC Certificate"] = "2", + ["CSC TrustedSecure EV Certificate"] = "3", + ["CSC TrustedSecure Domain Validated SSL"] = "4", + ["CSC Trusted Secure Domain Validated SSL"] = "4", + ["CSC TrustedSecure Domain Validated Wildcard SSL"] = "5", + ["CSC Trusted Secure Domain Validated Wildcard SSL"] = "5", + ["CSC TrustedSecure Domain Validated UC Certificate"] = "6", + ["CSC Trusted Secure Domain Validated UC Certificate"] = "6", + }; + + // Reverse map: CSC API certificate type string -> Keyfactor product ID (used during sync) + // CSC may return numeric codes ("0","1") or descriptive strings ("Premium","EV","UC", etc.) + private static readonly Dictionary CodeToProductIdMap = new(StringComparer.OrdinalIgnoreCase) + { + ["0"] = "CSC TrustedSecure Premium Certificate", + ["Premium"] = "CSC TrustedSecure Premium Certificate", + ["CSC TrustedSecure Premium Certificate"] = "CSC TrustedSecure Premium Certificate", + ["1"] = "CSC TrustedSecure Premium Wildcard Certificate", + ["Wildcard"] = "CSC TrustedSecure Premium Wildcard Certificate", + ["Premium Wildcard"] = "CSC TrustedSecure Premium Wildcard Certificate", + ["CSC TrustedSecure Premium Wildcard Certificate"] = "CSC TrustedSecure Premium Wildcard Certificate", + ["2"] = "CSC TrustedSecure UC Certificate", + ["UC"] = "CSC TrustedSecure UC Certificate", + ["CSC TrustedSecure UC Certificate"] = "CSC TrustedSecure UC Certificate", + ["3"] = "CSC TrustedSecure EV Certificate", + ["EV"] = "CSC TrustedSecure EV Certificate", + ["CSC TrustedSecure EV Certificate"] = "CSC TrustedSecure EV Certificate", + ["4"] = "CSC TrustedSecure Domain Validated SSL", + ["DV"] = "CSC TrustedSecure Domain Validated SSL", + ["Domain Validated SSL"] = "CSC TrustedSecure Domain Validated SSL", + ["CSC TrustedSecure Domain Validated SSL"] = "CSC TrustedSecure Domain Validated SSL", + ["5"] = "CSC TrustedSecure Domain Validated Wildcard SSL", + ["DV Wildcard"] = "CSC TrustedSecure Domain Validated Wildcard SSL", + ["Domain Validated Wildcard SSL"] = "CSC TrustedSecure Domain Validated Wildcard SSL", + ["CSC TrustedSecure Domain Validated Wildcard SSL"] = "CSC TrustedSecure Domain Validated Wildcard SSL", + ["6"] = "CSC TrustedSecure Domain Validated UC Certificate", + ["DV UC"] = "CSC TrustedSecure Domain Validated UC Certificate", + ["Domain Validated UC Certificate"] = "CSC TrustedSecure Domain Validated UC Certificate", + ["CSC TrustedSecure Domain Validated UC Certificate"] = "CSC TrustedSecure Domain Validated UC Certificate", + }; + private string GetCertificateType(string productId) { - switch (productId) + Logger.LogTrace("GetCertificateType: productId='{ProductId}'", productId ?? "(null)"); + if (!string.IsNullOrEmpty(productId) && ProductIdToCodeMap.TryGetValue(productId, out var code)) { - case "CSC TrustedSecure Premium Certificate": - return "0"; - case "CSC TrustedSecure EV Certificate": - return "3"; - case "CSC TrustedSecure UC Certificate": - return "2"; - case "CSC TrustedSecure Premium Wildcard Certificate": - return "1"; - case "CSC Trusted Secure Domain Validated SSL": - return "4"; - case "CSC Trusted Secure Domain Validated Wildcard SSL": - return "5"; - case "CSC Trusted Secure Domain Validated UC Certificate": - return "6"; - case "CSC TrustedSecure Domain Validated SSL": - return "4"; - case "CSC TrustedSecure Domain Validated Wildcard SSL": - return "5"; - case "CSC TrustedSecure Domain Validated UC Certificate": - return "6"; + Logger.LogTrace("GetCertificateType: mapped '{ProductId}' -> '{Code}'", productId, code); + return code; } - + Logger.LogWarning("GetCertificateType: no mapping found for '{ProductId}', returning -1.", productId); return "-1"; } + /// + /// Maps a CSC API certificateType value back to a Keyfactor product ID. + /// Handles numeric codes, descriptive strings, and passthrough of already-correct values. + /// + public string MapCertificateTypeToProductId(string cscCertificateType) + { + Logger.LogTrace("MapCertificateTypeToProductId: input='{CscCertType}'", cscCertificateType ?? "(null)"); + if (!string.IsNullOrEmpty(cscCertificateType) && CodeToProductIdMap.TryGetValue(cscCertificateType, out var productId)) + { + Logger.LogTrace("MapCertificateTypeToProductId: mapped '{CscCertType}' -> '{ProductId}'", cscCertificateType, productId); + return productId; + } + Logger.LogWarning("MapCertificateTypeToProductId: no mapping for '{CscCertType}', passing through as-is.", cscCertificateType); + return cscCertificateType ?? "CscGlobal"; + } + public Notifications GetNotifications(EnrollmentProductInfo productInfo) { Logger.LogTrace("GetNotifications: building notifications."); From 0b6f8a5ab9b30d6153dc217abc67bbc689b01486 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Wed, 8 Apr 2026 16:28:25 -0400 Subject: [PATCH 07/29] product fixes --- cscglobal-caplugin/Constants.cs | 4 +-- cscglobal-caplugin/RequestManager.cs | 42 +++++++++++++++------------- 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/cscglobal-caplugin/Constants.cs b/cscglobal-caplugin/Constants.cs index d53fa61..d588706 100644 --- a/cscglobal-caplugin/Constants.cs +++ b/cscglobal-caplugin/Constants.cs @@ -26,8 +26,8 @@ public class ProductIDs "CSC TrustedSecure UC Certificate", "CSC TrustedSecure Premium Wildcard Certificate", "CSC TrustedSecure Domain Validated SSL", - "CSC TrustedSecure Domain Validated Wildcard SSL", - "CSC TrustedSecure Domain Validated UC Certificate" + "CSC Trusted Secure Domain Validated Wildcard SSL", + "CSC Trusted Secure Domain Validated UC Certificate" }; } diff --git a/cscglobal-caplugin/RequestManager.cs b/cscglobal-caplugin/RequestManager.cs index 85e9b38..4e3a7ac 100644 --- a/cscglobal-caplugin/RequestManager.cs +++ b/cscglobal-caplugin/RequestManager.cs @@ -389,41 +389,45 @@ public RegistrationRequest GetRegistrationRequest(EnrollmentProductInfo productI ["CSC TrustedSecure EV Certificate"] = "3", ["CSC TrustedSecure Domain Validated SSL"] = "4", ["CSC Trusted Secure Domain Validated SSL"] = "4", - ["CSC TrustedSecure Domain Validated Wildcard SSL"] = "5", ["CSC Trusted Secure Domain Validated Wildcard SSL"] = "5", - ["CSC TrustedSecure Domain Validated UC Certificate"] = "6", ["CSC Trusted Secure Domain Validated UC Certificate"] = "6", }; - // Reverse map: CSC API certificate type string -> Keyfactor product ID (used during sync) - // CSC may return numeric codes ("0","1") or descriptive strings ("Premium","EV","UC", etc.) + // Reverse map: CSC API certificateType string -> Keyfactor product ID (used during sync) + // Note: CSC naming is inconsistent — first 4 types use "TrustedSecure" (no space), + // DV Wildcard and DV UC use "Trusted Secure" (with space), + // but CSC API returns DV SSL as "CSC Trusted Secure Domain Validated SSL" (with space) + // while the product ID is "CSC TrustedSecure Domain Validated SSL" (no space). private static readonly Dictionary CodeToProductIdMap = new(StringComparer.OrdinalIgnoreCase) { + // Premium ["0"] = "CSC TrustedSecure Premium Certificate", - ["Premium"] = "CSC TrustedSecure Premium Certificate", ["CSC TrustedSecure Premium Certificate"] = "CSC TrustedSecure Premium Certificate", + ["CSC Trusted Secure Premium Certificate"] = "CSC TrustedSecure Premium Certificate", + // Premium Wildcard ["1"] = "CSC TrustedSecure Premium Wildcard Certificate", - ["Wildcard"] = "CSC TrustedSecure Premium Wildcard Certificate", - ["Premium Wildcard"] = "CSC TrustedSecure Premium Wildcard Certificate", ["CSC TrustedSecure Premium Wildcard Certificate"] = "CSC TrustedSecure Premium Wildcard Certificate", + ["CSC Trusted Secure Premium Wildcard Certificate"] = "CSC TrustedSecure Premium Wildcard Certificate", + // UC ["2"] = "CSC TrustedSecure UC Certificate", - ["UC"] = "CSC TrustedSecure UC Certificate", ["CSC TrustedSecure UC Certificate"] = "CSC TrustedSecure UC Certificate", + ["CSC Trusted Secure UC Certificate"] = "CSC TrustedSecure UC Certificate", + // EV ["3"] = "CSC TrustedSecure EV Certificate", - ["EV"] = "CSC TrustedSecure EV Certificate", ["CSC TrustedSecure EV Certificate"] = "CSC TrustedSecure EV Certificate", + ["CSC Trusted Secure EV Certificate"] = "CSC TrustedSecure EV Certificate", + // DV SSL — product ID has no space, but CSC API returns with space ["4"] = "CSC TrustedSecure Domain Validated SSL", - ["DV"] = "CSC TrustedSecure Domain Validated SSL", - ["Domain Validated SSL"] = "CSC TrustedSecure Domain Validated SSL", ["CSC TrustedSecure Domain Validated SSL"] = "CSC TrustedSecure Domain Validated SSL", - ["5"] = "CSC TrustedSecure Domain Validated Wildcard SSL", - ["DV Wildcard"] = "CSC TrustedSecure Domain Validated Wildcard SSL", - ["Domain Validated Wildcard SSL"] = "CSC TrustedSecure Domain Validated Wildcard SSL", - ["CSC TrustedSecure Domain Validated Wildcard SSL"] = "CSC TrustedSecure Domain Validated Wildcard SSL", - ["6"] = "CSC TrustedSecure Domain Validated UC Certificate", - ["DV UC"] = "CSC TrustedSecure Domain Validated UC Certificate", - ["Domain Validated UC Certificate"] = "CSC TrustedSecure Domain Validated UC Certificate", - ["CSC TrustedSecure Domain Validated UC Certificate"] = "CSC TrustedSecure Domain Validated UC Certificate", + ["CSC Trusted Secure Domain Validated SSL"] = "CSC TrustedSecure Domain Validated SSL", + // DV Wildcard — product ID has space (matches CSC API) + ["5"] = "CSC Trusted Secure Domain Validated Wildcard SSL", + ["CSC Trusted Secure Domain Validated Wildcard SSL"] = "CSC Trusted Secure Domain Validated Wildcard SSL", + ["CSC TrustedSecure Domain Validated Wildcard SSL"] = "CSC Trusted Secure Domain Validated Wildcard SSL", + // DV UC — product ID has space (matches CSC API) + ["6"] = "CSC Trusted Secure Domain Validated UC Certificate", + ["CSC Trusted Secure Domain Validated UC Certificate"] = "CSC Trusted Secure Domain Validated UC Certificate", + ["CSC TrustedSecure Domain Validated UC Certificate"] = "CSC Trusted Secure Domain Validated UC Certificate", }; private string GetCertificateType(string productId) From 445eb57e40b20de2723f6190e7e0ce11d2bea170 Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Wed, 8 Apr 2026 20:30:35 +0000 Subject: [PATCH 08/29] Update generated docs --- integration-manifest.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/integration-manifest.json b/integration-manifest.json index bab6aae..71d13f4 100644 --- a/integration-manifest.json +++ b/integration-manifest.json @@ -94,8 +94,8 @@ "CSC TrustedSecure UC Certificate", "CSC TrustedSecure Premium Wildcard Certificate", "CSC TrustedSecure Domain Validated SSL", - "CSC TrustedSecure Domain Validated Wildcard SSL", - "CSC TrustedSecure Domain Validated UC Certificate" + "CSC Trusted Secure Domain Validated Wildcard SSL", + "CSC Trusted Secure Domain Validated UC Certificate" ] } } From 8f098a9fe9792492acbe3113c81c2e1d55e7c63f Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Wed, 8 Apr 2026 16:45:25 -0400 Subject: [PATCH 09/29] fixed renewal issue --- cscglobal-caplugin/RequestManager.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/cscglobal-caplugin/RequestManager.cs b/cscglobal-caplugin/RequestManager.cs index 4e3a7ac..00e4de1 100644 --- a/cscglobal-caplugin/RequestManager.cs +++ b/cscglobal-caplugin/RequestManager.cs @@ -106,11 +106,13 @@ public EnrollmentResult GetRenewResponse(RenewalResponse renewResponse) } var commonName = renewResponse.Result?.CommonName ?? "(unknown)"; - Logger.LogTrace("GetRenewResponse: renewal succeeded for CommonName='{CommonName}'", commonName); + var uuid = renewResponse.Result?.Status?.Uuid; + Logger.LogTrace("GetRenewResponse: renewal succeeded for CommonName='{CommonName}', UUID='{Uuid}'", commonName, uuid ?? "(null)"); return new EnrollmentResult { - Status = (int)EndEntityStatus.GENERATED, - StatusMessage = $"Renewal Successfully Completed For {commonName}" + Status = (int)EndEntityStatus.EXTERNALVALIDATION, + CARequestID = uuid, + StatusMessage = $"Renewal Successfully Submitted For {commonName}. Certificate will be available after next sync." }; } @@ -273,9 +275,9 @@ public EnrollmentResult GetReIssueResult(IReissueResponse reissueResponse) return new EnrollmentResult { - Status = (int)EndEntityStatus.GENERATED, + Status = (int)EndEntityStatus.EXTERNALVALIDATION, CARequestID = uuid, - StatusMessage = $"Reissue Successfully Completed For {commonName}" + StatusMessage = $"Reissue Successfully Submitted For {commonName}. Certificate will be available after next sync." }; } From 77b42cd5c55135c5d5a88a18c2d4f0678ae61ea2 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Wed, 8 Apr 2026 17:12:20 -0400 Subject: [PATCH 10/29] documentation fixes --- docsource/configuration.md | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/docsource/configuration.md b/docsource/configuration.md index d8c196e..54c3210 100644 --- a/docsource/configuration.md +++ b/docsource/configuration.md @@ -10,6 +10,55 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and The Root certificates for installation on the Anygateway server machine should be obtained from CSC. +## CA Connection Configuration + +When defining the Certificate Authority in the AnyCA Gateway REST portal, configure the following fields on the **CA Connection** tab: + +CONFIG ELEMENT | DESCRIPTION | DEFAULT +---------------|-------------|-------- +CscGlobalUrl | The base URL for the CSCGlobal API (e.g. `https://apis.cscglobal.com`) | (required) +ApiKey | Your CSCGlobal API key | (required) +BearerToken | Your CSCGlobal Bearer token for authentication | (required) +DefaultPageSize | Page size for API list requests | 100 +SyncFilterDays | Number of days from today used to filter certificates by expiration date during **incremental** sync. Only certificates expiring within this window are returned. Does not apply to full sync. | 5 +RenewalWindowDays | Number of days before the annual order expiry date within which a **RenewOrReissue** request triggers a paid **Renewal** rather than a free **Reissue**. See [Renewal vs. Reissue Logic](#renewal-vs-reissue-logic) below. | 30 + +## Renewal vs. Reissue Logic + +CSC Global subscriptions are annual orders. When Keyfactor Command sends a **RenewOrReissue** request, the plugin must decide whether to submit a **Renewal** (a new paid order) or a **Reissue** (a free re-key under the existing active order). + +The decision is based on the **RenewalWindowDays** setting and works as follows: + +1. The plugin fetches the original certificate from CSC and reads its `orderDate`. +2. It computes the **order expiry** as `orderDate + 1 year`. +3. It calculates **days remaining** until the order expires. +4. If `days remaining <= RenewalWindowDays`, the request is treated as a **Renewal** (new paid order). +5. If `days remaining > RenewalWindowDays`, the request is treated as a **Reissue** (free under the active order). + +**Example with default RenewalWindowDays = 30:** + +``` +Order Date: 2025-04-08 +Order Expiry: 2026-04-08 +Today: 2026-03-15 +Days Left: 24 + +24 <= 30 --> RENEWAL (new paid order) +``` + +``` +Order Date: 2025-04-08 +Order Expiry: 2026-04-08 +Today: 2025-09-01 +Days Left: 219 + +219 > 30 --> REISSUE (free under active order) +``` + +**Fallback behavior:** If the plugin cannot retrieve the `orderDate` from CSC (e.g., API error or missing field), it falls back to checking the certificate's expiration date. If the certificate is already expired, it treats the request as a Renewal. + +**Note:** Both Renewal and Reissue submissions are asynchronous at CSC. The plugin returns a "pending" status and the issued certificate will appear in Keyfactor after the next sync cycle. + ## Certificate Template Creation Step PLEASE NOTE, AT THIS TIME THE RAPID_SSL TEMPLATE IS NOT SUPPORTED BY THE CSC API AND WILL NOT WORK WITH THIS INTEGRATION From 204367dd23acd4ad12deefb642ddeb649b109c65 Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Wed, 8 Apr 2026 21:14:19 +0000 Subject: [PATCH 11/29] Update generated docs --- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/README.md b/README.md index 10b6189..f5e93ae 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,55 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and * **Addtl Sans Comma Separated DCV Emails** - OPTIONAL: Additional SANs DCV Emails, comma separated +## CA Connection Configuration + +When defining the Certificate Authority in the AnyCA Gateway REST portal, configure the following fields on the **CA Connection** tab: + +CONFIG ELEMENT | DESCRIPTION | DEFAULT +---------------|-------------|-------- +CscGlobalUrl | The base URL for the CSCGlobal API (e.g. `https://apis.cscglobal.com`) | (required) +ApiKey | Your CSCGlobal API key | (required) +BearerToken | Your CSCGlobal Bearer token for authentication | (required) +DefaultPageSize | Page size for API list requests | 100 +SyncFilterDays | Number of days from today used to filter certificates by expiration date during **incremental** sync. Only certificates expiring within this window are returned. Does not apply to full sync. | 5 +RenewalWindowDays | Number of days before the annual order expiry date within which a **RenewOrReissue** request triggers a paid **Renewal** rather than a free **Reissue**. See [Renewal vs. Reissue Logic](#renewal-vs-reissue-logic) below. | 30 + +## Renewal vs. Reissue Logic + +CSC Global subscriptions are annual orders. When Keyfactor Command sends a **RenewOrReissue** request, the plugin must decide whether to submit a **Renewal** (a new paid order) or a **Reissue** (a free re-key under the existing active order). + +The decision is based on the **RenewalWindowDays** setting and works as follows: + +1. The plugin fetches the original certificate from CSC and reads its `orderDate`. +2. It computes the **order expiry** as `orderDate + 1 year`. +3. It calculates **days remaining** until the order expires. +4. If `days remaining <= RenewalWindowDays`, the request is treated as a **Renewal** (new paid order). +5. If `days remaining > RenewalWindowDays`, the request is treated as a **Reissue** (free under the active order). + +**Example with default RenewalWindowDays = 30:** + +``` +Order Date: 2025-04-08 +Order Expiry: 2026-04-08 +Today: 2026-03-15 +Days Left: 24 + +24 <= 30 --> RENEWAL (new paid order) +``` + +``` +Order Date: 2025-04-08 +Order Expiry: 2026-04-08 +Today: 2025-09-01 +Days Left: 219 + +219 > 30 --> REISSUE (free under active order) +``` + +**Fallback behavior:** If the plugin cannot retrieve the `orderDate` from CSC (e.g., API error or missing field), it falls back to checking the certificate's expiration date. If the certificate is already expired, it treats the request as a Renewal. + +**Note:** Both Renewal and Reissue submissions are asynchronous at CSC. The plugin returns a "pending" status and the issued certificate will appear in Keyfactor after the next sync cycle. + ## License From ff2f4c52cc873008cf8a7602d97c4d708c4d4cab Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Fri, 22 May 2026 11:51:12 -0400 Subject: [PATCH 12/29] DNS Changes --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 125 ++++++++++++++++++ cscglobal-caplugin/Dns/DnsProviderFactory.cs | 105 +++++++++++++++ cscglobal-caplugin/Interfaces/IDnsProvider.cs | 49 +++++++ docsource/configuration.md | 42 ++++++ 4 files changed, 321 insertions(+) create mode 100644 cscglobal-caplugin/Dns/DnsProviderFactory.cs create mode 100644 cscglobal-caplugin/Interfaces/IDnsProvider.cs diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index 5449f64..5d18b54 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -13,6 +13,7 @@ using Keyfactor.AnyGateway.Extensions; using Keyfactor.Extensions.CAPlugin.CSCGlobal.Client; using Keyfactor.Extensions.CAPlugin.CSCGlobal.Client.Models; +using Keyfactor.Extensions.CAPlugin.CSCGlobal.Dns; using Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces; using Keyfactor.Logging; using Keyfactor.PKI.Enums.EJBCA; @@ -39,6 +40,12 @@ public CSCGlobalCAPlugin() public int RenewalWindowDays { get; set; } + /// + /// Registry of available DNS providers. Resolution happens per-record at enrollment time + /// so a single CA can publish across multiple DNS providers based on the domain. + /// + private DnsProviderFactory? _dnsProviderFactory; + //done public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDataReader certificateDataReader) { @@ -115,6 +122,25 @@ public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDa Logger.LogDebug("RenewalWindowDays configured to {Days} days", RenewalWindowDays); }, $"RenewalWindowDays={RenewalWindowDays}"); + flow.Step("InitDnsProviderRegistry", () => + { + try + { + _dnsProviderFactory = new DnsProviderFactory(configProvider); + } + catch (Exception ex) + { + Logger.LogError(ex, "InitDnsProviderRegistry: factory threw, DNS auto-publishing disabled. {Error}", ex.Message); + _dnsProviderFactory = null; + } + + if (_dnsProviderFactory == null || _dnsProviderFactory.Providers.Count == 0) + Logger.LogInformation("No DNS providers registered. CNAME DCV records will require manual publishing."); + else + Logger.LogInformation("{Count} DNS provider(s) registered for per-domain CNAME DCV auto-publishing.", + _dnsProviderFactory.Providers.Count); + }); + Logger.MethodExit(LogLevel.Debug); } @@ -565,6 +591,12 @@ await flow.StepAsync("SubmitRegistrationToCSC", async () => var enrollResult = _requestManager.GetEnrollmentResult(enrollmentResponse); flow.Step("MapResult", $"Status={enrollResult?.Status}, ID={enrollResult?.CARequestID ?? "(null)"}"); + + await flow.StepAsync("PublishCnameDcv", async () => + { + await TryPublishCnameDcvAsync(productInfo, enrollResult); + }); + Logger.MethodExit(LogLevel.Debug); return enrollResult; @@ -1057,6 +1089,99 @@ public List GetProductIds() #region PRIVATE + /// + /// Attempts to publish CNAME DCV records by resolving an for + /// each record from the registry. Resolution is + /// per-record so different domains can be handled by different DNS providers. + /// No-op if no providers are registered, the cert isn't using CNAME validation, or the + /// response contains no CNAME details. Failures are logged but never thrown — manual + /// publishing remains a fallback so the enrollment result is still returned to Keyfactor. + /// + private async Task TryPublishCnameDcvAsync(EnrollmentProductInfo productInfo, EnrollmentResult? enrollResult) + { + if (_dnsProviderFactory == null || _dnsProviderFactory.Providers.Count == 0) + { + Logger.LogTrace("TryPublishCnameDcvAsync: no DNS providers registered, skipping auto-publish."); + return; + } + + if (enrollResult?.EnrollmentContext == null || enrollResult.EnrollmentContext.Count == 0) + { + Logger.LogTrace("TryPublishCnameDcvAsync: no CNAME entries in EnrollmentContext, skipping."); + return; + } + + var dcvMethod = productInfo?.ProductParameters != null + && productInfo.ProductParameters.TryGetValue(EnrollmentConfigConstants.DomainControlValidationMethod, out var m) + ? m + : null; + + if (string.IsNullOrEmpty(dcvMethod) || + !string.Equals(dcvMethod, "CNAME", StringComparison.OrdinalIgnoreCase)) + { + Logger.LogTrace("TryPublishCnameDcvAsync: DCV method '{Method}' is not CNAME, skipping auto-publish.", dcvMethod ?? "(null)"); + return; + } + + Logger.LogInformation("TryPublishCnameDcvAsync: attempting to publish {Count} CNAME record(s) via registered DNS providers.", + enrollResult.EnrollmentContext.Count); + + var successCount = 0; + var failCount = 0; + var unresolvedCount = 0; + + foreach (var entry in enrollResult.EnrollmentContext) + { + var recordName = entry.Key; + var cnameTarget = entry.Value; + + // CSC may also surface DCV email entries in this dictionary (key == value). Skip those. + if (string.Equals(recordName, cnameTarget, StringComparison.OrdinalIgnoreCase)) + { + Logger.LogTrace("TryPublishCnameDcvAsync: skipping entry '{Key}' (looks like an email DCV passthrough, not a CNAME).", recordName); + continue; + } + + var provider = _dnsProviderFactory.ResolveForDomain(recordName); + if (provider == null) + { + unresolvedCount++; + Logger.LogWarning( + "TryPublishCnameDcvAsync: no registered DNS provider claims '{Record}'. Manual publish required for this record.", + recordName); + continue; + } + + try + { + Logger.LogTrace("TryPublishCnameDcvAsync: creating CNAME '{Name}' -> '{Target}' via '{Provider}'.", + recordName, cnameTarget, provider.Name); + var ok = await provider.CreateCnameRecordAsync(recordName, cnameTarget); + if (ok) + { + successCount++; + Logger.LogInformation("Published CNAME '{Name}' -> '{Target}' via '{Provider}'.", recordName, cnameTarget, provider.Name); + } + else + { + failCount++; + Logger.LogWarning("DNS provider '{Provider}' reported failure publishing CNAME '{Name}'. Manual publish may be required.", + provider.Name, recordName); + } + } + catch (Exception ex) + { + failCount++; + Logger.LogError(ex, "DNS provider '{Provider}' threw publishing CNAME '{Name}'. Manual publish may be required. {Error}", + provider.Name, recordName, ex.Message); + } + } + + Logger.LogInformation( + "TryPublishCnameDcvAsync: complete. Published={Published}, Failed={Failed}, Unresolved={Unresolved}", + successCount, failCount, unresolvedCount); + } + //Trying to fix leaf extraction private static readonly Regex PemBlock = new( "-----BEGIN CERTIFICATE-----\\s*(?[A-Za-z0-9+/=\\r\\n]+?)\\s*-----END CERTIFICATE-----", diff --git a/cscglobal-caplugin/Dns/DnsProviderFactory.cs b/cscglobal-caplugin/Dns/DnsProviderFactory.cs new file mode 100644 index 0000000..4cfb3ab --- /dev/null +++ b/cscglobal-caplugin/Dns/DnsProviderFactory.cs @@ -0,0 +1,105 @@ +// Copyright 2021 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 Keyfactor.AnyGateway.Extensions; +using Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces; +using Keyfactor.Logging; +using Microsoft.Extensions.Logging; + +namespace Keyfactor.Extensions.CAPlugin.CSCGlobal.Dns; + +/// +/// Registry of available implementations. Resolution is +/// **per domain** — at enrollment time we ask each registered provider whether it +/// owns the DNS zone for a given record, and use the first match. This mirrors the +/// pattern used by the Keyfactor ACME CA plugin and avoids per-CA configuration of +/// a single global provider, so one CA can publish across multiple DNS providers. +/// +/// Providers register themselves by being added to the +/// switch below as their concrete implementations land in the codebase. +/// +public class DnsProviderFactory +{ + private readonly ILogger _logger; + private readonly List _providers; + + public DnsProviderFactory(IAnyCAPluginConfigProvider configProvider) + { + _logger = LogHandler.GetClassLogger(); + _providers = LoadProviders(configProvider); + _logger.LogInformation("DnsProviderFactory initialized with {Count} provider(s): [{Names}]", + _providers.Count, + string.Join(", ", _providers.Select(p => p.Name))); + } + + /// The set of providers known to this factory, in registration order. + public IReadOnlyList Providers => _providers; + + /// + /// Find the first registered provider that can handle the given record name. + /// Returns null if no provider claims ownership of the zone (in which case the + /// CNAME must be published manually). + /// + public IDnsProvider? ResolveForDomain(string recordName) + { + _logger.LogTrace("ResolveForDomain: looking up provider for '{Record}' across {Count} provider(s).", + recordName ?? "(null)", _providers.Count); + + if (string.IsNullOrWhiteSpace(recordName)) + { + _logger.LogWarning("ResolveForDomain: record name is null/empty, cannot resolve."); + return null; + } + + foreach (var provider in _providers) + { + try + { + if (provider.CanHandleDomain(recordName)) + { + _logger.LogTrace("ResolveForDomain: provider '{Provider}' claims '{Record}'.", provider.Name, recordName); + return provider; + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "ResolveForDomain: provider '{Provider}' threw in CanHandleDomain('{Record}'); skipping. {Error}", + provider.Name, recordName, ex.Message); + } + } + + _logger.LogDebug("ResolveForDomain: no provider claims '{Record}'.", recordName); + return null; + } + + /// + /// Instantiate the set of providers available to this gateway. Each provider + /// receives the full CA connection data so it can read its own configuration + /// keys (credentials, endpoints, etc.). Add new providers here as their + /// implementations land. + /// + private List LoadProviders(IAnyCAPluginConfigProvider configProvider) + { + var providers = new List(); + + if (configProvider?.CAConnectionData == null) + { + _logger.LogWarning("LoadProviders: configProvider or CAConnectionData is null, no providers will be loaded."); + return providers; + } + + // Register concrete providers below as they are implemented. Each provider should + // be defensive about its own configuration — only instantiate if required keys + // are present so a missing/optional provider doesn't break the gateway. + // + // Example: + // if (configProvider.CAConnectionData.ContainsKey("Cloudflare_ApiToken")) + // providers.Add(new CloudflareDnsProvider(configProvider.CAConnectionData)); + + return providers; + } +} diff --git a/cscglobal-caplugin/Interfaces/IDnsProvider.cs b/cscglobal-caplugin/Interfaces/IDnsProvider.cs new file mode 100644 index 0000000..b7d63cb --- /dev/null +++ b/cscglobal-caplugin/Interfaces/IDnsProvider.cs @@ -0,0 +1,49 @@ +// Copyright 2021 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. + +namespace Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces; + +/// +/// Contract implemented by external DNS provider plugins so the CSC plugin can +/// auto-publish CNAME records required by CSC's Domain Control Validation (DCV). +/// +/// Resolution happens **per domain** at enrollment time. The framework asks each +/// registered provider and uses the first match — +/// so a single CA can publish across multiple DNS providers (e.g. some domains +/// on Cloudflare, others on Route 53) without per-CA configuration. +/// +public interface IDnsProvider +{ + /// The unique provider name (e.g. "Cloudflare", "Route53", "Azure"). + string Name { get; } + + /// + /// Returns true if this provider owns the DNS zone for the given record name and can + /// therefore publish a CNAME on its behalf. Typically implemented by listing managed + /// zones from the provider's API and matching by suffix. + /// + /// The FQDN of the record being considered (e.g. "_dcv.example.com"). + bool CanHandleDomain(string recordName); + + /// + /// Publish a CNAME DCV record for the given record name pointing at the supplied target. + /// + /// FQDN of the record to create (e.g. "_dcv.example.com"). + /// Target value the CNAME should resolve to (supplied by CSC). + /// Cancellation token. + /// True if the record was created (or already existed and matches); false on failure. + Task CreateCnameRecordAsync(string recordName, string cnameTarget, CancellationToken cancellationToken = default); + + /// + /// Remove a previously created CNAME DCV record. Called after CSC validation completes + /// (or during cleanup). Implementations should be tolerant of missing records. + /// + /// FQDN of the record to remove. + /// Cancellation token. + /// True if the record was removed (or not present); false on failure. + Task DeleteCnameRecordAsync(string recordName, CancellationToken cancellationToken = default); +} diff --git a/docsource/configuration.md b/docsource/configuration.md index 54c3210..c28d128 100644 --- a/docsource/configuration.md +++ b/docsource/configuration.md @@ -23,6 +23,8 @@ DefaultPageSize | Page size for API list requests | 100 SyncFilterDays | Number of days from today used to filter certificates by expiration date during **incremental** sync. Only certificates expiring within this window are returned. Does not apply to full sync. | 5 RenewalWindowDays | Number of days before the annual order expiry date within which a **RenewOrReissue** request triggers a paid **Renewal** rather than a free **Reissue**. See [Renewal vs. Reissue Logic](#renewal-vs-reissue-logic) below. | 30 +> **Note:** DNS auto-publishing is configured by deploying provider DLLs, not via a CA setting. See [Pluggable DNS Providers](#pluggable-dns-providers). + ## Renewal vs. Reissue Logic CSC Global subscriptions are annual orders. When Keyfactor Command sends a **RenewOrReissue** request, the plugin must decide whether to submit a **Renewal** (a new paid order) or a **Reissue** (a free re-key under the existing active order). @@ -59,6 +61,46 @@ Days Left: 219 **Note:** Both Renewal and Reissue submissions are asynchronous at CSC. The plugin returns a "pending" status and the issued certificate will appear in Keyfactor after the next sync cycle. +## Pluggable DNS Providers + +CSC supports two Domain Control Validation (DCV) methods: **EMAIL** and **CNAME**. With CNAME validation, CSC returns a CNAME record (name → target) that must exist in DNS before they will validate the order. + +By default this plugin returns the CNAME details to Keyfactor Command for **manual publishing**. To fully automate enrollment, you can deploy one or more DNS provider DLLs alongside the plugin — the framework will publish each CNAME via the provider that owns the matching DNS zone. + +### Behavior + +* **Resolution is per record, not per CA.** When a CSC order returns CNAME details, the plugin asks each registered DNS provider `CanHandleDomain(recordName)`. The first provider that claims the zone publishes the record. One CA can drive multiple providers (e.g. Cloudflare for some domains, Route 53 for others) with no per-CA configuration. +* **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected. +* **Best-effort.** If no registered provider owns the zone, or the publish call fails, the enrollment still succeeds and the CNAME details are still surfaced to Keyfactor Command so a human can publish manually as a fallback. +* **Trace-logged.** Every resolution and publish attempt (success, failure, unresolved) is logged so issues are visible without surprising end users. + +### Authoring a DNS Provider + +A DNS provider is a separate DLL that implements `Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces.IDnsProvider`: + +```csharp +public interface IDnsProvider +{ + string Name { get; } + bool CanHandleDomain(string recordName); + Task CreateCnameRecordAsync(string recordName, string cnameTarget, CancellationToken cancellationToken = default); + Task DeleteCnameRecordAsync(string recordName, CancellationToken cancellationToken = default); +} +``` + +`CanHandleDomain` is the resolution hook — implementations typically list managed zones from the provider's API (cached at construction time) and return true when `recordName` falls within one of them. + +To wire a provider into the gateway: + +1. Build the provider as a separate DLL referencing the CSC plugin's `IDnsProvider` interface. +2. Drop the DLL into the gateway `Extensions` folder alongside this plugin. +3. Add provider-specific configuration keys to the CA Connection tab (for example `Cloudflare_ApiToken`, `Route53_AccessKey`, `Route53_SecretKey`). +4. Add a registration line to `DnsProviderFactory.LoadProviders()` that instantiates the provider when its required keys are present. + +### Currently Built-In Providers + +None at this time. The framework is in place; concrete provider implementations are tracked separately. + ## Certificate Template Creation Step PLEASE NOTE, AT THIS TIME THE RAPID_SSL TEMPLATE IS NOT SUPPORTED BY THE CSC API AND WILL NOT WORK WITH THIS INTEGRATION From b13867078d9dec0e4dde16b18f1b9bf58a5a7fff Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Fri, 22 May 2026 15:52:44 +0000 Subject: [PATCH 13/29] Update generated docs --- README.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/README.md b/README.md index f5e93ae..42f6e4a 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,8 @@ DefaultPageSize | Page size for API list requests | 100 SyncFilterDays | Number of days from today used to filter certificates by expiration date during **incremental** sync. Only certificates expiring within this window are returned. Does not apply to full sync. | 5 RenewalWindowDays | Number of days before the annual order expiry date within which a **RenewOrReissue** request triggers a paid **Renewal** rather than a free **Reissue**. See [Renewal vs. Reissue Logic](#renewal-vs-reissue-logic) below. | 30 +> **Note:** DNS auto-publishing is configured by deploying provider DLLs, not via a CA setting. See [Pluggable DNS Providers](#pluggable-dns-providers). + ## Renewal vs. Reissue Logic CSC Global subscriptions are annual orders. When Keyfactor Command sends a **RenewOrReissue** request, the plugin must decide whether to submit a **Renewal** (a new paid order) or a **Reissue** (a free re-key under the existing active order). @@ -360,6 +362,46 @@ Days Left: 219 **Note:** Both Renewal and Reissue submissions are asynchronous at CSC. The plugin returns a "pending" status and the issued certificate will appear in Keyfactor after the next sync cycle. +## Pluggable DNS Providers + +CSC supports two Domain Control Validation (DCV) methods: **EMAIL** and **CNAME**. With CNAME validation, CSC returns a CNAME record (name → target) that must exist in DNS before they will validate the order. + +By default this plugin returns the CNAME details to Keyfactor Command for **manual publishing**. To fully automate enrollment, you can deploy one or more DNS provider DLLs alongside the plugin — the framework will publish each CNAME via the provider that owns the matching DNS zone. + +### Behavior + +* **Resolution is per record, not per CA.** When a CSC order returns CNAME details, the plugin asks each registered DNS provider `CanHandleDomain(recordName)`. The first provider that claims the zone publishes the record. One CA can drive multiple providers (e.g. Cloudflare for some domains, Route 53 for others) with no per-CA configuration. +* **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected. +* **Best-effort.** If no registered provider owns the zone, or the publish call fails, the enrollment still succeeds and the CNAME details are still surfaced to Keyfactor Command so a human can publish manually as a fallback. +* **Trace-logged.** Every resolution and publish attempt (success, failure, unresolved) is logged so issues are visible without surprising end users. + +### Authoring a DNS Provider + +A DNS provider is a separate DLL that implements `Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces.IDnsProvider`: + +```csharp +public interface IDnsProvider +{ + string Name { get; } + bool CanHandleDomain(string recordName); + Task CreateCnameRecordAsync(string recordName, string cnameTarget, CancellationToken cancellationToken = default); + Task DeleteCnameRecordAsync(string recordName, CancellationToken cancellationToken = default); +} +``` + +`CanHandleDomain` is the resolution hook — implementations typically list managed zones from the provider's API (cached at construction time) and return true when `recordName` falls within one of them. + +To wire a provider into the gateway: + +1. Build the provider as a separate DLL referencing the CSC plugin's `IDnsProvider` interface. +2. Drop the DLL into the gateway `Extensions` folder alongside this plugin. +3. Add provider-specific configuration keys to the CA Connection tab (for example `Cloudflare_ApiToken`, `Route53_AccessKey`, `Route53_SecretKey`). +4. Add a registration line to `DnsProviderFactory.LoadProviders()` that instantiates the provider when its required keys are present. + +### Currently Built-In Providers + +None at this time. The framework is in place; concrete provider implementations are tracked separately. + ## License From 84d48a84aad926dbc87f6dbfc1ce3639152adf9c Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Tue, 26 May 2026 11:36:45 -0400 Subject: [PATCH 14/29] dns code updates --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 115 +++++++++++------- cscglobal-caplugin/CSCGlobalCAPlugin.csproj | 6 +- cscglobal-caplugin/Dns/DnsProviderFactory.cs | 105 ---------------- cscglobal-caplugin/Interfaces/IDnsProvider.cs | 49 -------- docsource/configuration.md | 54 ++++---- 5 files changed, 100 insertions(+), 229 deletions(-) delete mode 100644 cscglobal-caplugin/Dns/DnsProviderFactory.cs delete mode 100644 cscglobal-caplugin/Interfaces/IDnsProvider.cs diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index 5d18b54..ec2569a 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -13,7 +13,6 @@ using Keyfactor.AnyGateway.Extensions; using Keyfactor.Extensions.CAPlugin.CSCGlobal.Client; using Keyfactor.Extensions.CAPlugin.CSCGlobal.Client.Models; -using Keyfactor.Extensions.CAPlugin.CSCGlobal.Dns; using Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces; using Keyfactor.Logging; using Keyfactor.PKI.Enums.EJBCA; @@ -24,14 +23,39 @@ namespace Keyfactor.Extensions.CAPlugin.CSCGlobal; public class CSCGlobalCAPlugin : IAnyCAPlugin { + /// + /// Validation type string passed to . + /// CSC's Domain Control Validation publishes a CNAME record, so we ask the framework for a + /// validator that handles the "cname" challenge type. + /// + private const string DNS_VALIDATION_TYPE = "cname"; + private readonly RequestManager _requestManager; private readonly ILogger Logger; + private readonly IDomainValidatorFactory? _validatorFactory; private ICertificateDataReader _certificateDataReader; + /// + /// Parameterless constructor retained for compatibility with older gateway hosts that don't + /// perform DI. When constructed this way the plugin runs without DNS auto-publishing. + /// public CSCGlobalCAPlugin() { Logger = LogHandler.GetClassLogger(); _requestManager = new RequestManager(); + _validatorFactory = null; + } + + /// + /// DI constructor used by AnyCA Gateway 3.3+ which injects the framework's domain validator + /// factory. When non-null, CNAME DCV records returned by CSC are auto-published via the + /// framework's registered DNS providers (resolved per-domain). + /// + public CSCGlobalCAPlugin(IDomainValidatorFactory validatorFactory) + { + Logger = LogHandler.GetClassLogger(); + _requestManager = new RequestManager(); + _validatorFactory = validatorFactory; } private ICscGlobalClient CscGlobalClient { get; set; } @@ -40,12 +64,6 @@ public CSCGlobalCAPlugin() public int RenewalWindowDays { get; set; } - /// - /// Registry of available DNS providers. Resolution happens per-record at enrollment time - /// so a single CA can publish across multiple DNS providers based on the domain. - /// - private DnsProviderFactory? _dnsProviderFactory; - //done public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDataReader certificateDataReader) { @@ -122,23 +140,15 @@ public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDa Logger.LogDebug("RenewalWindowDays configured to {Days} days", RenewalWindowDays); }, $"RenewalWindowDays={RenewalWindowDays}"); - flow.Step("InitDnsProviderRegistry", () => + flow.Step("CheckDnsValidatorFactory", () => { - try - { - _dnsProviderFactory = new DnsProviderFactory(configProvider); - } - catch (Exception ex) - { - Logger.LogError(ex, "InitDnsProviderRegistry: factory threw, DNS auto-publishing disabled. {Error}", ex.Message); - _dnsProviderFactory = null; - } - - if (_dnsProviderFactory == null || _dnsProviderFactory.Providers.Count == 0) - Logger.LogInformation("No DNS providers registered. CNAME DCV records will require manual publishing."); + if (_validatorFactory == null) + Logger.LogInformation( + "No IDomainValidatorFactory was injected by the gateway host. CNAME DCV records will require manual publishing."); else - Logger.LogInformation("{Count} DNS provider(s) registered for per-domain CNAME DCV auto-publishing.", - _dnsProviderFactory.Providers.Count); + Logger.LogInformation( + "IDomainValidatorFactory available from gateway host. CNAME DCV records will be auto-published per-domain via the framework's registered DNS providers (validation type '{Type}').", + DNS_VALIDATION_TYPE); }); Logger.MethodExit(LogLevel.Debug); @@ -1090,18 +1100,17 @@ public List GetProductIds() #region PRIVATE /// - /// Attempts to publish CNAME DCV records by resolving an for - /// each record from the registry. Resolution is - /// per-record so different domains can be handled by different DNS providers. - /// No-op if no providers are registered, the cert isn't using CNAME validation, or the - /// response contains no CNAME details. Failures are logged but never thrown — manual - /// publishing remains a fallback so the enrollment result is still returned to Keyfactor. + /// Publishes CNAME DCV records via the gateway framework's . + /// Per-record resolution: each record is routed to whichever DNS provider plugin the framework + /// resolves for its domain. No-op if the factory wasn't injected, the cert isn't using CNAME + /// validation, or the response contains no CNAME details. Failures are logged but never thrown — + /// manual publishing remains a fallback so the enrollment result is still returned to Keyfactor. /// private async Task TryPublishCnameDcvAsync(EnrollmentProductInfo productInfo, EnrollmentResult? enrollResult) { - if (_dnsProviderFactory == null || _dnsProviderFactory.Providers.Count == 0) + if (_validatorFactory == null) { - Logger.LogTrace("TryPublishCnameDcvAsync: no DNS providers registered, skipping auto-publish."); + Logger.LogTrace("TryPublishCnameDcvAsync: no IDomainValidatorFactory was injected, skipping auto-publish."); return; } @@ -1123,8 +1132,9 @@ private async Task TryPublishCnameDcvAsync(EnrollmentProductInfo productInfo, En return; } - Logger.LogInformation("TryPublishCnameDcvAsync: attempting to publish {Count} CNAME record(s) via registered DNS providers.", - enrollResult.EnrollmentContext.Count); + Logger.LogInformation( + "TryPublishCnameDcvAsync: attempting to publish {Count} CNAME record(s) via framework DNS providers (validation type '{Type}').", + enrollResult.EnrollmentContext.Count, DNS_VALIDATION_TYPE); var successCount = 0; var failCount = 0; @@ -1142,38 +1152,53 @@ private async Task TryPublishCnameDcvAsync(EnrollmentProductInfo productInfo, En continue; } - var provider = _dnsProviderFactory.ResolveForDomain(recordName); - if (provider == null) + IDomainValidator? validator; + try + { + validator = _validatorFactory.ResolveDomainValidator(recordName, DNS_VALIDATION_TYPE); + } + catch (Exception ex) + { + unresolvedCount++; + Logger.LogWarning(ex, "ResolveDomainValidator threw for '{Record}' (type '{Type}'): {Error}", + recordName, DNS_VALIDATION_TYPE, ex.Message); + continue; + } + + if (validator == null) { unresolvedCount++; Logger.LogWarning( - "TryPublishCnameDcvAsync: no registered DNS provider claims '{Record}'. Manual publish required for this record.", - recordName); + "No DNS provider matched domain '{Record}' for validation type '{Type}'. Manual publish required for this record.", + recordName, DNS_VALIDATION_TYPE); continue; } try { - Logger.LogTrace("TryPublishCnameDcvAsync: creating CNAME '{Name}' -> '{Target}' via '{Provider}'.", - recordName, cnameTarget, provider.Name); - var ok = await provider.CreateCnameRecordAsync(recordName, cnameTarget); - if (ok) + Logger.LogTrace("StageValidation: '{Name}' -> '{Target}' via validator type '{ValType}'.", + recordName, cnameTarget, validator.GetValidationType()); + var result = await validator.StageValidation(recordName, cnameTarget, CancellationToken.None); + + if (result?.Success == true) { successCount++; - Logger.LogInformation("Published CNAME '{Name}' -> '{Target}' via '{Provider}'.", recordName, cnameTarget, provider.Name); + Logger.LogInformation("Published CNAME '{Name}' -> '{Target}' (status='{Status}').", + recordName, cnameTarget, result.Status ?? "(none)"); } else { failCount++; - Logger.LogWarning("DNS provider '{Provider}' reported failure publishing CNAME '{Name}'. Manual publish may be required.", - provider.Name, recordName); + Logger.LogWarning( + "StageValidation reported failure for CNAME '{Name}'. Status='{Status}', Error='{Error}'. Manual publish may be required.", + recordName, result?.Status ?? "(none)", result?.ErrorMessage ?? "(none)"); } } catch (Exception ex) { failCount++; - Logger.LogError(ex, "DNS provider '{Provider}' threw publishing CNAME '{Name}'. Manual publish may be required. {Error}", - provider.Name, recordName, ex.Message); + Logger.LogError(ex, "StageValidation threw publishing CNAME '{Name}'. Manual publish may be required. {Error}", + recordName, ex.Message); } } diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.csproj b/cscglobal-caplugin/CSCGlobalCAPlugin.csproj index 4d71ec5..01ee6c9 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.csproj +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.csproj @@ -18,19 +18,19 @@ - + - + - + diff --git a/cscglobal-caplugin/Dns/DnsProviderFactory.cs b/cscglobal-caplugin/Dns/DnsProviderFactory.cs deleted file mode 100644 index 4cfb3ab..0000000 --- a/cscglobal-caplugin/Dns/DnsProviderFactory.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2021 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 Keyfactor.AnyGateway.Extensions; -using Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces; -using Keyfactor.Logging; -using Microsoft.Extensions.Logging; - -namespace Keyfactor.Extensions.CAPlugin.CSCGlobal.Dns; - -/// -/// Registry of available implementations. Resolution is -/// **per domain** — at enrollment time we ask each registered provider whether it -/// owns the DNS zone for a given record, and use the first match. This mirrors the -/// pattern used by the Keyfactor ACME CA plugin and avoids per-CA configuration of -/// a single global provider, so one CA can publish across multiple DNS providers. -/// -/// Providers register themselves by being added to the -/// switch below as their concrete implementations land in the codebase. -/// -public class DnsProviderFactory -{ - private readonly ILogger _logger; - private readonly List _providers; - - public DnsProviderFactory(IAnyCAPluginConfigProvider configProvider) - { - _logger = LogHandler.GetClassLogger(); - _providers = LoadProviders(configProvider); - _logger.LogInformation("DnsProviderFactory initialized with {Count} provider(s): [{Names}]", - _providers.Count, - string.Join(", ", _providers.Select(p => p.Name))); - } - - /// The set of providers known to this factory, in registration order. - public IReadOnlyList Providers => _providers; - - /// - /// Find the first registered provider that can handle the given record name. - /// Returns null if no provider claims ownership of the zone (in which case the - /// CNAME must be published manually). - /// - public IDnsProvider? ResolveForDomain(string recordName) - { - _logger.LogTrace("ResolveForDomain: looking up provider for '{Record}' across {Count} provider(s).", - recordName ?? "(null)", _providers.Count); - - if (string.IsNullOrWhiteSpace(recordName)) - { - _logger.LogWarning("ResolveForDomain: record name is null/empty, cannot resolve."); - return null; - } - - foreach (var provider in _providers) - { - try - { - if (provider.CanHandleDomain(recordName)) - { - _logger.LogTrace("ResolveForDomain: provider '{Provider}' claims '{Record}'.", provider.Name, recordName); - return provider; - } - } - catch (Exception ex) - { - _logger.LogWarning(ex, "ResolveForDomain: provider '{Provider}' threw in CanHandleDomain('{Record}'); skipping. {Error}", - provider.Name, recordName, ex.Message); - } - } - - _logger.LogDebug("ResolveForDomain: no provider claims '{Record}'.", recordName); - return null; - } - - /// - /// Instantiate the set of providers available to this gateway. Each provider - /// receives the full CA connection data so it can read its own configuration - /// keys (credentials, endpoints, etc.). Add new providers here as their - /// implementations land. - /// - private List LoadProviders(IAnyCAPluginConfigProvider configProvider) - { - var providers = new List(); - - if (configProvider?.CAConnectionData == null) - { - _logger.LogWarning("LoadProviders: configProvider or CAConnectionData is null, no providers will be loaded."); - return providers; - } - - // Register concrete providers below as they are implemented. Each provider should - // be defensive about its own configuration — only instantiate if required keys - // are present so a missing/optional provider doesn't break the gateway. - // - // Example: - // if (configProvider.CAConnectionData.ContainsKey("Cloudflare_ApiToken")) - // providers.Add(new CloudflareDnsProvider(configProvider.CAConnectionData)); - - return providers; - } -} diff --git a/cscglobal-caplugin/Interfaces/IDnsProvider.cs b/cscglobal-caplugin/Interfaces/IDnsProvider.cs deleted file mode 100644 index b7d63cb..0000000 --- a/cscglobal-caplugin/Interfaces/IDnsProvider.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2021 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. - -namespace Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces; - -/// -/// Contract implemented by external DNS provider plugins so the CSC plugin can -/// auto-publish CNAME records required by CSC's Domain Control Validation (DCV). -/// -/// Resolution happens **per domain** at enrollment time. The framework asks each -/// registered provider and uses the first match — -/// so a single CA can publish across multiple DNS providers (e.g. some domains -/// on Cloudflare, others on Route 53) without per-CA configuration. -/// -public interface IDnsProvider -{ - /// The unique provider name (e.g. "Cloudflare", "Route53", "Azure"). - string Name { get; } - - /// - /// Returns true if this provider owns the DNS zone for the given record name and can - /// therefore publish a CNAME on its behalf. Typically implemented by listing managed - /// zones from the provider's API and matching by suffix. - /// - /// The FQDN of the record being considered (e.g. "_dcv.example.com"). - bool CanHandleDomain(string recordName); - - /// - /// Publish a CNAME DCV record for the given record name pointing at the supplied target. - /// - /// FQDN of the record to create (e.g. "_dcv.example.com"). - /// Target value the CNAME should resolve to (supplied by CSC). - /// Cancellation token. - /// True if the record was created (or already existed and matches); false on failure. - Task CreateCnameRecordAsync(string recordName, string cnameTarget, CancellationToken cancellationToken = default); - - /// - /// Remove a previously created CNAME DCV record. Called after CSC validation completes - /// (or during cleanup). Implementations should be tolerant of missing records. - /// - /// FQDN of the record to remove. - /// Cancellation token. - /// True if the record was removed (or not present); false on failure. - Task DeleteCnameRecordAsync(string recordName, CancellationToken cancellationToken = default); -} diff --git a/docsource/configuration.md b/docsource/configuration.md index c28d128..a0f240c 100644 --- a/docsource/configuration.md +++ b/docsource/configuration.md @@ -23,7 +23,7 @@ DefaultPageSize | Page size for API list requests | 100 SyncFilterDays | Number of days from today used to filter certificates by expiration date during **incremental** sync. Only certificates expiring within this window are returned. Does not apply to full sync. | 5 RenewalWindowDays | Number of days before the annual order expiry date within which a **RenewOrReissue** request triggers a paid **Renewal** rather than a free **Reissue**. See [Renewal vs. Reissue Logic](#renewal-vs-reissue-logic) below. | 30 -> **Note:** DNS auto-publishing is configured by deploying provider DLLs, not via a CA setting. See [Pluggable DNS Providers](#pluggable-dns-providers). +> **Note:** DNS auto-publishing for CNAME DCV is handled by the AnyCA Gateway REST framework's Domain Validation system (gateway 3.3+). It's configured in the gateway UI under **Domain Validation Configurations**, not on the CA Connection tab. See [DNS Auto-Publishing (CNAME DCV)](#dns-auto-publishing-cname-dcv). ## Renewal vs. Reissue Logic @@ -61,45 +61,45 @@ Days Left: 219 **Note:** Both Renewal and Reissue submissions are asynchronous at CSC. The plugin returns a "pending" status and the issued certificate will appear in Keyfactor after the next sync cycle. -## Pluggable DNS Providers +## DNS Auto-Publishing (CNAME DCV) CSC supports two Domain Control Validation (DCV) methods: **EMAIL** and **CNAME**. With CNAME validation, CSC returns a CNAME record (name → target) that must exist in DNS before they will validate the order. -By default this plugin returns the CNAME details to Keyfactor Command for **manual publishing**. To fully automate enrollment, you can deploy one or more DNS provider DLLs alongside the plugin — the framework will publish each CNAME via the provider that owns the matching DNS zone. +By default this plugin returns the CNAME details to Keyfactor Command for **manual publishing**. To fully automate enrollment, the plugin uses the **AnyCA Gateway REST framework's built-in DNS provider system** (available in framework 3.3 and later). The framework discovers DNS provider plugins deployed alongside the CA plugin and routes each CNAME to whichever provider claims the matching DNS zone. -### Behavior +### Requirements -* **Resolution is per record, not per CA.** When a CSC order returns CNAME details, the plugin asks each registered DNS provider `CanHandleDomain(recordName)`. The first provider that claims the zone publishes the record. One CA can drive multiple providers (e.g. Cloudflare for some domains, Route 53 for others) with no per-CA configuration. -* **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected. -* **Best-effort.** If no registered provider owns the zone, or the publish call fails, the enrollment still succeeds and the CNAME details are still surfaced to Keyfactor Command so a human can publish manually as a fallback. -* **Trace-logged.** Every resolution and publish attempt (success, failure, unresolved) is logged so issues are visible without surprising end users. +* AnyCA Gateway REST framework **3.3 or later** (the `IDomainValidatorFactory` interface ships in `Keyfactor.AnyGateway.IAnyCAPlugin` 3.3+). +* At least one DNS provider DLL (e.g. GoDaddy, Cloudflare, Route 53, Azure) deployed in the gateway `Extensions` folder. +* A Domain Validation Configuration registered in the gateway UI that maps your domain(s) to the deployed provider (for example, `*.example.com` → GoDaddy). -### Authoring a DNS Provider +### How It Works -A DNS provider is a separate DLL that implements `Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces.IDnsProvider`: +1. CSC returns the CNAME `name → target` details in the enrollment response. +2. For each CNAME entry, the plugin calls `IDomainValidatorFactory.ResolveDomainValidator(recordName, "cname")`. +3. The framework returns the `IDomainValidator` whose Domain Validation Configuration matches the record's zone (or `null` if no match). +4. The plugin calls `validator.StageValidation(recordName, cnameTarget, ct)` to publish the record. +5. CSC asynchronously validates the CNAME; the issued certificate appears on the next sync. -```csharp -public interface IDnsProvider -{ - string Name { get; } - bool CanHandleDomain(string recordName); - Task CreateCnameRecordAsync(string recordName, string cnameTarget, CancellationToken cancellationToken = default); - Task DeleteCnameRecordAsync(string recordName, CancellationToken cancellationToken = default); -} -``` +### Behavior -`CanHandleDomain` is the resolution hook — implementations typically list managed zones from the provider's API (cached at construction time) and return true when `recordName` falls within one of them. +* **Resolution is per record, not per CA.** One CA can drive multiple DNS providers (GoDaddy for some domains, Route 53 for others) with no per-CA configuration. +* **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected — no DNS publishing occurs. +* **Best-effort.** If no provider claims the zone, the publish call fails, or the factory wasn't injected (gateway pre-3.3), the enrollment still succeeds and the CNAME details remain in the Keyfactor request so a human can publish manually as a fallback. +* **Trace-logged.** Every resolution (matched/unresolved) and publish attempt (success/failure) is logged at Info/Trace level. +* **Validation type string.** The plugin passes `"cname"` to `ResolveDomainValidator`. The DNS provider you deploy must advertise support for that validation type (via its `GetValidationType()` method) or it won't be matched. -To wire a provider into the gateway: +### Configuration in the Gateway UI -1. Build the provider as a separate DLL referencing the CSC plugin's `IDnsProvider` interface. -2. Drop the DLL into the gateway `Extensions` folder alongside this plugin. -3. Add provider-specific configuration keys to the CA Connection tab (for example `Cloudflare_ApiToken`, `Route53_AccessKey`, `Route53_SecretKey`). -4. Add a registration line to `DnsProviderFactory.LoadProviders()` that instantiates the provider when its required keys are present. +In the AnyCA Gateway REST portal, under **Domain Validation Configurations**: -### Currently Built-In Providers +1. **Add** a new configuration. +2. Pick the **Domain Validator** (e.g. `GoDaddyDnsPlugin`) — these come from the DNS provider DLLs you've dropped in `Extensions/`. +3. Add one or more **domain patterns** (e.g. `*.example.com`). +4. Fill out the provider-specific **Configuration Settings** (API keys, zone IDs, etc.). +5. Save. -None at this time. The framework is in place; concrete provider implementations are tracked separately. +Once configured, any CSC enrollment for a domain matching one of those patterns will have its CNAME auto-published. ## Certificate Template Creation Step From 448f1679864b40c456e02a6dd3886e0a50e5585c Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Tue, 26 May 2026 15:38:43 +0000 Subject: [PATCH 15/29] Update generated docs --- README.md | 54 +++++++++++++++++++++++++++--------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 42f6e4a..2793370 100644 --- a/README.md +++ b/README.md @@ -324,7 +324,7 @@ DefaultPageSize | Page size for API list requests | 100 SyncFilterDays | Number of days from today used to filter certificates by expiration date during **incremental** sync. Only certificates expiring within this window are returned. Does not apply to full sync. | 5 RenewalWindowDays | Number of days before the annual order expiry date within which a **RenewOrReissue** request triggers a paid **Renewal** rather than a free **Reissue**. See [Renewal vs. Reissue Logic](#renewal-vs-reissue-logic) below. | 30 -> **Note:** DNS auto-publishing is configured by deploying provider DLLs, not via a CA setting. See [Pluggable DNS Providers](#pluggable-dns-providers). +> **Note:** DNS auto-publishing for CNAME DCV is handled by the AnyCA Gateway REST framework's Domain Validation system (gateway 3.3+). It's configured in the gateway UI under **Domain Validation Configurations**, not on the CA Connection tab. See [DNS Auto-Publishing (CNAME DCV)](#dns-auto-publishing-cname-dcv). ## Renewal vs. Reissue Logic @@ -362,45 +362,45 @@ Days Left: 219 **Note:** Both Renewal and Reissue submissions are asynchronous at CSC. The plugin returns a "pending" status and the issued certificate will appear in Keyfactor after the next sync cycle. -## Pluggable DNS Providers +## DNS Auto-Publishing (CNAME DCV) CSC supports two Domain Control Validation (DCV) methods: **EMAIL** and **CNAME**. With CNAME validation, CSC returns a CNAME record (name → target) that must exist in DNS before they will validate the order. -By default this plugin returns the CNAME details to Keyfactor Command for **manual publishing**. To fully automate enrollment, you can deploy one or more DNS provider DLLs alongside the plugin — the framework will publish each CNAME via the provider that owns the matching DNS zone. +By default this plugin returns the CNAME details to Keyfactor Command for **manual publishing**. To fully automate enrollment, the plugin uses the **AnyCA Gateway REST framework's built-in DNS provider system** (available in framework 3.3 and later). The framework discovers DNS provider plugins deployed alongside the CA plugin and routes each CNAME to whichever provider claims the matching DNS zone. -### Behavior +### Requirements -* **Resolution is per record, not per CA.** When a CSC order returns CNAME details, the plugin asks each registered DNS provider `CanHandleDomain(recordName)`. The first provider that claims the zone publishes the record. One CA can drive multiple providers (e.g. Cloudflare for some domains, Route 53 for others) with no per-CA configuration. -* **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected. -* **Best-effort.** If no registered provider owns the zone, or the publish call fails, the enrollment still succeeds and the CNAME details are still surfaced to Keyfactor Command so a human can publish manually as a fallback. -* **Trace-logged.** Every resolution and publish attempt (success, failure, unresolved) is logged so issues are visible without surprising end users. +* AnyCA Gateway REST framework **3.3 or later** (the `IDomainValidatorFactory` interface ships in `Keyfactor.AnyGateway.IAnyCAPlugin` 3.3+). +* At least one DNS provider DLL (e.g. GoDaddy, Cloudflare, Route 53, Azure) deployed in the gateway `Extensions` folder. +* A Domain Validation Configuration registered in the gateway UI that maps your domain(s) to the deployed provider (for example, `*.example.com` → GoDaddy). -### Authoring a DNS Provider +### How It Works -A DNS provider is a separate DLL that implements `Keyfactor.Extensions.CAPlugin.CSCGlobal.Interfaces.IDnsProvider`: +1. CSC returns the CNAME `name → target` details in the enrollment response. +2. For each CNAME entry, the plugin calls `IDomainValidatorFactory.ResolveDomainValidator(recordName, "cname")`. +3. The framework returns the `IDomainValidator` whose Domain Validation Configuration matches the record's zone (or `null` if no match). +4. The plugin calls `validator.StageValidation(recordName, cnameTarget, ct)` to publish the record. +5. CSC asynchronously validates the CNAME; the issued certificate appears on the next sync. -```csharp -public interface IDnsProvider -{ - string Name { get; } - bool CanHandleDomain(string recordName); - Task CreateCnameRecordAsync(string recordName, string cnameTarget, CancellationToken cancellationToken = default); - Task DeleteCnameRecordAsync(string recordName, CancellationToken cancellationToken = default); -} -``` +### Behavior -`CanHandleDomain` is the resolution hook — implementations typically list managed zones from the provider's API (cached at construction time) and return true when `recordName` falls within one of them. +* **Resolution is per record, not per CA.** One CA can drive multiple DNS providers (GoDaddy for some domains, Route 53 for others) with no per-CA configuration. +* **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected — no DNS publishing occurs. +* **Best-effort.** If no provider claims the zone, the publish call fails, or the factory wasn't injected (gateway pre-3.3), the enrollment still succeeds and the CNAME details remain in the Keyfactor request so a human can publish manually as a fallback. +* **Trace-logged.** Every resolution (matched/unresolved) and publish attempt (success/failure) is logged at Info/Trace level. +* **Validation type string.** The plugin passes `"cname"` to `ResolveDomainValidator`. The DNS provider you deploy must advertise support for that validation type (via its `GetValidationType()` method) or it won't be matched. -To wire a provider into the gateway: +### Configuration in the Gateway UI -1. Build the provider as a separate DLL referencing the CSC plugin's `IDnsProvider` interface. -2. Drop the DLL into the gateway `Extensions` folder alongside this plugin. -3. Add provider-specific configuration keys to the CA Connection tab (for example `Cloudflare_ApiToken`, `Route53_AccessKey`, `Route53_SecretKey`). -4. Add a registration line to `DnsProviderFactory.LoadProviders()` that instantiates the provider when its required keys are present. +In the AnyCA Gateway REST portal, under **Domain Validation Configurations**: -### Currently Built-In Providers +1. **Add** a new configuration. +2. Pick the **Domain Validator** (e.g. `GoDaddyDnsPlugin`) — these come from the DNS provider DLLs you've dropped in `Extensions/`. +3. Add one or more **domain patterns** (e.g. `*.example.com`). +4. Fill out the provider-specific **Configuration Settings** (API keys, zone IDs, etc.). +5. Save. -None at this time. The framework is in place; concrete provider implementations are tracked separately. +Once configured, any CSC enrollment for a domain matching one of those patterns will have its CNAME auto-published. ## License From eb39fcfaceb4b035fbd16826310b829d838a490f Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Tue, 26 May 2026 13:01:13 -0400 Subject: [PATCH 16/29] change type --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 10 +++++++--- docsource/configuration.md | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index ec2569a..04d25bd 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -25,10 +25,14 @@ public class CSCGlobalCAPlugin : IAnyCAPlugin { /// /// Validation type string passed to . - /// CSC's Domain Control Validation publishes a CNAME record, so we ask the framework for a - /// validator that handles the "cname" challenge type. + /// DNS provider plugins in the Keyfactor ecosystem (GoDaddy, Cloudflare, Route 53, Azure, etc.) + /// standardize on "dns-01" as their advertised validation type — originally from ACME's + /// DNS-01 challenge, but in practice used as a generic "publishes DNS records" capability tag. + /// CSC's Domain Control Validation publishes a CNAME (not a TXT), but the underlying + /// call is generic key/value — the provider + /// publishes whatever record type its implementation chooses. /// - private const string DNS_VALIDATION_TYPE = "cname"; + private const string DNS_VALIDATION_TYPE = "dns-01"; private readonly RequestManager _requestManager; private readonly ILogger Logger; diff --git a/docsource/configuration.md b/docsource/configuration.md index a0f240c..cd028a9 100644 --- a/docsource/configuration.md +++ b/docsource/configuration.md @@ -87,7 +87,7 @@ By default this plugin returns the CNAME details to Keyfactor Command for **manu * **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected — no DNS publishing occurs. * **Best-effort.** If no provider claims the zone, the publish call fails, or the factory wasn't injected (gateway pre-3.3), the enrollment still succeeds and the CNAME details remain in the Keyfactor request so a human can publish manually as a fallback. * **Trace-logged.** Every resolution (matched/unresolved) and publish attempt (success/failure) is logged at Info/Trace level. -* **Validation type string.** The plugin passes `"cname"` to `ResolveDomainValidator`. The DNS provider you deploy must advertise support for that validation type (via its `GetValidationType()` method) or it won't be matched. +* **Validation type string.** The plugin passes `"dns-01"` to `ResolveDomainValidator`. This is the de-facto standard string used by the Keyfactor DNS provider plugins (GoDaddy, Cloudflare, Route 53, Azure) — originally from ACME's DNS-01 challenge, but used generically as a "publishes DNS records" capability tag. The DNS provider you deploy must advertise support for `"dns-01"` (via its `GetValidationType()` method) or it won't be matched. The underlying `StageValidation(key, value, ct)` call is generic, and the provider implementation decides whether to publish a CNAME or TXT based on the value supplied. ### Configuration in the Gateway UI From 3ba367be3c638f47664a329d324e60ccc8d682d2 Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Tue, 26 May 2026 17:03:03 +0000 Subject: [PATCH 17/29] Update generated docs --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2793370..e5bf317 100644 --- a/README.md +++ b/README.md @@ -388,7 +388,7 @@ By default this plugin returns the CNAME details to Keyfactor Command for **manu * **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected — no DNS publishing occurs. * **Best-effort.** If no provider claims the zone, the publish call fails, or the factory wasn't injected (gateway pre-3.3), the enrollment still succeeds and the CNAME details remain in the Keyfactor request so a human can publish manually as a fallback. * **Trace-logged.** Every resolution (matched/unresolved) and publish attempt (success/failure) is logged at Info/Trace level. -* **Validation type string.** The plugin passes `"cname"` to `ResolveDomainValidator`. The DNS provider you deploy must advertise support for that validation type (via its `GetValidationType()` method) or it won't be matched. +* **Validation type string.** The plugin passes `"dns-01"` to `ResolveDomainValidator`. This is the de-facto standard string used by the Keyfactor DNS provider plugins (GoDaddy, Cloudflare, Route 53, Azure) — originally from ACME's DNS-01 challenge, but used generically as a "publishes DNS records" capability tag. The DNS provider you deploy must advertise support for `"dns-01"` (via its `GetValidationType()` method) or it won't be matched. The underlying `StageValidation(key, value, ct)` call is generic, and the provider implementation decides whether to publish a CNAME or TXT based on the value supplied. ### Configuration in the Gateway UI From 65454d0d61931ab62634b112d4f41c403fd64742 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Tue, 26 May 2026 14:39:12 -0400 Subject: [PATCH 18/29] fixed mismatch --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 29 +++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index 04d25bd..431ab23 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -1103,6 +1103,17 @@ public List GetProductIds() #region PRIVATE + /// + /// Strip a single trailing dot from a DNS name. CSC returns FQDN-canonical names with + /// a trailing dot but the framework's Domain Validation Configurations are stored without + /// one, so the strings have to be normalized before lookup or the equality check fails. + /// + private static string StripTrailingDot(string? s) + { + if (string.IsNullOrEmpty(s)) return s ?? string.Empty; + return s.EndsWith('.') ? s[..^1] : s; + } + /// /// Publishes CNAME DCV records via the gateway framework's . /// Per-record resolution: each record is routed to whichever DNS provider plugin the framework @@ -1146,16 +1157,26 @@ private async Task TryPublishCnameDcvAsync(EnrollmentProductInfo productInfo, En foreach (var entry in enrollResult.EnrollmentContext) { - var recordName = entry.Key; - var cnameTarget = entry.Value; + var rawRecordName = entry.Key; + var rawCnameTarget = entry.Value; // CSC may also surface DCV email entries in this dictionary (key == value). Skip those. - if (string.Equals(recordName, cnameTarget, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(rawRecordName, rawCnameTarget, StringComparison.OrdinalIgnoreCase)) { - Logger.LogTrace("TryPublishCnameDcvAsync: skipping entry '{Key}' (looks like an email DCV passthrough, not a CNAME).", recordName); + Logger.LogTrace("TryPublishCnameDcvAsync: skipping entry '{Key}' (looks like an email DCV passthrough, not a CNAME).", rawRecordName); continue; } + // CSC returns FQDN-canonical names with trailing dots (e.g. "foo.example.com."). + // The framework's Domain Validation Configuration stores domain patterns without + // the trailing dot, so strip it before resolution and publishing or no provider + // will match (the framework will look up "*.example.com." which won't equal "*.example.com"). + var recordName = StripTrailingDot(rawRecordName); + var cnameTarget = StripTrailingDot(rawCnameTarget); + + if (recordName != rawRecordName) + Logger.LogTrace("TryPublishCnameDcvAsync: normalized record name '{Raw}' -> '{Normalized}'.", rawRecordName, recordName); + IDomainValidator? validator; try { From 01273319473b4dd346879c517513c38470ce0ed0 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Tue, 26 May 2026 15:34:30 -0400 Subject: [PATCH 19/29] Use 'cname' validation type for CSC CNAME DCV CSC DCV requires a CNAME record, so resolve a DNS provider advertising the 'cname' validation type (e.g. GoDaddyCnameDomainValidator) rather than the ACME 'dns-01'/TXT variant. Docs updated to call out the CNAME validator and warn against selecting the TXT validator for CSC domains. --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 12 +++++------- docsource/configuration.md | 9 ++++++--- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index 431ab23..0c3721d 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -25,14 +25,12 @@ public class CSCGlobalCAPlugin : IAnyCAPlugin { /// /// Validation type string passed to . - /// DNS provider plugins in the Keyfactor ecosystem (GoDaddy, Cloudflare, Route 53, Azure, etc.) - /// standardize on "dns-01" as their advertised validation type — originally from ACME's - /// DNS-01 challenge, but in practice used as a generic "publishes DNS records" capability tag. - /// CSC's Domain Control Validation publishes a CNAME (not a TXT), but the underlying - /// call is generic key/value — the provider - /// publishes whatever record type its implementation chooses. + /// CSC's Domain Control Validation publishes a CNAME record, so we resolve a DNS provider + /// that advertises the "cname" validation type (e.g. GoDaddy's GoDaddyCnameDomainValidator). + /// This is distinct from ACME's "dns-01" challenge, which publishes TXT records — a single + /// DNS provider DLL can ship separate validator classes for each type. /// - private const string DNS_VALIDATION_TYPE = "dns-01"; + private const string DNS_VALIDATION_TYPE = "cname"; private readonly RequestManager _requestManager; private readonly ILogger Logger; diff --git a/docsource/configuration.md b/docsource/configuration.md index cd028a9..9b5961c 100644 --- a/docsource/configuration.md +++ b/docsource/configuration.md @@ -87,20 +87,23 @@ By default this plugin returns the CNAME details to Keyfactor Command for **manu * **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected — no DNS publishing occurs. * **Best-effort.** If no provider claims the zone, the publish call fails, or the factory wasn't injected (gateway pre-3.3), the enrollment still succeeds and the CNAME details remain in the Keyfactor request so a human can publish manually as a fallback. * **Trace-logged.** Every resolution (matched/unresolved) and publish attempt (success/failure) is logged at Info/Trace level. -* **Validation type string.** The plugin passes `"dns-01"` to `ResolveDomainValidator`. This is the de-facto standard string used by the Keyfactor DNS provider plugins (GoDaddy, Cloudflare, Route 53, Azure) — originally from ACME's DNS-01 challenge, but used generically as a "publishes DNS records" capability tag. The DNS provider you deploy must advertise support for `"dns-01"` (via its `GetValidationType()` method) or it won't be matched. The underlying `StageValidation(key, value, ct)` call is generic, and the provider implementation decides whether to publish a CNAME or TXT based on the value supplied. +* **Validation type string.** The plugin passes `"cname"` to `ResolveDomainValidator`. CSC's DCV requires a **CNAME** record, which is different from ACME's `"dns-01"` challenge (a TXT record). A single DNS provider DLL can ship multiple validator classes — one advertising `"dns-01"` (publishes TXT, for ACME) and one advertising `"cname"` (publishes CNAME, for CSC). You must deploy and configure a validator that advertises `"cname"` or no provider will match. +* **Trailing dots normalized.** CSC returns FQDN-canonical names with a trailing dot (e.g. `_token.example.com.`). The plugin strips the trailing dot before resolution and publishing, because Domain Validation Configurations and DNS provider APIs expect names without it. ### Configuration in the Gateway UI In the AnyCA Gateway REST portal, under **Domain Validation Configurations**: 1. **Add** a new configuration. -2. Pick the **Domain Validator** (e.g. `GoDaddyDnsPlugin`) — these come from the DNS provider DLLs you've dropped in `Extensions/`. +2. Pick a **Domain Validator Type** that publishes **CNAME** records and advertises validation type `cname`. For GoDaddy this is `GoDaddyCnameDomainValidator` (the `GoDaddyDomainValidator` variant publishes TXT for ACME and will **not** work for CSC). 3. Add one or more **domain patterns** (e.g. `*.example.com`). -4. Fill out the provider-specific **Configuration Settings** (API keys, zone IDs, etc.). +4. Fill out the provider-specific **Configuration Settings** (API keys, base URL, etc.). 5. Save. Once configured, any CSC enrollment for a domain matching one of those patterns will have its CNAME auto-published. +> **Common pitfall:** If you configure the TXT/`dns-01` validator (e.g. `GoDaddyDomainValidator`) for a CSC domain, the record will publish as a **TXT** and CSC's CNAME validation will never succeed. Make sure you select the **CNAME** validator variant. + ## Certificate Template Creation Step PLEASE NOTE, AT THIS TIME THE RAPID_SSL TEMPLATE IS NOT SUPPORTED BY THE CSC API AND WILL NOT WORK WITH THIS INTEGRATION From 5ea38b462661f5e69f2b3eb98b2fb8bd3f087788 Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Tue, 26 May 2026 19:36:03 +0000 Subject: [PATCH 20/29] Update generated docs --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e5bf317..36d4a34 100644 --- a/README.md +++ b/README.md @@ -388,20 +388,23 @@ By default this plugin returns the CNAME details to Keyfactor Command for **manu * **Only invoked for CNAME DCV.** Templates configured with EMAIL validation are unaffected — no DNS publishing occurs. * **Best-effort.** If no provider claims the zone, the publish call fails, or the factory wasn't injected (gateway pre-3.3), the enrollment still succeeds and the CNAME details remain in the Keyfactor request so a human can publish manually as a fallback. * **Trace-logged.** Every resolution (matched/unresolved) and publish attempt (success/failure) is logged at Info/Trace level. -* **Validation type string.** The plugin passes `"dns-01"` to `ResolveDomainValidator`. This is the de-facto standard string used by the Keyfactor DNS provider plugins (GoDaddy, Cloudflare, Route 53, Azure) — originally from ACME's DNS-01 challenge, but used generically as a "publishes DNS records" capability tag. The DNS provider you deploy must advertise support for `"dns-01"` (via its `GetValidationType()` method) or it won't be matched. The underlying `StageValidation(key, value, ct)` call is generic, and the provider implementation decides whether to publish a CNAME or TXT based on the value supplied. +* **Validation type string.** The plugin passes `"cname"` to `ResolveDomainValidator`. CSC's DCV requires a **CNAME** record, which is different from ACME's `"dns-01"` challenge (a TXT record). A single DNS provider DLL can ship multiple validator classes — one advertising `"dns-01"` (publishes TXT, for ACME) and one advertising `"cname"` (publishes CNAME, for CSC). You must deploy and configure a validator that advertises `"cname"` or no provider will match. +* **Trailing dots normalized.** CSC returns FQDN-canonical names with a trailing dot (e.g. `_token.example.com.`). The plugin strips the trailing dot before resolution and publishing, because Domain Validation Configurations and DNS provider APIs expect names without it. ### Configuration in the Gateway UI In the AnyCA Gateway REST portal, under **Domain Validation Configurations**: 1. **Add** a new configuration. -2. Pick the **Domain Validator** (e.g. `GoDaddyDnsPlugin`) — these come from the DNS provider DLLs you've dropped in `Extensions/`. +2. Pick a **Domain Validator Type** that publishes **CNAME** records and advertises validation type `cname`. For GoDaddy this is `GoDaddyCnameDomainValidator` (the `GoDaddyDomainValidator` variant publishes TXT for ACME and will **not** work for CSC). 3. Add one or more **domain patterns** (e.g. `*.example.com`). -4. Fill out the provider-specific **Configuration Settings** (API keys, zone IDs, etc.). +4. Fill out the provider-specific **Configuration Settings** (API keys, base URL, etc.). 5. Save. Once configured, any CSC enrollment for a domain matching one of those patterns will have its CNAME auto-published. +> **Common pitfall:** If you configure the TXT/`dns-01` validator (e.g. `GoDaddyDomainValidator`) for a CSC domain, the record will publish as a **TXT** and CSC's CNAME validation will never succeed. Make sure you select the **CNAME** validator variant. + ## License From 73f7dddd85cd3d523e3be5b6f38ded9a7cc5b46d Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Wed, 27 May 2026 11:10:59 -0400 Subject: [PATCH 21/29] added polling to grab cert --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 136 +++++++++++++++++++++++- cscglobal-caplugin/Constants.cs | 1 + docsource/configuration.md | 14 +++ 3 files changed, 149 insertions(+), 2 deletions(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index 0c3721d..4ff69fd 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -32,6 +32,9 @@ public class CSCGlobalCAPlugin : IAnyCAPlugin /// private const string DNS_VALIDATION_TYPE = "cname"; + /// Delay between CSC status polls while waiting for DCV to complete. + private static readonly TimeSpan DcvPollInterval = TimeSpan.FromSeconds(10); + private readonly RequestManager _requestManager; private readonly ILogger Logger; private readonly IDomainValidatorFactory? _validatorFactory; @@ -66,6 +69,14 @@ public CSCGlobalCAPlugin(IDomainValidatorFactory validatorFactory) public int RenewalWindowDays { get; set; } + /// + /// Maximum seconds to synchronously poll CSC for certificate issuance after submitting an + /// order (and publishing CNAME DCV). 0 disables polling — the enrollment returns "pending" + /// immediately and the cert is picked up on the next sync. When > 0, fast-validating + /// orders can return the issued cert directly in the enrollment response. + /// + public int DcvPollTimeoutSeconds { get; set; } + //done public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDataReader certificateDataReader) { @@ -142,6 +153,25 @@ public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDa Logger.LogDebug("RenewalWindowDays configured to {Days} days", RenewalWindowDays); }, $"RenewalWindowDays={RenewalWindowDays}"); + flow.Step("ReadDcvPollTimeoutSeconds", () => + { + DcvPollTimeoutSeconds = 0; // default: disabled + if (configProvider.CAConnectionData.TryGetValue(Constants.DcvPollTimeoutSeconds, out var pollObj)) + { + Logger.LogTrace("DcvPollTimeoutSeconds raw value: '{Value}'", pollObj?.ToString() ?? "(null)"); + if (int.TryParse(pollObj?.ToString(), out var pollSeconds) && pollSeconds >= 0) + DcvPollTimeoutSeconds = pollSeconds; + else + Logger.LogWarning("DcvPollTimeoutSeconds value '{Value}' could not be parsed or was < 0, using default 0 (disabled).", pollObj); + } + else + { + Logger.LogTrace("DcvPollTimeoutSeconds key not found in CAConnectionData, using default 0 (disabled)."); + } + Logger.LogDebug("DcvPollTimeoutSeconds configured to {Seconds}s ({State})", + DcvPollTimeoutSeconds, DcvPollTimeoutSeconds > 0 ? "enabled" : "disabled"); + }); + flow.Step("CheckDnsValidatorFactory", () => { if (_validatorFactory == null) @@ -609,6 +639,18 @@ await flow.StepAsync("PublishCnameDcv", async () => await TryPublishCnameDcvAsync(productInfo, enrollResult); }); + EnrollmentResult? newPolled = null; + await flow.StepAsync("PollForIssuance", async () => + { + newPolled = await TryPollForIssuedCertAsync(enrollResult?.CARequestID); + }); + if (newPolled != null) + { + flow.Step("PollResult", "issued during poll window"); + Logger.MethodExit(LogLevel.Debug); + return newPolled; + } + Logger.MethodExit(LogLevel.Debug); return enrollResult; @@ -752,8 +794,14 @@ await flow.StepAsync("SubmitRenewalToCSC", async () => Logger.LogTrace("Renewal Response JSON: {Json}", JsonConvert.SerializeObject(renewResponse)); var renewResult = _requestManager.GetRenewResponse(renewResponse); flow.Step("MapRenewalResult", $"Status={renewResult?.Status}, Message={renewResult?.StatusMessage ?? "(null)"}"); + + EnrollmentResult? renewPolled = null; + await flow.StepAsync("PollForIssuance", async () => + { + renewPolled = await TryPollForIssuedCertAsync(renewResult?.CARequestID); + }); Logger.MethodExit(LogLevel.Debug); - return renewResult; + return renewPolled ?? renewResult; } flow.Fail("MissingEnrollmentParams", "Applicant Last Name not present — one-click renew unavailable"); @@ -825,8 +873,14 @@ await flow.StepAsync("SubmitReissueToCSC", async () => Logger.LogTrace("Reissue Response JSON: {Json}", JsonConvert.SerializeObject(reissueResponse)); var reissueResult = _requestManager.GetReIssueResult(reissueResponse); flow.Step("MapReissueResult", $"Status={reissueResult?.Status}, Message={reissueResult?.StatusMessage ?? "(null)"}"); + + EnrollmentResult? reissuePolled = null; + await flow.StepAsync("PollForIssuance", async () => + { + reissuePolled = await TryPollForIssuedCertAsync(reissueResult?.CARequestID); + }); Logger.MethodExit(LogLevel.Debug); - return reissueResult; + return reissuePolled ?? reissueResult; } flow.Fail("MissingEnrollmentParams", "Applicant Last Name not present — one-click reissue unavailable"); @@ -985,6 +1039,13 @@ public Dictionary GetCAConnectorAnnotations() Hidden = false, DefaultValue = "30", Type = "Number" + }, + [Constants.DcvPollTimeoutSeconds] = new() + { + Comments = "Max seconds to synchronously poll CSC for issuance after submitting an order (and publishing CNAME DCV). 0 disables polling (enrollment returns pending immediately; cert arrives on next sync). When >0, fast-validating orders can return the cert directly. Keep small to avoid long-blocking enrollment requests.", + Hidden = false, + DefaultValue = "0", + Type = "Number" } }; } @@ -1112,6 +1173,77 @@ private static string StripTrailingDot(string? s) return s.EndsWith('.') ? s[..^1] : s; } + /// + /// Synchronously poll CSC for issuance of the order identified by , + /// up to . Returns a GENERATED + /// carrying the issued leaf certificate if CSC issues within the window, or null if the + /// window expires (in which case the caller falls back to its pending/EXTERNALVALIDATION result). + /// No-op (returns null) when polling is disabled or the uuid is missing. + /// + private async Task TryPollForIssuedCertAsync(string? uuid) + { + if (DcvPollTimeoutSeconds <= 0) + { + Logger.LogTrace("TryPollForIssuedCertAsync: polling disabled (DcvPollTimeoutSeconds=0), skipping."); + return null; + } + + if (string.IsNullOrEmpty(uuid)) + { + Logger.LogWarning("TryPollForIssuedCertAsync: no UUID/CARequestID to poll, skipping."); + return null; + } + + var deadline = DateTime.UtcNow.AddSeconds(DcvPollTimeoutSeconds); + Logger.LogInformation("TryPollForIssuedCertAsync: polling CSC for issuance of '{Uuid}' for up to {Seconds}s (interval {Interval}s).", + uuid, DcvPollTimeoutSeconds, (int)DcvPollInterval.TotalSeconds); + + var attempt = 0; + while (DateTime.UtcNow < deadline) + { + attempt++; + AnyCAPluginCertificate record; + try + { + record = await GetSingleRecord(uuid); + } + catch (Exception ex) + { + Logger.LogWarning(ex, "TryPollForIssuedCertAsync: poll attempt {Attempt} for '{Uuid}' threw, will retry. {Error}", + attempt, uuid, ex.Message); + record = null; + } + + if (record != null) + { + Logger.LogTrace("TryPollForIssuedCertAsync: attempt {Attempt} for '{Uuid}' — status={Status}, cert={CertState}.", + attempt, uuid, record.Status, string.IsNullOrEmpty(record.Certificate) ? "empty" : "present"); + + if (record.Status == (int)EndEntityStatus.GENERATED && !string.IsNullOrEmpty(record.Certificate)) + { + Logger.LogInformation("TryPollForIssuedCertAsync: '{Uuid}' issued after {Attempt} poll(s); returning cert directly.", uuid, attempt); + return new EnrollmentResult + { + Status = (int)EndEntityStatus.GENERATED, + CARequestID = uuid, + Certificate = record.Certificate, + StatusMessage = $"Certificate issued and retrieved for order {uuid}." + }; + } + } + + // Don't sleep past the deadline. + if (DateTime.UtcNow.Add(DcvPollInterval) >= deadline) + break; + + await Task.Delay(DcvPollInterval); + } + + Logger.LogInformation("TryPollForIssuedCertAsync: '{Uuid}' not issued within {Seconds}s after {Attempts} attempt(s); falling back to pending.", + uuid, DcvPollTimeoutSeconds, attempt); + return null; + } + /// /// Publishes CNAME DCV records via the gateway framework's . /// Per-record resolution: each record is routed to whichever DNS provider plugin the framework diff --git a/cscglobal-caplugin/Constants.cs b/cscglobal-caplugin/Constants.cs index d588706..6331af9 100644 --- a/cscglobal-caplugin/Constants.cs +++ b/cscglobal-caplugin/Constants.cs @@ -15,6 +15,7 @@ public class Constants public static string DefaultPageSize = "DefaultPageSize"; public static string SyncFilterDays = "SyncFilterDays"; public static string RenewalWindowDays = "RenewalWindowDays"; + public static string DcvPollTimeoutSeconds = "DcvPollTimeoutSeconds"; } public class ProductIDs diff --git a/docsource/configuration.md b/docsource/configuration.md index 9b5961c..a8c3f38 100644 --- a/docsource/configuration.md +++ b/docsource/configuration.md @@ -22,6 +22,7 @@ BearerToken | Your CSCGlobal Bearer token for authentication | (required) DefaultPageSize | Page size for API list requests | 100 SyncFilterDays | Number of days from today used to filter certificates by expiration date during **incremental** sync. Only certificates expiring within this window are returned. Does not apply to full sync. | 5 RenewalWindowDays | Number of days before the annual order expiry date within which a **RenewOrReissue** request triggers a paid **Renewal** rather than a free **Reissue**. See [Renewal vs. Reissue Logic](#renewal-vs-reissue-logic) below. | 30 +DcvPollTimeoutSeconds | Max seconds to synchronously poll CSC for certificate issuance after submitting an order. `0` disables polling (enrollment returns pending immediately; cert arrives on the next sync). When `>0`, fast-validating orders can return the issued cert directly in the enrollment response. See [Synchronous Issuance Polling](#synchronous-issuance-polling) below. | 0 > **Note:** DNS auto-publishing for CNAME DCV is handled by the AnyCA Gateway REST framework's Domain Validation system (gateway 3.3+). It's configured in the gateway UI under **Domain Validation Configurations**, not on the CA Connection tab. See [DNS Auto-Publishing (CNAME DCV)](#dns-auto-publishing-cname-dcv). @@ -104,6 +105,19 @@ Once configured, any CSC enrollment for a domain matching one of those patterns > **Common pitfall:** If you configure the TXT/`dns-01` validator (e.g. `GoDaddyDomainValidator`) for a CSC domain, the record will publish as a **TXT** and CSC's CNAME validation will never succeed. Make sure you select the **CNAME** validator variant. +## Synchronous Issuance Polling + +CSC validates domain control asynchronously — after an order is submitted (and the CNAME DCV record published), CSC/Sectigo polls public DNS on its own schedule and issues the certificate once validation passes. By default this plugin returns a **pending** (`EXTERNALVALIDATION`) result immediately and the issued certificate is picked up on the next gateway **sync** cycle. + +For environments where DNS is published automatically (see [DNS Auto-Publishing](#dns-auto-publishing-cname-dcv)) and validation tends to complete quickly, you can have the plugin **poll CSC synchronously** at the end of enrollment and return the issued certificate directly — avoiding the wait for the next sync. + +* Set **`DcvPollTimeoutSeconds`** to the maximum number of seconds to poll (e.g. `60`). `0` (default) disables polling entirely. +* The plugin polls CSC every 10 seconds until the order is issued or the timeout is reached. +* If the certificate issues within the window, the enrollment returns it immediately with a success status. +* If the window expires, the plugin falls back to the **pending** result and the certificate arrives on the next sync — exactly as it would with polling disabled. + +**Tradeoff:** Polling blocks the enrollment request for up to `DcvPollTimeoutSeconds`. CSC validation frequently takes minutes to hours, so most orders will still fall through to pending — keep the timeout small (30–90s) to catch only the fast cases without hanging callers. This applies to New enrollments, Renewals, and Reissues. + ## Certificate Template Creation Step PLEASE NOTE, AT THIS TIME THE RAPID_SSL TEMPLATE IS NOT SUPPORTED BY THE CSC API AND WILL NOT WORK WITH THIS INTEGRATION From 95e9337d83f216f49db0705e0c28d2d62e6e6757 Mon Sep 17 00:00:00 2001 From: Keyfactor Date: Wed, 27 May 2026 15:12:54 +0000 Subject: [PATCH 22/29] Update generated docs --- README.md | 15 +++++++++++++++ integration-manifest.json | 4 ++++ 2 files changed, 19 insertions(+) diff --git a/README.md b/README.md index 36d4a34..2157d48 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and * **DefaultPageSize** - Default page size for use with the API. Default is 100 * **SyncFilterDays** - Number of days from today to filter certificates by expiration date during incremental sync. * **RenewalWindowDays** - Number of days before the annual order expiry within which a RenewOrReissue triggers a paid Renewal rather than a free Reissue. Default is 30. + * **DcvPollTimeoutSeconds** - Max seconds to synchronously poll CSC for issuance after submitting an order (and publishing CNAME DCV). 0 disables polling (enrollment returns pending immediately; cert arrives on next sync). When >0, fast-validating orders can return the cert directly. Keep small to avoid long-blocking enrollment requests. 2. PLEASE NOTE, AT THIS TIME THE RAPID_SSL TEMPLATE IS NOT SUPPORTED BY THE CSC API AND WILL NOT WORK WITH THIS INTEGRATION @@ -323,6 +324,7 @@ BearerToken | Your CSCGlobal Bearer token for authentication | (required) DefaultPageSize | Page size for API list requests | 100 SyncFilterDays | Number of days from today used to filter certificates by expiration date during **incremental** sync. Only certificates expiring within this window are returned. Does not apply to full sync. | 5 RenewalWindowDays | Number of days before the annual order expiry date within which a **RenewOrReissue** request triggers a paid **Renewal** rather than a free **Reissue**. See [Renewal vs. Reissue Logic](#renewal-vs-reissue-logic) below. | 30 +DcvPollTimeoutSeconds | Max seconds to synchronously poll CSC for certificate issuance after submitting an order. `0` disables polling (enrollment returns pending immediately; cert arrives on the next sync). When `>0`, fast-validating orders can return the issued cert directly in the enrollment response. See [Synchronous Issuance Polling](#synchronous-issuance-polling) below. | 0 > **Note:** DNS auto-publishing for CNAME DCV is handled by the AnyCA Gateway REST framework's Domain Validation system (gateway 3.3+). It's configured in the gateway UI under **Domain Validation Configurations**, not on the CA Connection tab. See [DNS Auto-Publishing (CNAME DCV)](#dns-auto-publishing-cname-dcv). @@ -405,6 +407,19 @@ Once configured, any CSC enrollment for a domain matching one of those patterns > **Common pitfall:** If you configure the TXT/`dns-01` validator (e.g. `GoDaddyDomainValidator`) for a CSC domain, the record will publish as a **TXT** and CSC's CNAME validation will never succeed. Make sure you select the **CNAME** validator variant. +## Synchronous Issuance Polling + +CSC validates domain control asynchronously — after an order is submitted (and the CNAME DCV record published), CSC/Sectigo polls public DNS on its own schedule and issues the certificate once validation passes. By default this plugin returns a **pending** (`EXTERNALVALIDATION`) result immediately and the issued certificate is picked up on the next gateway **sync** cycle. + +For environments where DNS is published automatically (see [DNS Auto-Publishing](#dns-auto-publishing-cname-dcv)) and validation tends to complete quickly, you can have the plugin **poll CSC synchronously** at the end of enrollment and return the issued certificate directly — avoiding the wait for the next sync. + +* Set **`DcvPollTimeoutSeconds`** to the maximum number of seconds to poll (e.g. `60`). `0` (default) disables polling entirely. +* The plugin polls CSC every 10 seconds until the order is issued or the timeout is reached. +* If the certificate issues within the window, the enrollment returns it immediately with a success status. +* If the window expires, the plugin falls back to the **pending** result and the certificate arrives on the next sync — exactly as it would with polling disabled. + +**Tradeoff:** Polling blocks the enrollment request for up to `DcvPollTimeoutSeconds`. CSC validation frequently takes minutes to hours, so most orders will still fall through to pending — keep the timeout small (30–90s) to catch only the fast cases without hanging callers. This applies to New enrollments, Renewals, and Reissues. + ## License diff --git a/integration-manifest.json b/integration-manifest.json index 71d13f4..3e167ff 100644 --- a/integration-manifest.json +++ b/integration-manifest.json @@ -36,6 +36,10 @@ { "name": "RenewalWindowDays", "description": "Number of days before the annual order expiry within which a RenewOrReissue triggers a paid Renewal rather than a free Reissue. Default is 30." + }, + { + "name": "DcvPollTimeoutSeconds", + "description": "Max seconds to synchronously poll CSC for issuance after submitting an order (and publishing CNAME DCV). 0 disables polling (enrollment returns pending immediately; cert arrives on next sync). When >0, fast-validating orders can return the cert directly. Keep small to avoid long-blocking enrollment requests." } ], "enrollment_config": [ From b016c6c0b61cf1666822e8327e6fe374ffee0b28 Mon Sep 17 00:00:00 2001 From: Brian Hill <76450501+bhillkeyfactor@users.noreply.github.com> Date: Tue, 14 Jul 2026 10:14:39 -0400 Subject: [PATCH 23/29] Update integration-manifest.json --- integration-manifest.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/integration-manifest.json b/integration-manifest.json index 3e167ff..2fea8e9 100644 --- a/integration-manifest.json +++ b/integration-manifest.json @@ -2,12 +2,12 @@ "$schema": "https://keyfactor.github.io/integration-manifest-schema.json", "integration_type": "anyca-plugin", "name": "CSCGlobal CAPlugin REST Gateway Plugin", - "status": "pilot", + "status": "production", "support_level": "kf-supported", "link_github": true, "update_catalog": true, "description": "CSCGlobal CAPlugin for the AnyCA REST Gateway framework", - "gateway_framework": "24.2.0", + "gateway_framework": "26.2.0", "release_project": "cscglobal-caplugin/CSCGlobalCAPlugin.csproj", "release_dir": "cscglobal-caplugin/bin/Release", "about": { @@ -103,4 +103,4 @@ ] } } -} \ No newline at end of file +} From cc9750498bf30a5866aa518784b69e565d5a6eb7 Mon Sep 17 00:00:00 2001 From: Brian Hill <76450501+bhillkeyfactor@users.noreply.github.com> Date: Tue, 14 Jul 2026 10:15:57 -0400 Subject: [PATCH 24/29] Update CSCGlobalCAPlugin.csproj --- cscglobal-caplugin/CSCGlobalCAPlugin.csproj | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.csproj b/cscglobal-caplugin/CSCGlobalCAPlugin.csproj index 01ee6c9..6436739 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.csproj +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.csproj @@ -16,30 +16,16 @@ - - - - - - - - + - - - - - - - Always - \ No newline at end of file + From 4d9ff865875b73bb44913098b05d1a07b600629b Mon Sep 17 00:00:00 2001 From: Brian Hill <76450501+bhillkeyfactor@users.noreply.github.com> Date: Tue, 14 Jul 2026 10:16:30 -0400 Subject: [PATCH 25/29] Update CSCGlobalCAPlugin.csproj --- cscglobal-caplugin/CSCGlobalCAPlugin.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.csproj b/cscglobal-caplugin/CSCGlobalCAPlugin.csproj index 6436739..e5f5ff7 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.csproj +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.csproj @@ -3,7 +3,7 @@ true - net6.0;net8.0;net10.0 + net10.0 Keyfactor.Extensions.CAPlugin.CSCGlobal true enable From 78f95a304523efba2f07cbbd174fa5d00d585a21 Mon Sep 17 00:00:00 2001 From: Brian Hill <76450501+bhillkeyfactor@users.noreply.github.com> Date: Tue, 14 Jul 2026 10:21:05 -0400 Subject: [PATCH 26/29] Update keyfactor-bootstrap-workflow-v3.yml --- .github/workflows/keyfactor-bootstrap-workflow-v3.yml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/keyfactor-bootstrap-workflow-v3.yml b/.github/workflows/keyfactor-bootstrap-workflow-v3.yml index 042ba5a..0f3d3ae 100644 --- a/.github/workflows/keyfactor-bootstrap-workflow-v3.yml +++ b/.github/workflows/keyfactor-bootstrap-workflow-v3.yml @@ -11,10 +11,17 @@ on: jobs: call-starter-workflow: - uses: keyfactor/actions/.github/workflows/starter.yml@v3.1.2 + uses: keyfactor/actions/.github/workflows/starter.yml@v5 + with: + command_token_url: ${{ vars.COMMAND_TOKEN_URL }} + command_hostname: ${{ vars.COMMAND_HOSTNAME }} + command_base_api_path: ${{ vars.COMMAND_API_PATH }} secrets: token: ${{ secrets.V2BUILDTOKEN}} - APPROVE_README_PUSH: ${{ secrets.APPROVE_README_PUSH}} gpg_key: ${{ secrets.KF_GPG_PRIVATE_KEY }} gpg_pass: ${{ secrets.KF_GPG_PASSPHRASE }} scan_token: ${{ secrets.SAST_TOKEN }} + entra_username: ${{ secrets.DOCTOOL_ENTRA_USERNAME }} + entra_password: ${{ secrets.DOCTOOL_ENTRA_PASSWD }} + command_client_id: ${{ secrets.COMMAND_CLIENT_ID }} + command_client_secret: ${{ secrets.COMMAND_CLIENT_SECRET }} From 979379bffa432e7667d48982fc3e8feca52e9047 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Tue, 14 Jul 2026 14:21:39 +0000 Subject: [PATCH 27/29] docs: auto-generate README and documentation [skip ci] --- README.md | 460 +++++++++++++++++++++++++++--------------------------- 1 file changed, 228 insertions(+), 232 deletions(-) diff --git a/README.md b/README.md index 2157d48..b06589c 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

-Integration Status: pilot +Integration Status: production Release Issues GitHub Downloads (all assets, all releases) @@ -14,7 +14,7 @@ Support - + · Requirements @@ -33,15 +33,14 @@

- This integration allows for the Synchronization, Enrollment, and Revocation of certificates from the CSCGlobal. This is the AnyGateway REST version. ## Compatibility -The CSCGlobal CAPlugin AnyCA Gateway REST plugin is compatible with the Keyfactor AnyCA Gateway REST 24.2.0 and later. +The CSCGlobal CAPlugin AnyCA Gateway REST plugin is compatible with the Keyfactor AnyCA Gateway REST 26.2.0 and later. ## Support -The CSCGlobal CAPlugin AnyCA Gateway REST plugin is supported by Keyfactor for Keyfactor customers. If you have a support issue, please open a support ticket with your Keyfactor representative. If you have a support issue, please open a support ticket via the Keyfactor Support Portal at https://support.keyfactor.com. +The CSCGlobal CAPlugin AnyCA Gateway REST plugin is supported by Keyfactor for Keyfactor customers. If you have a support issue, please open a support ticket via the Keyfactor Support Portal at https://support.keyfactor.com. > To report a problem or suggest a new feature, use the **[Issues](../../issues)** tab. If you want to contribute actual bug fixes or proposed enhancements, use the **[Pull requests](../../pulls)** tab. @@ -55,16 +54,15 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and 2. On the server hosting the AnyCA Gateway REST, download and unzip the latest [CSCGlobal CAPlugin AnyCA Gateway REST plugin](https://github.com/Keyfactor/cscglobal-caplugin/releases/latest) from GitHub. -3. Copy the unzipped directory (usually called `net6.0` or `net8.0`) to the Extensions directory: +3. Copy the unzipped directory (usually called `net10.0`) to the Extensions directory: ```shell Depending on your AnyCA Gateway REST version, copy the unzipped directory to one of the following locations: - Program Files\Keyfactor\AnyCA Gateway\AnyGatewayREST\net6.0\Extensions - Program Files\Keyfactor\AnyCA Gateway\AnyGatewayREST\net8.0\Extensions + Program Files\Keyfactor\AnyCA Gateway\AnyGatewayREST\net10.0\Extensions ``` - > The directory containing the CSCGlobal CAPlugin AnyCA Gateway REST plugin DLLs (`net6.0` or `net8.0`) can be named anything, as long as it is unique within the `Extensions` directory. + > The directory containing the CSCGlobal CAPlugin AnyCA Gateway REST plugin DLLs (`net10.0`) can be named anything, as long as it is unique within the `Extensions` directory. 4. Restart the AnyCA Gateway REST service. @@ -82,235 +80,234 @@ This integration is tested and confirmed as working for Anygateway REST 24.2 and Populate using the configuration fields collected in the [requirements](#requirements) section. - * **CscGlobalUrl** - CSCGlobal API URL - * **ApiKey** - CSCGlobal API Key - * **BearerToken** - CSCGlobal Bearer Token - * **DefaultPageSize** - Default page size for use with the API. Default is 100 - * **SyncFilterDays** - Number of days from today to filter certificates by expiration date during incremental sync. - * **RenewalWindowDays** - Number of days before the annual order expiry within which a RenewOrReissue triggers a paid Renewal rather than a free Reissue. Default is 30. - * **DcvPollTimeoutSeconds** - Max seconds to synchronously poll CSC for issuance after submitting an order (and publishing CNAME DCV). 0 disables polling (enrollment returns pending immediately; cert arrives on next sync). When >0, fast-validating orders can return the cert directly. Keep small to avoid long-blocking enrollment requests. + * **CscGlobalUrl** - CSCGlobal API URL + * **ApiKey** - CSCGlobal API Key + * **BearerToken** - CSCGlobal Bearer Token + * **DefaultPageSize** - Default page size for use with the API. Default is 100 + * **SyncFilterDays** - Number of days from today to filter certificates by expiration date during incremental sync. + * **RenewalWindowDays** - Number of days before the annual order expiry within which a RenewOrReissue triggers a paid Renewal rather than a free Reissue. Default is 30. + * **DcvPollTimeoutSeconds** - Max seconds to synchronously poll CSC for issuance after submitting an order (and publishing CNAME DCV). 0 disables polling (enrollment returns pending immediately; cert arrives on next sync). When >0, fast-validating orders can return the cert directly. Keep small to avoid long-blocking enrollment requests. 2. PLEASE NOTE, AT THIS TIME THE RAPID_SSL TEMPLATE IS NOT SUPPORTED BY THE CSC API AND WILL NOT WORK WITH THIS INTEGRATION - The following certificate templates are supported. Please set up the key sizes accordingly in the Certificate Profile menu of Anygateway REST, then enter the remaining details - and the Enrollment Fields for each Template accordingly using the Certificate Templates section in Command. If you would like to set up default values for enrollment parameters, you can do so the in the Certificate Template Menu of Anygateway REST. - If a field value is specified as both an Enrollment Field in Command and in the Certificate Template Menu in the REST Gateway, the value in the Enrollment Field will take precedence. - - CONFIG ELEMENT | DESCRIPTION - ----------------------------|------------------ - Template Short Name | CSC TrustedSecure Premium Certificate - Template Display Name | CSC TrustedSecure Premium Certificate - Friendly Name | CSC TrustedSecure Premium Certificate - Keys Size | 2048 - Enforce RFC 2818 Compliance | True - CSR Enrollment | True - Pfx Enrollment | True - - - **CSC TrustedSecure Premium Certificate - Enrollment Fields** - - NAME | DATA TYPE | VALUES - -----|--------------|----------------- - Term | Multiple Choice | 12,24 - Applicant First Name | String | N/A - Applicant Last Name | String | N/A - Applicant Email Address | String | N/A - Applicant Phone | String | N/A - Domain Control Validation Method | Multiple Choice | EMAIL - Organization Contact | Multiple Choice | Get From CSC Differs For Clients - Business Unit | Multiple Choice | Get From CSC Differs For Clients - Notification Email(s) Comma Separated | String | N/A - CN DCV Email | String | N/A - - **CSC TrustedSecure EV Certificate - Details Tab** - - CONFIG ELEMENT | DESCRIPTION - ----------------------------|------------------ - Template Short Name | CSC TrustedSecure EV Certificate - Template Display Name | CSC TrustedSecure EV Certificate - Friendly Name | CSC TrustedSecure EV Certificate - Keys Size | 2048 - Enforce RFC 2818 Compliance | True - CSR Enrollment | True - Pfx Enrollment | True - - - **CSC TrustedSecure EV Certificate - Enrollment Fields** - - NAME | DATA TYPE | VALUES - -----|--------------|----------------- - Term | Multiple Choice | 12,24 - Applicant First Name | String | N/A - Applicant Last Name | String | N/A - Applicant Email Address | String | N/A - Applicant Phone | String | N/A - Domain Control Validation Method | Multiple Choice | EMAIL - Organization Contact | Multiple Choice | Get From CSC Differs For Clients - Business Unit | Multiple Choice | Get From CSC Differs For Clients - Notification Email(s) Comma Separated | String | N/A - CN DCV Email | String | N/A - Organization Country | String | N/A - - **CSC TrustedSecure UC Certificate - Details Tab** - - CONFIG ELEMENT | DESCRIPTION - ----------------------------|------------------ - Template Short Name | CSC TrustedSecure UC Certificate - Template Display Name | CSC TrustedSecure UC Certificate - Friendly Name | CSC TrustedSecure UC Certificate - Keys Size | 2048 - Enforce RFC 2818 Compliance | True - CSR Enrollment | True - Pfx Enrollment | True - - - **CSC TrustedSecure UC Certificate - Enrollment Fields** - - NAME | DATA TYPE | VALUES - -----|--------------|----------------- - Term | Multiple Choice | 12,24 - Applicant First Name | String | N/A - Applicant Last Name | String | N/A - Applicant Email Address | String | N/A - Applicant Phone | String | N/A - Domain Control Validation Method | Multiple Choice | EMAIL - Organization Contact | Multiple Choice | Get From CSC Differs For Clients - Business Unit | Multiple Choice | Get From CSC Differs For Clients - Notification Email(s) Comma Separated | String | N/A - CN DCV Email | String | N/A - Addtl Sans Comma Separated DCV Emails | String | N/A - - - **CSC TrustedSecure Premium Wildcard Certificate - Details Tab** - - CONFIG ELEMENT | DESCRIPTION - ----------------------------|------------------ - Template Short Name | CSC TrustedSecure Premium Wildcard Certificate - Template Display Name | CSC TrustedSecure Premium Wildcard Certificate - Friendly Name | CSC TrustedSecure Premium Wildcard Certificate - Keys Size | 2048 - Enforce RFC 2818 Compliance | True - CSR Enrollment | True - Pfx Enrollment | True - - - **CSC TrustedSecure Premium Wildcard Certificate - Enrollment Fields** - - NAME | DATA TYPE | VALUES - -----|--------------|----------------- - Term | Multiple Choice | 12,24 - Applicant First Name | String | N/A - Applicant Last Name | String | N/A - Applicant Email Address | String | N/A - Applicant Phone | String | N/A - Domain Control Validation Method | Multiple Choice | EMAIL - Organization Contact | Multiple Choice | Get From CSC Differs For Clients - Business Unit | Multiple Choice | Get From CSC Differs For Clients - Notification Email(s) Comma Separated | String | N/A - CN DCV Email | String | N/A - - **CSC TrustedSecure Domain Validated SSL - Details Tab** - - CONFIG ELEMENT | DESCRIPTION - ----------------------------|------------------ - Template Short Name | CSC TrustedSecure Domain Validated SSL - Template Display Name | CSC TrustedSecure Domain Validated SSL - Friendly Name | CSC TrustedSecure Domain Validated SSL - Keys Size | 2048 - Enforce RFC 2818 Compliance | True - CSR Enrollment | True - Pfx Enrollment | True - - - **CSC TrustedSecure Domain Validated SSL - Enrollment Fields** - - NAME | DATA TYPE | VALUES - -----|--------------|----------------- - Term | Multiple Choice | 12,24 - Applicant First Name | String | N/A - Applicant Last Name | String | N/A - Applicant Email Address | String | N/A - Applicant Phone | String | N/A - Domain Control Validation Method | Multiple Choice | EMAIL - Organization Contact | Multiple Choice | Get From CSC Differs For Clients - Business Unit | Multiple Choice | Get From CSC Differs For Clients - Notification Email(s) Comma Separated | String | N/A - CN DCV Email | String | N/A - - **CSC TrustedSecure Domain Validated Wildcard SSL - Details Tab** - - CONFIG ELEMENT | DESCRIPTION - ----------------------------|------------------ - Template Short Name | CSC TrustedSecure Domain Validated Wildcard SSL - Template Display Name | CSC TrustedSecure Domain Validated Wildcard SSL - Friendly Name | CSC TrustedSecure Domain Validated Wildcard SSL - Keys Size | 2048 - Enforce RFC 2818 Compliance | True - CSR Enrollment | True - Pfx Enrollment | True - - - **CSC TrustedSecure Domain Validated Wildcard SSL - Enrollment Fields** - - NAME | DATA TYPE | VALUES - -----|--------------|----------------- - Term | Multiple Choice | 12,24 - Applicant First Name | String | N/A - Applicant Last Name | String | N/A - Applicant Email Address | String | N/A - Applicant Phone | String | N/A - Domain Control Validation Method | Multiple Choice | EMAIL - Organization Contact | Multiple Choice | Get From CSC Differs For Clients - Business Unit | Multiple Choice | Get From CSC Differs For Clients - Notification Email(s) Comma Separated | String | N/A - CN DCV Email | String | N/A - - **CSC TrustedSecure Domain Validated UC Certificate - Details Tab** - - CONFIG ELEMENT | DESCRIPTION - ----------------------------|------------------ - Template Short Name | CSC TrustedSecure Domain Validated UC Certificate - Template Display Name | CSC TrustedSecure Domain Validated UC Certificate - Friendly Name | CSC TrustedSecure Domain Validated UC Certificate - Keys Size | 2048 - Enforce RFC 2818 Compliance | True - CSR Enrollment | True - Pfx Enrollment | True - - - **CSC TrustedSecure Domain Validated UC Certificate - Enrollment Fields** - - NAME | DATA TYPE | VALUES - -----|--------------|----------------- - Term | Multiple Choice | 12,24 - Applicant First Name | String | N/A - Applicant Last Name | String | N/A - Applicant Email Address | String | N/A - Applicant Phone | String | N/A - Domain Control Validation Method | Multiple Choice | EMAIL - Organization Contact | Multiple Choice | Get From CSC Differs For Clients - Business Unit | Multiple Choice | Get From CSC Differs For Clients - Notification Email(s) Comma Separated | String | N/A - CN DCV Email | String | N/A - Addtl Sans Comma Separated DCV Emails | String | N/A +The following certificate templates are supported. Please set up the key sizes accordingly in the Certificate Profile menu of Anygateway REST, then enter the remaining details +and the Enrollment Fields for each Template accordingly using the Certificate Templates section in Command. If you would like to set up default values for enrollment parameters, you can do so the in the Certificate Template Menu of Anygateway REST. +If a field value is specified as both an Enrollment Field in Command and in the Certificate Template Menu in the REST Gateway, the value in the Enrollment Field will take precedence. + +CONFIG ELEMENT | DESCRIPTION +----------------------------|------------------ +Template Short Name | CSC TrustedSecure Premium Certificate +Template Display Name | CSC TrustedSecure Premium Certificate +Friendly Name | CSC TrustedSecure Premium Certificate +Keys Size | 2048 +Enforce RFC 2818 Compliance | True +CSR Enrollment | True +Pfx Enrollment | True + + +**CSC TrustedSecure Premium Certificate - Enrollment Fields** + +NAME | DATA TYPE | VALUES +-----|--------------|----------------- +Term | Multiple Choice | 12,24 +Applicant First Name | String | N/A +Applicant Last Name | String | N/A +Applicant Email Address | String | N/A +Applicant Phone | String | N/A +Domain Control Validation Method | Multiple Choice | EMAIL +Organization Contact | Multiple Choice | Get From CSC Differs For Clients +Business Unit | Multiple Choice | Get From CSC Differs For Clients +Notification Email(s) Comma Separated | String | N/A +CN DCV Email | String | N/A + +**CSC TrustedSecure EV Certificate - Details Tab** + +CONFIG ELEMENT | DESCRIPTION +----------------------------|------------------ +Template Short Name | CSC TrustedSecure EV Certificate +Template Display Name | CSC TrustedSecure EV Certificate +Friendly Name | CSC TrustedSecure EV Certificate +Keys Size | 2048 +Enforce RFC 2818 Compliance | True +CSR Enrollment | True +Pfx Enrollment | True + + +**CSC TrustedSecure EV Certificate - Enrollment Fields** + +NAME | DATA TYPE | VALUES +-----|--------------|----------------- +Term | Multiple Choice | 12,24 +Applicant First Name | String | N/A +Applicant Last Name | String | N/A +Applicant Email Address | String | N/A +Applicant Phone | String | N/A +Domain Control Validation Method | Multiple Choice | EMAIL +Organization Contact | Multiple Choice | Get From CSC Differs For Clients +Business Unit | Multiple Choice | Get From CSC Differs For Clients +Notification Email(s) Comma Separated | String | N/A +CN DCV Email | String | N/A +Organization Country | String | N/A + +**CSC TrustedSecure UC Certificate - Details Tab** + +CONFIG ELEMENT | DESCRIPTION +----------------------------|------------------ +Template Short Name | CSC TrustedSecure UC Certificate +Template Display Name | CSC TrustedSecure UC Certificate +Friendly Name | CSC TrustedSecure UC Certificate +Keys Size | 2048 +Enforce RFC 2818 Compliance | True +CSR Enrollment | True +Pfx Enrollment | True + + +**CSC TrustedSecure UC Certificate - Enrollment Fields** + +NAME | DATA TYPE | VALUES +-----|--------------|----------------- +Term | Multiple Choice | 12,24 +Applicant First Name | String | N/A +Applicant Last Name | String | N/A +Applicant Email Address | String | N/A +Applicant Phone | String | N/A +Domain Control Validation Method | Multiple Choice | EMAIL +Organization Contact | Multiple Choice | Get From CSC Differs For Clients +Business Unit | Multiple Choice | Get From CSC Differs For Clients +Notification Email(s) Comma Separated | String | N/A +CN DCV Email | String | N/A +Addtl Sans Comma Separated DCV Emails | String | N/A + + +**CSC TrustedSecure Premium Wildcard Certificate - Details Tab** + +CONFIG ELEMENT | DESCRIPTION +----------------------------|------------------ +Template Short Name | CSC TrustedSecure Premium Wildcard Certificate +Template Display Name | CSC TrustedSecure Premium Wildcard Certificate +Friendly Name | CSC TrustedSecure Premium Wildcard Certificate +Keys Size | 2048 +Enforce RFC 2818 Compliance | True +CSR Enrollment | True +Pfx Enrollment | True + + +**CSC TrustedSecure Premium Wildcard Certificate - Enrollment Fields** + +NAME | DATA TYPE | VALUES +-----|--------------|----------------- +Term | Multiple Choice | 12,24 +Applicant First Name | String | N/A +Applicant Last Name | String | N/A +Applicant Email Address | String | N/A +Applicant Phone | String | N/A +Domain Control Validation Method | Multiple Choice | EMAIL +Organization Contact | Multiple Choice | Get From CSC Differs For Clients +Business Unit | Multiple Choice | Get From CSC Differs For Clients +Notification Email(s) Comma Separated | String | N/A +CN DCV Email | String | N/A + +**CSC TrustedSecure Domain Validated SSL - Details Tab** + +CONFIG ELEMENT | DESCRIPTION +----------------------------|------------------ +Template Short Name | CSC TrustedSecure Domain Validated SSL +Template Display Name | CSC TrustedSecure Domain Validated SSL +Friendly Name | CSC TrustedSecure Domain Validated SSL +Keys Size | 2048 +Enforce RFC 2818 Compliance | True +CSR Enrollment | True +Pfx Enrollment | True + + +**CSC TrustedSecure Domain Validated SSL - Enrollment Fields** + +NAME | DATA TYPE | VALUES +-----|--------------|----------------- +Term | Multiple Choice | 12,24 +Applicant First Name | String | N/A +Applicant Last Name | String | N/A +Applicant Email Address | String | N/A +Applicant Phone | String | N/A +Domain Control Validation Method | Multiple Choice | EMAIL +Organization Contact | Multiple Choice | Get From CSC Differs For Clients +Business Unit | Multiple Choice | Get From CSC Differs For Clients +Notification Email(s) Comma Separated | String | N/A +CN DCV Email | String | N/A + +**CSC TrustedSecure Domain Validated Wildcard SSL - Details Tab** + +CONFIG ELEMENT | DESCRIPTION +----------------------------|------------------ +Template Short Name | CSC TrustedSecure Domain Validated Wildcard SSL +Template Display Name | CSC TrustedSecure Domain Validated Wildcard SSL +Friendly Name | CSC TrustedSecure Domain Validated Wildcard SSL +Keys Size | 2048 +Enforce RFC 2818 Compliance | True +CSR Enrollment | True +Pfx Enrollment | True + + +**CSC TrustedSecure Domain Validated Wildcard SSL - Enrollment Fields** + +NAME | DATA TYPE | VALUES +-----|--------------|----------------- +Term | Multiple Choice | 12,24 +Applicant First Name | String | N/A +Applicant Last Name | String | N/A +Applicant Email Address | String | N/A +Applicant Phone | String | N/A +Domain Control Validation Method | Multiple Choice | EMAIL +Organization Contact | Multiple Choice | Get From CSC Differs For Clients +Business Unit | Multiple Choice | Get From CSC Differs For Clients +Notification Email(s) Comma Separated | String | N/A +CN DCV Email | String | N/A + +**CSC TrustedSecure Domain Validated UC Certificate - Details Tab** + +CONFIG ELEMENT | DESCRIPTION +----------------------------|------------------ +Template Short Name | CSC TrustedSecure Domain Validated UC Certificate +Template Display Name | CSC TrustedSecure Domain Validated UC Certificate +Friendly Name | CSC TrustedSecure Domain Validated UC Certificate +Keys Size | 2048 +Enforce RFC 2818 Compliance | True +CSR Enrollment | True +Pfx Enrollment | True + + +**CSC TrustedSecure Domain Validated UC Certificate - Enrollment Fields** + +NAME | DATA TYPE | VALUES +-----|--------------|----------------- +Term | Multiple Choice | 12,24 +Applicant First Name | String | N/A +Applicant Last Name | String | N/A +Applicant Email Address | String | N/A +Applicant Phone | String | N/A +Domain Control Validation Method | Multiple Choice | EMAIL +Organization Contact | Multiple Choice | Get From CSC Differs For Clients +Business Unit | Multiple Choice | Get From CSC Differs For Clients +Notification Email(s) Comma Separated | String | N/A +CN DCV Email | String | N/A +Addtl Sans Comma Separated DCV Emails | String | N/A 3. Follow the [official Keyfactor documentation](https://software.keyfactor.com/Guides/AnyCAGatewayREST/Content/AnyCAGatewayREST/AddCA-Keyfactor.htm) to add each defined Certificate Authority to Keyfactor Command and import the newly defined Certificate Templates. 4. In Keyfactor Command (v12.3+), for each imported Certificate Template, follow the [official documentation](https://software.keyfactor.com/Core-OnPrem/Current/Content/ReferenceGuide/Configuring%20Template%20Options.htm) to define enrollment fields for each of the following parameters: - * **Term** - OPTIONAL: Certificate term (e.g. 12 or 24 months) - * **Applicant First Name** - OPTIONAL: Applicant First Name - * **Applicant Last Name** - OPTIONAL: Applicant Last Name - * **Applicant Email Address** - OPTIONAL: Applicant Email Address - * **Applicant Phone** - OPTIONAL: Applicant Phone (+nn.nnnnnnnn) - * **Domain Control Validation Method** - OPTIONAL: Domain Control Validation Method (e.g. EMAIL) - * **Organization Contact** - OPTIONAL: Organization Contact (selected from CSC configuration) - * **Business Unit** - OPTIONAL: Business Unit (selected from CSC configuration) - * **Notification Email(s) Comma Separated** - OPTIONAL: Notification Email(s), comma separated - * **CN DCV Email** - OPTIONAL: CN DCV Email (e.g. admin@yourdomain.com) - * **Organization Country** - OPTIONAL: Organization Country - * **Addtl Sans Comma Separated DCV Emails** - OPTIONAL: Additional SANs DCV Emails, comma separated - + * **Term** - OPTIONAL: Certificate term (e.g. 12 or 24 months) + * **Applicant First Name** - OPTIONAL: Applicant First Name + * **Applicant Last Name** - OPTIONAL: Applicant Last Name + * **Applicant Email Address** - OPTIONAL: Applicant Email Address + * **Applicant Phone** - OPTIONAL: Applicant Phone (+nn.nnnnnnnn) + * **Domain Control Validation Method** - OPTIONAL: Domain Control Validation Method (e.g. EMAIL) + * **Organization Contact** - OPTIONAL: Organization Contact (selected from CSC configuration) + * **Business Unit** - OPTIONAL: Business Unit (selected from CSC configuration) + * **Notification Email(s) Comma Separated** - OPTIONAL: Notification Email(s), comma separated + * **CN DCV Email** - OPTIONAL: CN DCV Email (e.g. admin@yourdomain.com) + * **Organization Country** - OPTIONAL: Organization Country + * **Addtl Sans Comma Separated DCV Emails** - OPTIONAL: Additional SANs DCV Emails, comma separated ## CA Connection Configuration @@ -420,11 +417,10 @@ For environments where DNS is published automatically (see [DNS Auto-Publishing] **Tradeoff:** Polling blocks the enrollment request for up to `DcvPollTimeoutSeconds`. CSC validation frequently takes minutes to hours, so most orders will still fall through to pending — keep the timeout small (30–90s) to catch only the fast cases without hanging callers. This applies to New enrollments, Renewals, and Reissues. - ## License Apache License 2.0, see [LICENSE](LICENSE). ## Related Integrations -See all [Keyfactor Any CA Gateways (REST)](https://github.com/orgs/Keyfactor/repositories?q=anycagateway). \ No newline at end of file +See all [Keyfactor Any CA Gateways (REST)](https://github.com/orgs/Keyfactor/repositories?q=anycagateway). From a1275f6fd62c55346c5cc9638c3c2bb4292a05e3 Mon Sep 17 00:00:00 2001 From: Brian Hill Date: Tue, 14 Jul 2026 11:03:42 -0400 Subject: [PATCH 28/29] Add Enabled CA connection flag Adds the standard Enabled boolean field to the CA Connection settings, matching the pattern used by every other Keyfactor CA plugin (SSL Store, Digicert, HydrantId, GCP CAS, Idnomic, etc.). Purpose: allow ops to create the CA record before all API credentials are available. When Enabled=false, the plugin short-circuits: - Initialize: skips CscGlobalClient construction (no valid creds needed) - Ping: no-op, logs a warning - ValidateCAConnectionInfo / ValidateProductInfo: skip validation - Synchronize: completes the buffer immediately - Enroll: returns FAILED with a clear message - Revoke: throws InvalidOperationException with a clear message Default is true so existing deployments that don't set the key continue to function without change. Reads the value from incoming connectionInfo in the Validate* methods so an operator editing the CA sees consistent behavior with the current form state. --- cscglobal-caplugin/CSCGlobalCAPlugin.cs | 123 ++++++++++++++++++++++-- cscglobal-caplugin/Constants.cs | 1 + docsource/configuration.md | 1 + 3 files changed, 117 insertions(+), 8 deletions(-) diff --git a/cscglobal-caplugin/CSCGlobalCAPlugin.cs b/cscglobal-caplugin/CSCGlobalCAPlugin.cs index 4ff69fd..c22aa32 100644 --- a/cscglobal-caplugin/CSCGlobalCAPlugin.cs +++ b/cscglobal-caplugin/CSCGlobalCAPlugin.cs @@ -65,6 +65,15 @@ public CSCGlobalCAPlugin(IDomainValidatorFactory validatorFactory) private ICscGlobalClient CscGlobalClient { get; set; } + /// + /// Whether the CA is enabled. When false, the plugin returns early from Ping, + /// ValidateCAConnectionInfo, ValidateProductInfo, Synchronize, Enroll, and Revoke without + /// calling CSC. Primarily used to allow creation of the CA record prior to configuration + /// information being available (standard field across Keyfactor CA plugins). Defaults to true + /// so existing deployments that don't set this key continue to function. + /// + public bool Enabled { get; set; } = true; + public int SyncFilterDays { get; set; } public int RenewalWindowDays { get; set; } @@ -96,13 +105,6 @@ public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDa _certificateDataReader = certificateDataReader; - flow.Step("CreateCscGlobalClient", () => - { - Logger.LogTrace("Creating CscGlobalClient from configProvider..."); - CscGlobalClient = new CscGlobalClient(configProvider); - Logger.LogTrace("CscGlobalClient created successfully."); - }); - flow.Step("ValidateConnectionData", () => { if (configProvider.CAConnectionData == null) @@ -113,6 +115,41 @@ public void Initialize(IAnyCAPluginConfigProvider configProvider, ICertificateDa Logger.LogTrace("CAConnectionData keys: {Keys}", string.Join(", ", configProvider.CAConnectionData.Keys)); }); + flow.Step("ReadEnabled", () => + { + Enabled = true; // default + if (configProvider.CAConnectionData.TryGetValue(Constants.Enabled, out var enabledObj)) + { + Logger.LogTrace("Enabled raw value: '{Value}'", enabledObj?.ToString() ?? "(null)"); + if (bool.TryParse(enabledObj?.ToString(), out var parsed)) + Enabled = parsed; + else + Logger.LogWarning("Enabled value '{Value}' could not be parsed as bool, defaulting to true.", enabledObj); + } + else + { + Logger.LogTrace("Enabled key not found in CAConnectionData, defaulting to true."); + } + Logger.LogInformation("CA is {State}.", Enabled ? "Enabled" : "Disabled"); + }, $"Enabled={Enabled}"); + + // Construct the CSC client only when enabled. When disabled we allow Initialize to complete + // without valid API credentials — this is the whole point of the Enabled toggle (so ops can + // create the CA record before credentials are available). + if (Enabled) + { + flow.Step("CreateCscGlobalClient", () => + { + Logger.LogTrace("Creating CscGlobalClient from configProvider..."); + CscGlobalClient = new CscGlobalClient(configProvider); + Logger.LogTrace("CscGlobalClient created successfully."); + }); + } + else + { + flow.Skip("CreateCscGlobalClient", "CA is Disabled"); + } + flow.Step("ReadSyncFilterDays", () => { if (configProvider.CAConnectionData.ContainsKey(Constants.SyncFilterDays)) @@ -297,6 +334,14 @@ public async Task Synchronize(BlockingCollection blockin if (blockingBuffer == null) throw new ArgumentNullException(nameof(blockingBuffer), "blockingBuffer cannot be null in Synchronize"); + if (!Enabled) + { + Logger.LogWarning("The CA is currently in the Disabled state. It must be Enabled to perform operations. Skipping Synchronize."); + blockingBuffer.CompleteAdding(); + Logger.MethodExit(LogLevel.Debug); + return; + } + try { if (fullSync) @@ -463,6 +508,12 @@ public async Task Revoke(string caRequestID, string hexSerialNumber, uint r Logger.LogTrace("Revoke called with caRequestID='{CaRequestId}', hexSerialNumber='{SerialNumber}', revocationReason={Reason}", caRequestID ?? "(null)", hexSerialNumber ?? "(null)", revocationReason); + if (!Enabled) + { + Logger.LogWarning("The CA is currently in the Disabled state. It must be Enabled to perform operations. Rejecting Revoke."); + throw new InvalidOperationException("The CSC Global CA is in the Disabled state. Enable it to perform revocations."); + } + flow.Step("ValidateInput", () => { if (string.IsNullOrEmpty(caRequestID)) @@ -539,6 +590,17 @@ public async Task Enroll(string csr, string subject, Dictionar san?.Count ?? 0, productInfo == null ? "NULL" : "present"); + if (!Enabled) + { + flow.Fail("Disabled", "CA is Disabled"); + Logger.LogWarning("The CA is currently in the Disabled state. It must be Enabled to perform operations. Rejecting Enroll."); + return new EnrollmentResult + { + Status = (int)EndEntityStatus.FAILED, + StatusMessage = "The CSC Global CA is in the Disabled state. Enable it to perform enrollments." + }; + } + flow.Step("ValidateInputs", () => { if (productInfo == null) @@ -927,7 +989,15 @@ await flow.StepAsync("PollForIssuance", async () => public async Task Ping() { Logger.MethodEntry(); - Logger.LogTrace("Ping: CscGlobalClient is {Null}", CscGlobalClient == null ? "NULL" : "present"); + Logger.LogTrace("Ping: Enabled={Enabled}, CscGlobalClient is {Null}", Enabled, CscGlobalClient == null ? "NULL" : "present"); + + if (!Enabled) + { + Logger.LogWarning("The CA is currently in the Disabled state. It must be Enabled to perform operations. Skipping Ping."); + Logger.MethodExit(); + return; + } + try { Logger.LogInformation("Ping request received"); @@ -955,6 +1025,21 @@ public async Task ValidateCAConnectionInfo(Dictionary connection throw new ArgumentNullException(nameof(connectionInfo), "connectionInfo cannot be null."); } + // Honor the Enabled flag from the incoming connectionInfo (which may differ from Initialize's + // snapshot when the operator is currently editing the CA). If disabled, skip validation so + // the CA can be saved without valid credentials. + var incomingEnabled = true; + if (connectionInfo.TryGetValue(Constants.Enabled, out var enabledObj) && + bool.TryParse(enabledObj?.ToString(), out var parsed)) + incomingEnabled = parsed; + + if (!incomingEnabled) + { + Logger.LogWarning("The CA is currently in the Disabled state. It must be Enabled to perform operations. Skipping ValidateCAConnectionInfo."); + Logger.MethodExit(LogLevel.Debug); + return; + } + Logger.MethodExit(LogLevel.Debug); } @@ -973,6 +1058,21 @@ public async Task ValidateProductInfo(EnrollmentProductInfo productInfo, throw new ArgumentNullException(nameof(productInfo), "productInfo cannot be null."); } + // Honor the Enabled flag from the incoming connectionInfo. If the CA is disabled, skip + // validation so a template can be saved on a disabled CA (pre-configuration workflow). + var incomingEnabled = true; + if (connectionInfo != null && + connectionInfo.TryGetValue(Constants.Enabled, out var enabledObj) && + bool.TryParse(enabledObj?.ToString(), out var parsed)) + incomingEnabled = parsed; + + if (!incomingEnabled) + { + Logger.LogWarning("The CA is currently in the Disabled state. It must be Enabled to perform operations. Skipping ValidateProductInfo."); + Logger.MethodExit(LogLevel.Debug); + return; + } + if (string.IsNullOrEmpty(productInfo.ProductID)) { Logger.LogError("ValidateProductInfo: productInfo.ProductID is null or empty."); @@ -998,6 +1098,13 @@ public Dictionary GetCAConnectorAnnotations() { return new Dictionary { + [Constants.Enabled] = new() + { + Comments = "Flag to Enable or Disable gateway functionality. Disabling is primarily used to allow creation of the CA prior to configuration information being available.", + Hidden = false, + DefaultValue = true, + Type = "Boolean" + }, [Constants.CscGlobalUrl] = new() { Comments = "CSCGlobal API URL", diff --git a/cscglobal-caplugin/Constants.cs b/cscglobal-caplugin/Constants.cs index 6331af9..dc10866 100644 --- a/cscglobal-caplugin/Constants.cs +++ b/cscglobal-caplugin/Constants.cs @@ -9,6 +9,7 @@ namespace Keyfactor.Extensions.CAPlugin.CSCGlobal; public class Constants { + public static string Enabled = "Enabled"; public static string CscGlobalUrl = "CscGlobalUrl"; public static string CscGlobalApiKey = "ApiKey"; public static string BearerToken = "BearerToken"; diff --git a/docsource/configuration.md b/docsource/configuration.md index a8c3f38..5dee9d3 100644 --- a/docsource/configuration.md +++ b/docsource/configuration.md @@ -16,6 +16,7 @@ When defining the Certificate Authority in the AnyCA Gateway REST portal, config CONFIG ELEMENT | DESCRIPTION | DEFAULT ---------------|-------------|-------- +Enabled | Flag to Enable or Disable gateway functionality. Set to `false` to allow creating the CA record before configuration information is available; the plugin then short-circuits Ping, Sync, Enroll, and Revoke with a warning until it is re-enabled. | `true` CscGlobalUrl | The base URL for the CSCGlobal API (e.g. `https://apis.cscglobal.com`) | (required) ApiKey | Your CSCGlobal API key | (required) BearerToken | Your CSCGlobal Bearer token for authentication | (required) From c03418010c64eccc8c0fa31f87e8d401f89070a1 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Tue, 14 Jul 2026 15:04:26 +0000 Subject: [PATCH 29/29] docs: auto-generate README and documentation [skip ci] --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b06589c..5effcf2 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,7 @@ When defining the Certificate Authority in the AnyCA Gateway REST portal, config CONFIG ELEMENT | DESCRIPTION | DEFAULT ---------------|-------------|-------- +Enabled | Flag to Enable or Disable gateway functionality. Set to `false` to allow creating the CA record before configuration information is available; the plugin then short-circuits Ping, Sync, Enroll, and Revoke with a warning until it is re-enabled. | `true` CscGlobalUrl | The base URL for the CSCGlobal API (e.g. `https://apis.cscglobal.com`) | (required) ApiKey | Your CSCGlobal API key | (required) BearerToken | Your CSCGlobal Bearer token for authentication | (required)