mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-12 20:28:59 +00:00
2a384c690e
Phase 2 of the #6 acquisition-readiness fix from the 2026-05-01 issuer
coverage audit. Phase 1 (commit 633a10a) shipped the secret.Ref opaque
credential type with PBKDF2-derived key, ChaCha20-Poly1305 envelope,
String/MarshalJSON redaction to "[redacted]", and the Use callback
that zero-fills the per-call buffer after the consumer returns.
This commit applies the type to the three connectors flagged by the
audit and adds the JSON-roundtrip glue that the production factory
path needs.
Shared (internal/secret/):
- Add UnmarshalJSON on *Ref so json.Unmarshal of a stored config
blob (issuerfactory.NewFromConfig) parses the bytes-as-string into
NewRefFromString without callers having to know the field type
changed. Null and missing keys leave the receiver nil; non-string
payloads (numbers, bools) are rejected with a typed error. Pinned
by TestRef_UnmarshalJSON: string_value, null, missing_key,
number_rejected, roundtrip_marshal_then_unmarshal (the round-trip
goes through "[redacted]" intentionally — JSON-marshal-then-
unmarshal of a Config with secrets is NOT a supported test pattern;
callers that construct a rawConfig must use a JSON literal with
the real values).
Per-connector migration:
- EJBCA (ejbca.go): Config.Token: string → *secret.Ref. ValidateConfig
empty-check uses Token.IsEmpty() (nil-safe). setAuthHeaders rewritten
to call Token.Use; the Bearer header string is built inside the
callback and the buffer is zeroed on return. mTLS path is
unaffected.
- GlobalSign (globalsign.go): Config.APIKey + Config.APISecret: string
→ *secret.Ref. Both ValidateConfig empty-checks use IsEmpty().
Extracted setAuthHeaders helper consolidates the four duplicated
triple-Set sites (ValidateConfig probe, IssueCertificate,
RevokeCertificate, pollCertificateOnce) so any future header-shape
change applies once. ValidateConfig now pulls from the local cfg
(post-Unmarshal) so the helper takes a *Config rather than the
receiver — needed because ValidateConfig writes the validated cfg
onto c.config only AFTER the probe succeeds.
- Sectigo (sectigo.go): Config.Login + Config.Password: string →
*secret.Ref. CustomerURI stays plain string (org identifier, not
a credential). setAuthHeaders rewritten to call Login.Use +
Password.Use; ValidateConfig's inline header writes use the same
pattern (the ValidateConfig probe writes to a local cfg, not
c.config, so it can't share setAuthHeaders without rewiring — the
inline form is fine, kept consistent in shape).
Test migration:
- ejbca_test.go, ejbca_failure_test.go, ejbca_stubs_test.go: bulk
Token: "X" → Token: secret.NewRefFromString("X") via sed; secret
import added.
- globalsign_test.go, globalsign_failure_test.go: same pattern for
APIKey + APISecret.
- sectigo_test.go, sectigo_failure_test.go: same pattern for Login +
Password.
Two tests (TestGlobalSign_ServerTLSConfig/PinnedCA_TrustsExpectedServer
and TestSectigoConnector/ValidateConfig_Success) used to construct
rawConfig via json.Marshal(config) → ValidateConfig(rawConfig). After
the migration, json.Marshal redacts *secret.Ref to "[redacted]" by
design, so the roundtripped rawConfig wrote "[redacted]" as the
actual header value and the mock server's auth-header check 403'd.
Both tests now build rawConfig as a JSON literal (the production-
shape input — the factory path always feeds rawConfig from the DB
or env, never from json.Marshal of an in-memory Config). The new
tests have a comment explaining the trap so the next person who
adds a similar test sees the pattern.
Out of scope (intentional):
- The `internal/config/config.SectigoConfig` / `GlobalSignConfig` /
`EJBCAConfig` env-var-loader structs are still plain strings —
those types are the env-load shape, not the steady-state runtime
shape. The seed path in service/issuer.go json-marshals them into
a map[string]interface{} which the factory then UnmarshalJSON's
into the connector Config; the new UnmarshalJSON on *Ref handles
the conversion at the boundary.
- DigiCert.APIKey + Vault.Token are still plain strings; Phase 3
will pick them up. The audit explicitly named EJBCA / GlobalSign /
Sectigo as the Phase 2 scope (RESULTS.md L633).
Verified locally:
- gofmt -l . clean
- go vet ./... clean
- staticcheck across all four packages clean
- go test -short -count=1 across secret, ejbca, globalsign, sectigo,
issuerfactory, service, api/handler: green
Audit reference: cowork/issuer-coverage-audit-2026-05-01/RESULTS.md
Top-10 fix #6 — Phase 2.
168 lines
6.2 KiB
Go
168 lines
6.2 KiB
Go
package globalsign_test
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/shankar0123/certctl/internal/connector/issuer/globalsign"
|
|
"github.com/shankar0123/certctl/internal/secret"
|
|
)
|
|
|
|
// Bundle N.A/B-extended: globalsign failure-mode round-out (78.2% → ≥85%).
|
|
// Targets uncovered branches in getHTTPClient / GetOrderStatus / parseCertDates.
|
|
|
|
func buildGlobalsignConnector(t *testing.T, baseURL string) *globalsign.Connector {
|
|
t.Helper()
|
|
cfg := &globalsign.Config{
|
|
APIUrl: baseURL,
|
|
APIKey: secret.NewRefFromString("k"),
|
|
APISecret: secret.NewRefFromString("s"),
|
|
PollMaxWaitSeconds: 1, // keep async-pending tests fast
|
|
}
|
|
// Use NewWithHTTPClient with a test client so getHTTPClient short-circuits
|
|
// (no mTLS cert loading). Custom transport is required so the
|
|
// `httpClient.Transport != nil` test-mode check fires.
|
|
httpClient := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} //nolint:gosec
|
|
return globalsign.NewWithHTTPClient(cfg, slog.Default(), httpClient)
|
|
}
|
|
|
|
func TestGlobalsign_GetOrderStatus_403_ReturnsError(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusForbidden)
|
|
_, _ = w.Write([]byte(`{"error":"unauthorized"}`))
|
|
}))
|
|
defer srv.Close()
|
|
c := buildGlobalsignConnector(t, srv.URL)
|
|
_, err := c.GetOrderStatus(context.Background(), "serial-123")
|
|
if err == nil || !strings.Contains(err.Error(), "403") {
|
|
t.Errorf("expected 403 error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestGlobalsign_GetOrderStatus_MalformedJSON(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{not json`))
|
|
}))
|
|
defer srv.Close()
|
|
c := buildGlobalsignConnector(t, srv.URL)
|
|
_, err := c.GetOrderStatus(context.Background(), "serial-123")
|
|
if err == nil || !strings.Contains(err.Error(), "parse") {
|
|
t.Errorf("expected parse error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestGlobalsign_GetOrderStatus_StatusVariants(t *testing.T) {
|
|
cases := []struct {
|
|
statusVal string
|
|
want string
|
|
}{
|
|
{"pending", "pending"},
|
|
{"processing", "pending"},
|
|
{"rejected", "failed"},
|
|
{"denied", "failed"},
|
|
{"failed", "failed"},
|
|
{"weird-new-status", "pending"}, // unknown → default pending
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.statusVal, func(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"status": tc.statusVal,
|
|
"serial_number": "serial-123",
|
|
})
|
|
}))
|
|
defer srv.Close()
|
|
c := buildGlobalsignConnector(t, srv.URL)
|
|
st, err := c.GetOrderStatus(context.Background(), "serial-123")
|
|
if err != nil {
|
|
t.Fatalf("GetOrderStatus: %v", err)
|
|
}
|
|
if st.Status != tc.want {
|
|
t.Errorf("expected status=%q for input=%q, got %q", tc.want, tc.statusVal, st.Status)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGlobalsign_GetOrderStatus_IssuedButCertMissing(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{"status":"issued","certificate":""}`))
|
|
}))
|
|
defer srv.Close()
|
|
c := buildGlobalsignConnector(t, srv.URL)
|
|
_, err := c.GetOrderStatus(context.Background(), "serial-123")
|
|
if err == nil || !strings.Contains(err.Error(), "certificate PEM is missing") {
|
|
t.Errorf("expected 'certificate PEM is missing' error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestGlobalsign_GetOrderStatus_IssuedWithMalformedPEM_NonFatalParseDateWarning(t *testing.T) {
|
|
// When status=issued and certificate is non-empty but doesn't parse as PEM,
|
|
// the connector logs a warning but still returns Status=completed (per the
|
|
// existing code: parseCertDates failure is non-fatal).
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{"status":"issued","certificate":"not-a-pem-block","serial_number":"sn1"}`))
|
|
}))
|
|
defer srv.Close()
|
|
c := buildGlobalsignConnector(t, srv.URL)
|
|
st, err := c.GetOrderStatus(context.Background(), "serial-123")
|
|
if err != nil {
|
|
t.Fatalf("GetOrderStatus: %v", err)
|
|
}
|
|
if st.Status != "completed" {
|
|
t.Errorf("expected completed (parseCertDates failure is non-fatal), got %q", st.Status)
|
|
}
|
|
}
|
|
|
|
func TestGlobalsign_GetHTTPClient_NoMTLSCertPaths_ReturnsClientAsIs(t *testing.T) {
|
|
// When ClientCertPath and ClientKeyPath are both empty, getHTTPClient
|
|
// returns httpClient as-is — exercises that branch.
|
|
//
|
|
// PollMaxWaitSeconds=1 keeps this test fast: a network failure on
|
|
// the invalid host is now treated as transient by the bounded-
|
|
// polling Poller, so without the deadline the call blocks for
|
|
// the production-default 10 minutes.
|
|
cfg := &globalsign.Config{
|
|
APIUrl: "http://example.invalid",
|
|
APIKey: secret.NewRefFromString("k"),
|
|
APISecret: secret.NewRefFromString("s"),
|
|
PollMaxWaitSeconds: 1,
|
|
// no cert paths
|
|
}
|
|
c := globalsign.NewWithHTTPClient(cfg, slog.Default(), &http.Client{})
|
|
// GetOrderStatus blocks briefly (1s) due to bounded polling, then
|
|
// returns a pending OrderStatus (transient network err did not
|
|
// become a permanent failure). The test exercises the
|
|
// no-mTLS branch in getHTTPClient — the post-poll status doesn't
|
|
// matter; we just need GetOrderStatus to be invoked through the
|
|
// branch.
|
|
_, _ = c.GetOrderStatus(context.Background(), "x")
|
|
}
|
|
|
|
func TestGlobalsign_GetHTTPClient_MTLSPathConfigured_LoadsKeyPair(t *testing.T) {
|
|
// Configure cert paths to a non-existent file — exercises the
|
|
// LoadX509KeyPair error branch in getHTTPClient.
|
|
cfg := &globalsign.Config{
|
|
APIUrl: "http://example.invalid",
|
|
APIKey: secret.NewRefFromString("k"),
|
|
APISecret: secret.NewRefFromString("s"),
|
|
ClientCertPath: "/nonexistent/cert.pem",
|
|
ClientKeyPath: "/nonexistent/key.pem",
|
|
}
|
|
c := globalsign.New(cfg, slog.Default())
|
|
_, err := c.GetOrderStatus(context.Background(), "x")
|
|
if err == nil || !strings.Contains(err.Error(), "client certificate") {
|
|
t.Errorf("expected 'client certificate' load error, got %v", err)
|
|
}
|
|
}
|