diff --git a/CERTInext.IntegrationTests/INTEGRATION_TESTING.md b/CERTInext.IntegrationTests/INTEGRATION_TESTING.md index dd7a1d8..3ae9abc 100644 --- a/CERTInext.IntegrationTests/INTEGRATION_TESTING.md +++ b/CERTInext.IntegrationTests/INTEGRATION_TESTING.md @@ -149,6 +149,7 @@ matching flag in your shell. These flags are deliberately **not** read from `~/. | `CERTINEXT_V2_RUN_BULK_TEST=1` | `V2DcvLifecycleTests.BulkV2Enrollment_AllOrdersIssue_AndPaginationWorks` (also needs Cloudflare); tune with `CERTINEXT_V2_BULK_TEST_COUNT` and `CERTINEXT_V2_BULK_TEST_PARALLEL` | | `CERTINEXT_V2_LIFECYCLE_DV_UCC=1`, `_OV=1`, `_OV_UCC=1`, `_EV=1`, `_WILDCARD_DV=1`, `_RENEW_REISSUE=1` | The matching `V2FullLifecycleTests` method; the OV and OV UCC tests also need `CERTINEXT_ORG_NUMBER`, and the EV test needs its own pre-vetted `CERTINEXT_EV_ORG_NUMBER` | | `CERTINEXT_V2_LIFECYCLE_FRESH_DCV=1` | `V2FreshDomainDcvLifecycleTests` (also needs Cloudflare and `CERTINEXT_V2_FRESH_DCV_PARENT`, the parent domain that fresh subdomains are created under) | +| `CERTINEXT_ALT_ENV_ENROLL=1` | `V2AltEnvEnrollTests` order-placing tests, against the account in `CERTINEXT_ALT_ENV_FILE` (a separate env file, not `~/.env_certinext[_v2]`). Also needs `CERTINEXT_ALT_ENV_DOMAIN`; optional `CERTINEXT_ALT_ENV_WILDCARD=1`, `CERTINEXT_ALT_ENV_EXTRA_SANS` (UCC), `CERTINEXT_ALT_ENV_VARIANT=ov|ev` with `CERTINEXT_ALT_ENV_ORG_NUMBER` (direct API test only), `CERTINEXT_ALT_ENV_GROUP_NUMBER` / `CERTINEXT_ALT_ENV_OMIT_GROUP=1`, `CERTINEXT_ALT_ENV_PRODUCT_CODE`, `CERTINEXT_ALT_ENV_ORDER_ID`. Orders are not revoked. The catalog and groups probes need only `CERTINEXT_ALT_ENV_FILE`; the read-only incremental-sync test also needs `CERTINEXT_ALT_ENV_SYNC_ORDER_IDS` (comma-separated issued orders; optional `CERTINEXT_ALT_ENV_SYNC_LAST_HOURS`, default 1) | | `CERTINEXT_V2_INLINE_CSR=0` | Not a test gate: runs the V2 enrollment tests (`V2LifecycleTests`, `V2FullLifecycleTests`, `V2DcvLifecycleTests`, `V2FreshDomainDcvLifecycleTests`, `PrivatePkiV2LiveTests`) with the `V2InlineCsr` connector setting off (SSL/TLS two-call: create, then submit CSR). Unset runs the default single-call flow; run the suite once in each mode. Private PKI stays two-call either way | | `CERTINEXT_PRIVATE_PKI_LIVE=1` | `PrivatePkiV2LiveTests.PrivatePki_V2_EnrollIntranetSsl_ThenRevoke_Live`; override the product code and CN with `CERTINEXT_PRIVATE_PKI_PRODUCT_CODE` and `CERTINEXT_PRIVATE_PKI_CN`, the variant with `CERTINEXT_PRIVATE_PKI_VARIANT`, and set `CERTINEXT_PRIVATE_PKI_LEAVE_PENDING=1` (process env) to leave an unissued order pending for manual approval | | `CERTINEXT_V2_OPS_TESTS=1` | `V2OrderWindowSweepTests` — see below | diff --git a/CERTInext.IntegrationTests/IntegrationTestFixture.cs b/CERTInext.IntegrationTests/IntegrationTestFixture.cs index 5feb52b..e6c400d 100644 --- a/CERTInext.IntegrationTests/IntegrationTestFixture.cs +++ b/CERTInext.IntegrationTests/IntegrationTestFixture.cs @@ -55,6 +55,8 @@ public sealed class IntegrationTestFixture : IDisposable "CERTINEXT_V2_LIFECYCLE_WILDCARD_DV", "CERTINEXT_V2_LIFECYCLE_RENEW_REISSUE", "CERTINEXT_V2_LIFECYCLE_FRESH_DCV", + // V2AltEnvEnrollTests: places real orders on the account in CERTINEXT_ALT_ENV_FILE. + "CERTINEXT_ALT_ENV_ENROLL", // Selects the V2InlineCsr connector setting for the V2 enrollment tests (see V2EnvHelper). "CERTINEXT_V2_INLINE_CSR", // Issue 0090 V2 place-order latency experiment (places real sandbox orders). diff --git a/CERTInext.IntegrationTests/TESTING.md b/CERTInext.IntegrationTests/TESTING.md index e7a313b..76f2133 100644 --- a/CERTInext.IntegrationTests/TESTING.md +++ b/CERTInext.IntegrationTests/TESTING.md @@ -104,6 +104,7 @@ only. `PrivatePki_V2_*`, the validity/latency/inline-CSR experiments, and the re | `V2DcvLifecycleTests` | `DcvEnroll_V2_CompletesWithoutThrowing`, `EnrollWithoutDcv_V2_DoesNotInvokeDnsProvider`, `GetSingleRecord_V2_DrivesDcvForPendingOrder`, `EnrollWithDcvOn_V2_OrderIssuedEndToEnd_AndAppearsInSync` | The V2 counterparts of the V1 DCV tests (`CERTINEXT_V2_PENDING_ORDER_ID` for the single-record one) | | | `EnrollWithDcvOn_V2_IssuesPerKeyAlgorithm` | **Opt-in** (`CERTINEXT_V2_ALGO_MATRIX`) | | | `BulkV2Enrollment_AllOrdersIssue_AndPaginationWorks` | **Opt-in** (`CERTINEXT_V2_RUN_BULK_TEST`) | +| `V2AltEnvEnrollTests` | `ListCatalog_FromAltEnvFile`, `Raw_ListIdentityAndGroups_FromAltEnvFile`, `Raw_PlaceSslOrder_FromAltEnvFile`, `Enroll_V2_Dv_FromAltEnvFile_Issues`, `Sync_V2_Incremental_FromAltEnvFile_ReturnsIssuedCertificates` | Read-only probes need `CERTINEXT_ALT_ENV_FILE` (the sync test also `CERTINEXT_ALT_ENV_SYNC_ORDER_IDS`); the order tests are **opt-in** (`CERTINEXT_ALT_ENV_ENROLL`). DV enrollment (single name, UCC, wildcard) against the account in a separate env file, through the plugin and through a direct API call (which can also place OV/EV), and an incremental sync check; orders are left issued | | `V2FreshDomainDcvLifecycleTests` | `EnrollWithDcvOn_V2_FreshUnverifiedSubdomain_StagesAndCleansUpTxt`, `EnrollWithDcvOn_V2_WildcardFreshSubdomain_RecordsTxtHostnameAndCleansUp` | **Opt-in** (`CERTINEXT_V2_LIFECYCLE_FRESH_DCV`). DCV against a never-validated subdomain, and against a wildcard on one: the TXT record is staged at the expected hostname and removed afterward | | `V2FullLifecycleTests` | `Enroll_V2_DvUcc_WithMultipleSans_FullLifecycle`, `Enroll_V2_Ov_FullLifecycle`, `Enroll_V2_OvUcc_WithMultipleSans_FullLifecycle`, `Enroll_V2_Ev_FullLifecycle`, `Enroll_V2_WildcardDv_WildcardOnly_FullLifecycle`, `Enroll_V2_WildcardDv_WildcardPlusApexSan_RecordsActualBehavior`, `EnrollRenewReissue_V2_IssuedDvOrder_RecordsActualBehavior` | **Opt-in** (one `CERTINEXT_V2_LIFECYCLE_*` flag per product, see [INTEGRATION_TESTING.md](INTEGRATION_TESTING.md#opt-in-flags)). Each enrolls, waits, synchronizes, and cleans up its order | | `PrivatePkiV2LiveTests` | `PrivatePki_V2_EnrollIntranetSsl_ThenRevoke_Live` | **Opt-in** (`CERTINEXT_PRIVATE_PKI_LIVE`). Enrolls a Private PKI Intranet SSL order with DNS and IP SANs, checks the issued SANs, and revokes it. Needs a Private PKI entitlement. Always two-call (create, then `PUT .../csr`): the sandbox rejects an inline CSR on Private PKI create with HTTP 422. The order parks at `pending-approval` and is cancelled, so the test reports it as inconclusive on this sandbox | diff --git a/CERTInext.IntegrationTests/V2AltEnvEnrollTests.cs b/CERTInext.IntegrationTests/V2AltEnvEnrollTests.cs new file mode 100644 index 0000000..465d2c7 --- /dev/null +++ b/CERTInext.IntegrationTests/V2AltEnvEnrollTests.cs @@ -0,0 +1,457 @@ +// Copyright 2026 Keyfactor +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// V2 SSL enrollment against an account described by an arbitrary env file, rather than +// ~/.env_certinext[_v2]. Covers the plugin path and the equivalent direct API call, plus +// read-only probes of the account's catalog and group membership. Orders placed here are +// deliberately NOT revoked or cancelled afterwards. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using Keyfactor.AnyGateway.Extensions; +using Keyfactor.Extensions.CAPlugin.CERTInext.Client; +using Keyfactor.PKI.Enums; +using Keyfactor.PKI.Enums.EJBCA; +using Org.BouncyCastle.Asn1; +using Org.BouncyCastle.Asn1.Pkcs; +using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Pkcs; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.X509; +using RestSharp; +using Xunit; +using Xunit.Abstractions; + +namespace Keyfactor.Extensions.CAPlugin.CERTInext.IntegrationTests +{ + /// + /// Env vars (read from the real environment; account values come from the file only and are + /// never promoted into process env, so other classes' sandbox fixtures are unaffected): + /// + /// CERTINEXT_ALT_ENV_FILE — path to a KEY=VALUE file with the V2 keys + /// (CERTINEXT_API_URL, CERTINEXT_CLIENT_ID, CERTINEXT_CLIENT_SECRET, + /// optional CERTINEXT_GROUP_NUMBER / CERTINEXT_ORG_NUMBER / requestor keys). + /// Enough on its own for the read-only tests. + /// CERTINEXT_ALT_ENV_ENROLL=1 — arms the order-placing tests. + /// CERTINEXT_ALT_ENV_DOMAIN — the name to order. + /// CERTINEXT_ALT_ENV_WILDCARD=1 — order *.<domain> (plus the bare + /// domain as a SAN on the plugin path) instead of the single name. + /// CERTINEXT_ALT_ENV_GROUP_NUMBER overrides the file's group; + /// CERTINEXT_ALT_ENV_OMIT_GROUP=1 sends none (the credential's default group). + /// CERTINEXT_ALT_ENV_EXTRA_SANS — comma-separated extra DNS names (UCC order). + /// CERTINEXT_ALT_ENV_VARIANT=ov|ev and CERTINEXT_ALT_ENV_ORG_NUMBER — direct API test only: + /// an OV/EV order with an organization block (org falls back to the file's CERTINEXT_ORG_NUMBER). + /// CERTINEXT_ALT_ENV_PRODUCT_CODE — optional ProductCode override. + /// CERTINEXT_ALT_ENV_ORDER_ID — plugin test only: re-read an existing order + /// instead of placing a new one. + /// + /// + public class V2AltEnvEnrollTests + { + private static readonly TimeSpan IssuanceTimeout = TimeSpan.FromMinutes(10); + private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(15); + + private readonly ITestOutputHelper _output; + + public V2AltEnvEnrollTests(ITestOutputHelper output) + { + _output = output; + } + + // --------------------------------------------------------------------------- + // Helpers + // --------------------------------------------------------------------------- + + private static string Opt(string name) => Environment.GetEnvironmentVariable(name); + + private static string Get(Dictionary env, string key, string fallback = "") => + env.TryGetValue(key, out string v) && !string.IsNullOrWhiteSpace(v) ? v : fallback; + + private static Dictionary LoadAltEnv() + { + string envFile = Opt("CERTINEXT_ALT_ENV_FILE"); + Skip.If(string.IsNullOrWhiteSpace(envFile) || !System.IO.File.Exists(envFile), + "CERTINEXT_ALT_ENV_FILE not set or not found. Skipping."); + var (env, _) = V2EnvHelper.LoadEnvFile(envFile); + return env; + } + + private static string RequireOrderDomain() + { + Skip.If(Opt("CERTINEXT_ALT_ENV_ENROLL") != "1", + "CERTINEXT_ALT_ENV_ENROLL=1 not set — this places a real order on the account in CERTINEXT_ALT_ENV_FILE. Skipping."); + string domain = Opt("CERTINEXT_ALT_ENV_DOMAIN"); + Skip.If(string.IsNullOrWhiteSpace(domain), "CERTINEXT_ALT_ENV_DOMAIN not set. Skipping."); + return domain; + } + + /// Group to send: the override, else the file's value; null when omitted. + private static string ResolveGroup(Dictionary env) + { + if (Opt("CERTINEXT_ALT_ENV_OMIT_GROUP") == "1") + return null; + string group = Opt("CERTINEXT_ALT_ENV_GROUP_NUMBER") is { Length: > 0 } g ? g : Get(env, "CERTINEXT_GROUP_NUMBER"); + return string.IsNullOrWhiteSpace(group) ? null : group; + } + + private static bool WantWildcard => Opt("CERTINEXT_ALT_ENV_WILDCARD") == "1"; + + /// CERTINEXT_ALT_ENV_EXTRA_SANS (comma-separated): extra DNS names, which make the order UCC. + private static string[] ExtraSans => + (Opt("CERTINEXT_ALT_ENV_EXTRA_SANS") ?? string.Empty) + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + /// Plugin config for the alt env account (V2, DCV off). + private static CERTInextConfig BuildPluginConfig(Dictionary env, int syncLookbackHours = 1) + { + return new CERTInextConfig + { + ApiUrl = Get(env, "CERTINEXT_API_URL"), + UseV2Api = true, + OAuthClientId = Get(env, "CERTINEXT_CLIENT_ID"), + OAuthClientSecret = Get(env, "CERTINEXT_CLIENT_SECRET"), + AccountNumber = Get(env, "CERTINEXT_ACCOUNT_NUMBER"), + GroupNumber = ResolveGroup(env) ?? string.Empty, + OrganizationNumber = Get(env, "CERTINEXT_ORG_NUMBER"), + + RequestorName = Get(env, "CERTINEXT_REQUESTOR_NAME", "Keyfactor Test"), + RequestorEmail = Get(env, "CERTINEXT_REQUESTOR_EMAIL"), + RequestorIsdCode = Get(env, "CERTINEXT_REQUESTOR_ISD_CODE", "1"), + RequestorMobileNumber = Get(env, "CERTINEXT_REQUESTOR_MOBILE", "0000000000"), + SignerPlace = "Gateway Lab", + SignerIp = "127.0.0.1", + + PageSize = 100, + V2SyncLookbackHours = syncLookbackHours, + DcvEnabled = false + }; + } + + private static async Task> RunSyncAsync( + CERTInextCAPlugin plugin, DateTime? lastSync, bool fullSync) + { + var buffer = new BlockingCollection(boundedCapacity: 10_000); + var collected = new List(); + + var syncTask = Task.Run(async () => + { + await plugin.Synchronize(buffer, lastSync: lastSync, fullSync: fullSync, cancelToken: CancellationToken.None); + if (!buffer.IsAddingCompleted) + buffer.CompleteAdding(); + }); + + foreach (var record in buffer.GetConsumingEnumerable()) + collected.Add(record); + + await syncTask; + return collected; + } + + /// + /// Parses the leaf from a certificate payload. It may arrive as one PEM block, a PEM chain, + /// or bare base64 DER; the BouncyCastle parser reads PEM itself and returns the first + /// (leaf) certificate. + /// + private static X509Certificate ParseLeaf(string certPem, out int pemBlocks) + { + pemBlocks = Regex.Matches(certPem, "-----BEGIN CERTIFICATE-----").Count; + byte[] certBytes = pemBlocks > 0 + ? System.Text.Encoding.ASCII.GetBytes(certPem) + : Convert.FromBase64String(string.Concat(certPem.Where(c => !char.IsWhiteSpace(c)))); + return new X509CertificateParser().ReadCertificate(certBytes); + } + + private static string DescribeLeaf(X509Certificate cert) + { + var sans = cert.GetSubjectAlternativeNames()?.Cast>().Select(s => s[1]?.ToString()) + ?? Enumerable.Empty(); + return $"Subject={cert.SubjectDN}, Issuer={cert.IssuerDN}, Serial={cert.SerialNumber.ToString(16)}, " + + $"NotAfter={cert.NotAfter:yyyy-MM-dd}, SANs=[{string.Join(", ", sans)}]"; + } + + private static string ScrubEmails(string s) => + s == null ? null : Regex.Replace(s, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+", ""); + + /// RSA-2048 CSR with CN= and every name in as a DNS SAN. + private static string GenerateCsrPem(string commonName, IEnumerable dnsSans) + { + var keyGen = new RsaKeyPairGenerator(); + keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); + var keyPair = keyGen.GenerateKeyPair(); + + var names = new GeneralNames(dnsSans.Select(d => new GeneralName(GeneralName.DnsName, d)).ToArray()); + var extGen = new X509ExtensionsGenerator(); + extGen.AddExtension(X509Extensions.SubjectAlternativeName, false, names); + var attrs = new DerSet(new AttributePkcs( + PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(extGen.Generate()))); + + var csr = new Pkcs10CertificationRequest( + "SHA256withRSA", new X509Name($"CN={commonName}"), keyPair.Public, attrs, keyPair.Private); + + return "-----BEGIN CERTIFICATE REQUEST-----\n" + + Convert.ToBase64String(csr.GetEncoded(), Base64FormattingOptions.InsertLineBreaks) + + "\n-----END CERTIFICATE REQUEST-----"; + } + + private async Task RawGetAsync(string apiUrl, string token, string path) + { + using var api = V2RawHttpHelpers.NewApiClient(apiUrl.TrimEnd('/')); + var req = new RestRequest(path, Method.Get); + req.AddHeader("Authorization", $"Bearer {token}"); + var resp = await api.ExecuteAsync(req); + _output.WriteLine($"GET {path} -> {(int)resp.StatusCode}\n{ScrubEmails(resp.Content)}"); + return resp.Content; + } + + // --------------------------------------------------------------------------- + // Read-only probes + // --------------------------------------------------------------------------- + + /// Logs the account's V2 product catalog. + [SkippableFact] + public async Task ListCatalog_FromAltEnvFile() + { + var env = LoadAltEnv(); + var config = new CERTInextConfig + { + ApiUrl = Get(env, "CERTINEXT_API_URL"), + UseV2Api = true, + OAuthClientId = Get(env, "CERTINEXT_CLIENT_ID"), + OAuthClientSecret = Get(env, "CERTINEXT_CLIENT_SECRET"), + }; + + using var client = new CERTInextClient(config); + var catalog = await client.GetProductDetailsV2Async(); + foreach (var p in catalog) + _output.WriteLine($"productCode={p.ProductCode} productTypeID={p.ProductTypeId} name='{p.ProductName}'"); + catalog.Should().NotBeNull(); + } + + /// Logs /auth/me and /groups: which groups the credential belongs to. + [SkippableFact] + public async Task Raw_ListIdentityAndGroups_FromAltEnvFile() + { + var env = LoadAltEnv(); + string apiUrl = Get(env, "CERTINEXT_API_URL"); + string token = await V2RawHttpHelpers.GetV2AccessTokenAsync( + apiUrl, Get(env, "CERTINEXT_CLIENT_ID"), Get(env, "CERTINEXT_CLIENT_SECRET")); + + await RawGetAsync(apiUrl, token, Constants.ApiV2.AuthMePath); + await RawGetAsync(apiUrl, token, "/api/certinext/v2/groups"); + } + + // --------------------------------------------------------------------------- + // Order-placing tests (opt-in; never revoked or cancelled) + // --------------------------------------------------------------------------- + + /// + /// Direct POST /ssl-certificates, bypassing the plugin: CSR inline, and no + /// X-Product-Code unless CERTINEXT_ALT_ENV_PRODUCT_CODE is set. DV by default; + /// CERTINEXT_ALT_ENV_VARIANT=ov (or ev) adds an organization block from + /// CERTINEXT_ALT_ENV_ORG_NUMBER, else the file's CERTINEXT_ORG_NUMBER. + /// + [SkippableFact] + public async Task Raw_PlaceSslOrder_FromAltEnvFile() + { + string baseName = RequireOrderDomain(); + var env = LoadAltEnv(); + string apiUrl = Get(env, "CERTINEXT_API_URL"); + string token = await V2RawHttpHelpers.GetV2AccessTokenAsync( + apiUrl, Get(env, "CERTINEXT_CLIENT_ID"), Get(env, "CERTINEXT_CLIENT_SECRET")); + + string group = ResolveGroup(env); + string productCode = Opt("CERTINEXT_ALT_ENV_PRODUCT_CODE"); + string name = Get(env, "CERTINEXT_REQUESTOR_NAME", "Keyfactor Test").Trim('"', '\''); + string email = Get(env, "CERTINEXT_REQUESTOR_EMAIL"); + string phone = "+1" + Get(env, "CERTINEXT_REQUESTOR_MOBILE", "0000000000"); + string domain = WantWildcard ? $"*.{baseName}" : baseName; + string variant = Opt("CERTINEXT_ALT_ENV_VARIANT") is { Length: > 0 } v ? v.ToLowerInvariant() : "dv"; + + var body = new Dictionary + { + ["productVariant"] = variant, + ["emailNotifications"] = "consent-only", + ["requestor"] = new { name, email, phone }, + ["certificate"] = ExtraSans.Length > 0 + ? new { domain, autoSecureWww = false, additionalDomains = ExtraSans } + : (object)new { domain, autoSecureWww = false }, + ["subscription"] = new { validityYears = 1, autoRenew = false, renewBeforeDays = 30 }, + ["agreement"] = new { signerName = name, signerPlace = "Gateway Lab", accepted = true }, + ["technicalPointOfContact"] = new { name, email, phone, designation = "Technical Contact" }, + ["csr"] = GenerateCsrPem(domain, new[] { domain }.Concat(ExtraSans)), + ["remarks"] = "Keyfactor plugin test (direct API).", + }; + if (group != null) + body["groupNumber"] = group; + if (variant != "dv") + { + string org = Opt("CERTINEXT_ALT_ENV_ORG_NUMBER") is { Length: > 0 } o ? o : Get(env, "CERTINEXT_ORG_NUMBER"); + org.Should().NotBeNullOrWhiteSpace("an OV/EV order needs CERTINEXT_ALT_ENV_ORG_NUMBER or CERTINEXT_ORG_NUMBER"); + body["organization"] = new { organizationNumber = org, preVetted = true }; + } + + using var api = V2RawHttpHelpers.NewApiClient(apiUrl.TrimEnd('/'), TimeSpan.FromSeconds(120)); + var req = new RestRequest(Constants.ApiV2.SslCertificatesPath, Method.Post); + req.AddHeader("Authorization", $"Bearer {token}"); + req.AddHeader("Idempotency-Key", Guid.NewGuid().ToString()); + if (!string.IsNullOrWhiteSpace(productCode)) + req.AddHeader("X-Product-Code", productCode); + req.AddJsonBody(body); + var resp = await api.ExecuteAsync(req); + + string corr = resp.Headers?.FirstOrDefault(h => string.Equals(h.Name, "x-correlation-id", StringComparison.OrdinalIgnoreCase))?.Value?.ToString(); + _output.WriteLine($"POST {Constants.ApiV2.SslCertificatesPath} variant={variant} domain={domain} " + + $"additionalDomains=[{string.Join(", ", ExtraSans)}] group={group ?? "(omitted)"} " + + $"productCode={(string.IsNullOrWhiteSpace(productCode) ? "(none)" : productCode)} " + + $"-> {(int)resp.StatusCode} x-correlation-id={corr}\n{ScrubEmails(resp.Content)}"); + resp.IsSuccessful.Should().BeTrue($"the order should be accepted; response: {ScrubEmails(resp.Content)}"); + } + + /// + /// Plugin Enroll (DV SSL, or DV SSL Wildcard with the bare domain as a SAN), then + /// GetSingleRecord until issued; logs the issued leaf's subject, issuer, serial, + /// expiry, and SANs. + /// + [SkippableFact] + public async Task Enroll_V2_Dv_FromAltEnvFile_Issues() + { + string baseName = RequireOrderDomain(); + var env = LoadAltEnv(); + + var config = BuildPluginConfig(env); + + config.OAuthClientId.Should().NotBeNullOrWhiteSpace("the alt env file must define CERTINEXT_CLIENT_ID"); + _output.WriteLine($"API host: {new Uri(config.ApiUrl).Host}, group configured: {!string.IsNullOrWhiteSpace(config.GroupNumber)}"); + + using var client = new CERTInextClient(config); + var plugin = new CERTInextCAPlugin(client, config); + + var parameters = new Dictionary + { + [Constants.EnrollmentParam.ProductVariant] = Constants.ApiV2.ProductVariantDv, + }; + string productCode = Opt("CERTINEXT_ALT_ENV_PRODUCT_CODE"); + if (!string.IsNullOrWhiteSpace(productCode)) + parameters[Constants.EnrollmentParam.ProductCode] = productCode; + + string commonName = WantWildcard ? $"*.{baseName}" : baseName; + string[] dnsSans = (WantWildcard ? new[] { commonName, baseName } : new[] { commonName }) + .Concat(ExtraSans).ToArray(); + bool ucc = ExtraSans.Length > 0; + _output.WriteLine($"ProductCode: {(string.IsNullOrWhiteSpace(productCode) ? "(none)" : productCode)}, " + + $"SANs requested: {string.Join(", ", dnsSans)}"); + + string existingOrderId = Opt("CERTINEXT_ALT_ENV_ORDER_ID"); + var enrollResult = !string.IsNullOrWhiteSpace(existingOrderId) + ? new EnrollmentResult { CARequestID = existingOrderId, Status = (int)EndEntityStatus.EXTERNALVALIDATION } + : await plugin.Enroll( + csr: GenerateCsrPem(commonName, dnsSans), + subject: $"CN={commonName}", + san: new Dictionary { ["dns"] = dnsSans }, + productInfo: new EnrollmentProductInfo + { + ProductID = (WantWildcard, ucc) switch + { + (true, true) => Constants.Products.DvSslWildcardUcc, + (true, false) => Constants.Products.DvSslWildcard, + (false, true) => Constants.Products.DvSslUcc, + (false, false) => Constants.Products.DvSsl, + }, + ProductParameters = parameters + }, + requestFormat: RequestFormat.PKCS10, + enrollmentType: EnrollmentType.New); + + _output.WriteLine($"Enroll: Status={enrollResult.Status}, CARequestID={enrollResult.CARequestID}, Message={enrollResult.StatusMessage}"); + enrollResult.Status.Should().NotBe((int)EndEntityStatus.FAILED, enrollResult.StatusMessage); + enrollResult.CARequestID.Should().NotBeNullOrWhiteSpace(); + + string certPem = enrollResult.Status == (int)EndEntityStatus.GENERATED ? enrollResult.Certificate : null; + var deadline = DateTime.UtcNow + IssuanceTimeout; + while (string.IsNullOrWhiteSpace(certPem) && DateTime.UtcNow < deadline) + { + await Task.Delay(PollInterval); + var record = await plugin.GetSingleRecord(enrollResult.CARequestID); + _output.WriteLine($"{DateTime.UtcNow:O} poll: Status={record?.Status}"); + record.Should().NotBeNull(); + record!.Status.Should().NotBe((int)EndEntityStatus.FAILED, "the order must not be rejected while waiting"); + if (record.Status == (int)EndEntityStatus.GENERATED) + certPem = record.Certificate; + } + + certPem.Should().NotBeNullOrWhiteSpace( + $"order {enrollResult.CARequestID} should issue within {IssuanceTimeout.TotalMinutes} minutes"); + + var cert = ParseLeaf(certPem!, out int pemBlocks); + _output.WriteLine($"Certificate payload: {certPem!.Length} chars, {pemBlocks} PEM block(s)"); + _output.WriteLine($"Issued. OrderId={enrollResult.CARequestID}: {DescribeLeaf(cert)}"); + } + + /// + /// Incremental (fullSync: false) sync, read-only: every order in + /// CERTINEXT_ALT_ENV_SYNC_ORDER_IDS (comma-separated) must come back GENERATED with a + /// parseable certificate. lastSync is CERTINEXT_ALT_ENV_SYNC_LAST_HOURS (default 1) + /// hours ago, with the same V2 lookback. + /// + [SkippableFact] + public async Task Sync_V2_Incremental_FromAltEnvFile_ReturnsIssuedCertificates() + { + var env = LoadAltEnv(); + string idList = Opt("CERTINEXT_ALT_ENV_SYNC_ORDER_IDS"); + Skip.If(string.IsNullOrWhiteSpace(idList), "CERTINEXT_ALT_ENV_SYNC_ORDER_IDS not set. Skipping."); + var expectedIds = idList.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + int hours = int.TryParse(Opt("CERTINEXT_ALT_ENV_SYNC_LAST_HOURS"), out int h) && h > 0 ? h : 1; + var config = BuildPluginConfig(env, syncLookbackHours: hours); + + // Route plugin logs to the test output (before the plugin is constructed) so held-back + // and skipped orders are visible in the sync summary. + var restoreLogging = TestOutputLogging.RouteTo(_output); + List records; + DateTime lastSync = DateTime.UtcNow.AddHours(-hours); + try + { + using var client = new CERTInextClient(config); + var plugin = new CERTInextCAPlugin(client, config); + records = await RunSyncAsync(plugin, lastSync, fullSync: false); + } + finally + { + restoreLogging(); + } + _output.WriteLine($"Incremental sync (lastSync={lastSync:O}, lookback={hours}h) returned {records.Count} record(s)."); + foreach (var r in records) + _output.WriteLine($" CARequestID={r.CARequestID}, Status={r.Status}, CertBytes={r.Certificate?.Length ?? 0}, ProductID={r.ProductID}"); + + foreach (string id in expectedIds) + { + var record = records.FirstOrDefault(r => r.CARequestID == id); + record.Should().NotBeNull($"order {id} should be returned by the incremental sync"); + record!.Status.Should().Be((int)EndEntityStatus.GENERATED, $"order {id} is issued"); + record.Certificate.Should().NotBeNullOrWhiteSpace($"order {id} should carry its certificate"); + + var cert = ParseLeaf(record.Certificate, out int pemBlocks); + _output.WriteLine($"Order {id}: {pemBlocks} PEM block(s); {DescribeLeaf(cert)}"); + } + } + } +}