mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-12 06:58:52 +00:00
ece15cb457
Closes Top-10 fix #2 of the 2026-05-03 issuer-coverage audit (see cowork/issuer-coverage-audit-2026-05-03/RESULTS.md). Pre-fix, vault.Config.Token and digicert.Config.APIKey were plain string fields. Practical impact: 1. GET /api/v1/issuers responses marshalled the credential into the JSON body. An acquirer's procurement engineer running 'curl /api/v1/issuers | jq' saw the token / API key in plain text on screen. 2. DEBUG-level HTTP request logging printed the credential header verbatim. 3. A heap dump of the running server contained the credential as readable bytes for the lifetime of the process. Bundle I from the 2026-05-01 audit closed this for AWSACMPCA, EJBCA, GlobalSign, Sectigo (Phase 1+2). Vault and DigiCert were left out. This commit ports the same migration onto them. Mechanics: - Config.Token / Config.APIKey type changed from 'string' to '*secret.Ref'. UnmarshalJSON of a JSON string populates the Ref via NewRefFromString — operator config files are unchanged. - Every header-write call site routed through Ref.Use, with the byte buffer zeroed after the callback returns. Vault: 3 sites (IssueCertificate, RevokeCertificate, GetCACertPEM). DigiCert: 5 sites (ValidateConfig, IssueCertificate, RevokeCertificate, pollOrderOnce, downloadCertificate). - ValidateConfig nil-checks switch from 'cfg.Token == ""' to 'cfg.Token.IsEmpty()' (mirrors Sectigo's existing pattern). - Tests migrated: every Config{Token:"..."} → Config{Token: secret.NewRefFromString("...")}. The 'json.Marshal(config) → ValidateConfig(rawConfig)' round-trip pattern in DigiCert's ValidateConfig_Success test is now broken by the redact-on-marshal contract — switched that one to construct the rawConfig as a JSON literal (mirrors Sectigo's existing test pattern). - Two new tests pin the redact-on-marshal contract: - TestVault_Config_TokenMarshalsAsRedacted (vault_redact_test.go) - TestDigiCert_Config_APIKeyMarshalsAsRedacted (digicert_redact_test.go) Both assert the marshaled JSON contains '"[redacted]"' and does NOT contain the plaintext bytes. Operator-visible: GET /api/v1/issuers responses for type=vault and type=digicert now show the credential as '[redacted]'. Existing config files keep working — the Ref unmarshal accepts strings. CHANGELOG note: certctl/CHANGELOG.md is intentionally not hand-edited; release notes are auto-generated from commit messages between consecutive tags. This commit's message body is the release-note artifact. Verified locally: - gofmt clean across the repo. - go vet ./... clean across the repo. - go test -race -count=1 -short ./internal/connector/issuer/vault/... ./internal/connector/issuer/digicert/... ./internal/secret/... green. Audit reference: cowork/issuer-coverage-audit-2026-05-03/ RESULTS.md Top-10 fix #2.
150 lines
5.3 KiB
Go
150 lines
5.3 KiB
Go
package vault_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/shankar0123/certctl/internal/connector/issuer"
|
|
"github.com/shankar0123/certctl/internal/connector/issuer/vault"
|
|
"github.com/shankar0123/certctl/internal/secret"
|
|
)
|
|
|
|
// Bundle N.A/B-extended: failure-mode round-out for Vault PKI connector.
|
|
// Exercises uncovered branches in IssueCertificate (malformed response,
|
|
// empty cert, structured Vault error format) and GetCACertPEM (non-200,
|
|
// connection error). Pushes vault 84.1% → ≥85%.
|
|
|
|
func TestVault_IssueCertificate_StructuredVaultError(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch {
|
|
case strings.HasSuffix(r.URL.Path, "/sys/health"):
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{"initialized":true,"sealed":false,"standby":false}`))
|
|
default:
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
// Vault's structured error format: {"errors": [...]}
|
|
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"errors": []string{"role policy missing", "ttl exceeds max"},
|
|
})
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
|
|
c := buildVaultConnector(t, srv.URL)
|
|
_, err := c.IssueCertificate(context.Background(), issuer.IssuanceRequest{
|
|
CommonName: "x.example.com",
|
|
CSRPEM: "-----BEGIN CERTIFICATE REQUEST-----\nfake\n-----END CERTIFICATE REQUEST-----",
|
|
})
|
|
if err == nil {
|
|
t.Fatalf("expected error for 400 with structured Vault errors")
|
|
}
|
|
if !strings.Contains(err.Error(), "role policy missing") {
|
|
t.Errorf("expected error to surface Vault's structured errors, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestVault_IssueCertificate_MalformedResponseJSON(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch {
|
|
case strings.HasSuffix(r.URL.Path, "/sys/health"):
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{"initialized":true,"sealed":false,"standby":false}`))
|
|
default:
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{not valid json`))
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
c := buildVaultConnector(t, srv.URL)
|
|
_, err := c.IssueCertificate(context.Background(), issuer.IssuanceRequest{
|
|
CommonName: "x.example.com",
|
|
CSRPEM: "-----BEGIN CERTIFICATE REQUEST-----\nfake\n-----END CERTIFICATE REQUEST-----",
|
|
})
|
|
if err == nil || !strings.Contains(err.Error(), "parse") {
|
|
t.Errorf("expected parse error for malformed JSON, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestVault_IssueCertificate_EmptyCertificate(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch {
|
|
case strings.HasSuffix(r.URL.Path, "/sys/health"):
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{"initialized":true,"sealed":false,"standby":false}`))
|
|
default:
|
|
w.WriteHeader(http.StatusOK)
|
|
// Vault response shape with empty certificate field
|
|
_, _ = w.Write([]byte(`{"data":{"certificate":"","serial_number":"01:02:03"}}`))
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
c := buildVaultConnector(t, srv.URL)
|
|
_, err := c.IssueCertificate(context.Background(), issuer.IssuanceRequest{
|
|
CommonName: "x.example.com",
|
|
CSRPEM: "-----BEGIN CERTIFICATE REQUEST-----\nfake\n-----END CERTIFICATE REQUEST-----",
|
|
})
|
|
if err == nil || !strings.Contains(err.Error(), "no certificate") {
|
|
t.Errorf("expected 'no certificate' error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestVault_IssueCertificate_MalformedCertPEM(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch {
|
|
case strings.HasSuffix(r.URL.Path, "/sys/health"):
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{"initialized":true,"sealed":false,"standby":false}`))
|
|
default:
|
|
w.WriteHeader(http.StatusOK)
|
|
// Cert is non-PEM garbage
|
|
_, _ = w.Write([]byte(`{"data":{"certificate":"not-a-pem-block","serial_number":"01"}}`))
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
c := buildVaultConnector(t, srv.URL)
|
|
_, err := c.IssueCertificate(context.Background(), issuer.IssuanceRequest{
|
|
CommonName: "x.example.com",
|
|
CSRPEM: "-----BEGIN CERTIFICATE REQUEST-----\nfake\n-----END CERTIFICATE REQUEST-----",
|
|
})
|
|
if err == nil || !strings.Contains(err.Error(), "decode") {
|
|
t.Errorf("expected PEM-decode error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestVault_GetCACertPEM_Non200_ReturnsError(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch {
|
|
case strings.HasSuffix(r.URL.Path, "/sys/health"):
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{"initialized":true,"sealed":false,"standby":false}`))
|
|
default:
|
|
// CA cert endpoint returns 403
|
|
w.WriteHeader(http.StatusForbidden)
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
c := buildVaultConnector(t, srv.URL)
|
|
_, err := c.GetCACertPEM(context.Background())
|
|
if err == nil || !strings.Contains(err.Error(), "403") {
|
|
t.Errorf("expected 403 error, got %v", err)
|
|
}
|
|
}
|
|
|
|
// buildVaultConnector constructs a vault.Connector pointed at the given URL
|
|
// by going through ValidateConfig (which the existing test pattern uses).
|
|
func buildVaultConnector(t *testing.T, url string) *vault.Connector {
|
|
t.Helper()
|
|
c := vault.New(nil, slog.Default())
|
|
cfg := vault.Config{Addr: url, Token: secret.NewRefFromString("tok"), Mount: "pki", Role: "web", TTL: "1h"}
|
|
raw, _ := json.Marshal(cfg)
|
|
if err := c.ValidateConfig(context.Background(), raw); err != nil {
|
|
t.Fatalf("ValidateConfig: %v", err)
|
|
}
|
|
return c
|
|
}
|