Files
certctl/internal/connector/issuer/digicert/digicert_failure_test.go
T
shankar0123 711265b652 asyncpoll: shared bounded-polling Poller + DigiCert refactor (Phase 1)
Phase 1 of the #5 acquisition-readiness fix from the 2026-05-01 issuer
coverage audit. Pre-fix, four async-CA connectors (DigiCert, Sectigo,
Entrust, GlobalSign) had GetOrderStatus paths that polled the upstream
on every scheduler tick with no exponential backoff, no max-retry cap,
and no deadline. The scheduler's tick rate (typically 30s) was the
only throttle — an unready order got hit every 30s indefinitely, and
a 429 from a rate-limited upstream produced "retry on the next tick"
which re-fanned-out the same call.

This commit ships the shared infrastructure (asyncpoll package) and
refactors DigiCert as the reference. Sectigo / Entrust / GlobalSign
follow the same mechanical pattern; they land in Phase 2.

Phase 1 (this commit):
- internal/connector/issuer/asyncpoll/asyncpoll.go: shared Poller
  with exponential backoff (5s → 15s → 45s → 2m → 5m capped),
  ±20% jitter, configurable MaxWait deadline (default 10m), and
  ctx-aware cancellation.
- Result enum: StillPending / Done / Failed. PollFunc returns
  (Result, err); Poll handles the wait loop, deadline check, and
  ctx propagation.
- ErrMaxWait sentinel for callers that want to distinguish
  "deadline exhausted" from "fn errored".
- asyncpoll_test.go: 11 tests covering happy path, transient error
  keep-polling, Failed terminates immediately, MaxWait timeout,
  MaxWait+lastErr wrap, ctx cancel, multiplicative backoff, jitter
  bounds (statistical), pct=0 deterministic, defaults applied.
- DigiCert refactor: GetOrderStatus now wraps pollOrderOnce in
  asyncpoll.Poll. Status-code triage:
    2xx + parse + status="issued"           → Done with cert
    2xx + parse + status="pending"          → StillPending
    2xx + parse + status="rejected"/"denied" → Done with status="failed"
    2xx + parse fail                        → Failed (permanent)
    4xx (not 429)                           → Failed (404 = order
                                              doesn't exist)
    429 / 5xx / network                     → StillPending
- Config.PollMaxWaitSeconds (env: CERTCTL_DIGICERT_POLL_MAX_WAIT_SECONDS)
  exposes the per-call deadline knob; default 600 (10m).
- Test helper buildDigicertConnector + GetOrderStatus_Pending test
  set PollMaxWaitSeconds=1 so async-pending tests don't block 10
  minutes on the production default.

Phase 2 (separate follow-up commit, not in this PR):
- Sectigo refactor (collectNotReady sentinel maps to StillPending).
- Entrust refactor (approval-pending → longer per-issuer MaxWait).
- GlobalSign refactor (serial-tracking; same Poller).
- Per-connector cadence integration tests against fake HTTP servers.
- docs/async-polling.md + docs/connectors.md updates.

Audit reference: cowork/issuer-coverage-audit-2026-05-01/RESULTS.md
Top-10 fix #5 — Phase 1.
2026-05-02 02:18:50 +00:00

173 lines
5.6 KiB
Go

package digicert_test
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/shankar0123/certctl/internal/connector/issuer/digicert"
)
// Bundle N.A/B-extended: digicert failure-mode round-out (81.0% → ≥85%).
// Targets GetOrderStatus / downloadCertificate / parsePEMBundle uncovered
// branches.
func buildDigicertConnector(t *testing.T, baseURL string) *digicert.Connector {
t.Helper()
c := digicert.New(nil, slog.Default())
// PollMaxWaitSeconds=1 keeps async-pending tests fast — pending
// status returns within ~1s instead of the 10-minute production
// default. Tests that exercise issued/failed/parse-error paths
// don't block on the wait.
cfg := digicert.Config{APIKey: "k", OrgID: "1", ProductType: "ssl_basic", BaseURL: baseURL, PollMaxWaitSeconds: 1}
raw, _ := json.Marshal(cfg)
if err := c.ValidateConfig(context.Background(), raw); err != nil {
t.Fatalf("ValidateConfig: %v", err)
}
return c
}
func TestDigicert_GetOrderStatus_404_ReturnsError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/user/me":
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":1}`))
default:
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"errors":[{"code":"order_not_found"}]}`))
}
}))
defer srv.Close()
c := buildDigicertConnector(t, srv.URL)
_, err := c.GetOrderStatus(context.Background(), "missing-order")
if err == nil || !strings.Contains(err.Error(), "404") {
t.Errorf("expected 404 error, got %v", err)
}
}
func TestDigicert_GetOrderStatus_MalformedJSON_ReturnsError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/user/me":
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":1}`))
default:
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{not valid json`))
}
}))
defer srv.Close()
c := buildDigicertConnector(t, srv.URL)
_, err := c.GetOrderStatus(context.Background(), "bad-order")
if err == nil || !strings.Contains(err.Error(), "parse") {
t.Errorf("expected parse error, got %v", err)
}
}
func TestDigicert_GetOrderStatus_IssuedButCertIDMissing(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/user/me":
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":1}`))
default:
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"issued","certificate":{"id":0}}`))
}
}))
defer srv.Close()
c := buildDigicertConnector(t, srv.URL)
_, err := c.GetOrderStatus(context.Background(), "issued-no-cert-id")
if err == nil || !strings.Contains(err.Error(), "certificate_id is missing") {
t.Errorf("expected 'certificate_id is missing' error, got %v", err)
}
}
func TestDigicert_GetOrderStatus_PendingProcessingDeniedUnknown(t *testing.T) {
cases := []struct {
name string
status string
wantStatus string
}{
{"pending", "pending", "pending"},
{"processing", "processing", "pending"},
{"rejected", "rejected", "failed"},
{"denied", "denied", "failed"},
{"unknown", "frobnicating", "pending"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/user/me":
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":1}`))
default:
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"` + tc.status + `"}`))
}
}))
defer srv.Close()
c := buildDigicertConnector(t, srv.URL)
st, err := c.GetOrderStatus(context.Background(), "order-x")
if err != nil {
t.Fatalf("GetOrderStatus: %v", err)
}
if st.Status != tc.wantStatus {
t.Errorf("expected status=%q for input=%q, got %q", tc.wantStatus, tc.status, st.Status)
}
})
}
}
func TestDigicert_DownloadCertificate_Non200_ReturnsError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/user/me":
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":1}`))
case strings.Contains(r.URL.Path, "/certificate/"):
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"errors":[{"code":"forbidden"}]}`))
default:
// /order/certificate/<id> returns issued with cert_id 7
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"issued","certificate":{"id":7}}`))
}
}))
defer srv.Close()
c := buildDigicertConnector(t, srv.URL)
_, err := c.GetOrderStatus(context.Background(), "order-y")
if err == nil || !strings.Contains(err.Error(), "403") {
t.Errorf("expected 403 download error, got %v", err)
}
}
func TestDigicert_DownloadCertificate_MalformedPEM_ReturnsError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/user/me":
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"id":1}`))
case strings.Contains(r.URL.Path, "/certificate/") && strings.Contains(r.URL.Path, "/download/"):
// Returns junk that won't decode as PEM
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("not a pem bundle"))
default:
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"issued","certificate":{"id":42}}`))
}
}))
defer srv.Close()
c := buildDigicertConnector(t, srv.URL)
_, err := c.GetOrderStatus(context.Background(), "order-z")
if err == nil {
t.Errorf("expected error from malformed PEM bundle, got nil")
}
}