Bundle C: Renewal/reliability cluster — 7 findings closed

Closes M-006 + M-007 + M-008 + M-015 + M-016 + M-019 + M-020 from
comprehensive-audit-2026-04-25. M-028 was already closed by the
Bundle B CI follow-up.

M-006 (CWE-913) — Idempotent migration 000014
  migrations/000014_policy_violation_severity_check.up.sql:
    Prepended ALTER TABLE ... DROP CONSTRAINT IF EXISTS before the
    ADD. Mirrors the down migration's existing IF EXISTS shape and
    the M-7 idempotent-index idiom. Re-runs against partially-applied
    DBs now succeed.

M-007 — Bulk-op partial-failure tests (3 new)
  internal/api/handler/bulk_partial_failure_test.go:
    TestBulkRevoke_PartialFailure_ReportsBoth
    TestBulkRenew_PartialFailure_ReportsBoth
    TestBulkReassign_PartialFailure_ReportsBoth
  Each asserts HTTP 200 + both success/failure counters round-trip
  + per-cert errors[] preserved with non-empty messages so operators
  can correlate each failure to its certificate ID.

M-008 — Admin-gated handler enumeration pin (verified-already-clean)
  Recon: only one admin-gated handler — bulk_revocation.go — with
  full 3-branch test triplet already in place. health.go calls
  IsAdmin informationally to surface the flag to the GUI without
  gating.
  internal/api/handler/m008_admin_gate_test.go:
    Walks every handler .go file, asserts every middleware.IsAdmin
    call site is in AdminGatedHandlers (with required test triplet)
    or InformationalIsAdminCallers (justified). Adding a new admin
    gate without updating both the constant AND adding the test
    triplet fails CI.

M-015 — Single-profile cardinality pin (verified-already-clean)
  Audit claim 'no cardinality validation' was wrong — enforced at
  struct level. domain.ManagedCertificate.{CertificateProfileID,
  RenewalPolicyID,IssuerID,OwnerID} and RenewalPolicy.
  CertificateProfileID are bare strings, not slices.
  internal/domain/m015_cardinality_test.go:
    reflect-based pin on kind=String. Schema change to N:N would
    have to update renewal.go's lookup loop in the same commit.

M-016 (CWE-754) — Reap stale-agent jobs
  internal/repository/postgres/job.go::ListJobsWithOfflineAgents:
    JOIN jobs to agents on agent_id, filter (status=Running AND
    a.last_heartbeat_at < cutoff), exclude server-keygen jobs.
  internal/service/job.go::ReapJobsWithOfflineAgents:
    Flips matched jobs to Failed reason agent_offline so I-001
    retry loop re-queues them on a healthy agent. Records audit
    event per reap.
  internal/scheduler/scheduler.go:
    Scheduler.runJobTimeout cycle now calls both reaper arms.
    agentOfflineJobTTL default 5min (5x agent-health-check default);
    SetAgentOfflineJobTTL knob for operator override.
  internal/service/job_offline_agent_reaper_test.go: 6 unit tests
  cover happy path, server-keygen-skip, non-Running-skip, non-
  positive-TTL fail-loud, repo-error propagation, audit-event
  recording.

M-019 — Configurable ARI HTTP timeout
  Audit claim 'no fallback timeout' was wrong — ari.go:52 already
  had a 15s timeout. Bundle C makes it configurable.
  internal/connector/issuer/acme/acme.go:
    Config.ARIHTTPTimeoutSeconds field with env path
    CERTCTL_ACME_ARI_HTTP_TIMEOUT_SECONDS.
  internal/connector/issuer/acme/ari.go:
    Both HTTP clients (GetRenewalInfo + getARIEndpoint) now use the
    new ariHTTPTimeout() helper. Zero / negative / nil-config all
    fall back to the historic 15s default.
  ari_timeout_test.go: 4 dispatch arm tests.

M-020 (CWE-770) — OCSP DoS hardening
  Pre-bundle the noAuthHandler chain had no rate limit. An attacker
  could DoS the OCSP responder, which for fail-open relying parties
  is a revocation bypass.
  cmd/server/main.go:
    noAuthHandler refactored from fixed middleware.Chain(...) to a
    conditional slice that appends middleware.NewRateLimiter when
    cfg.RateLimit.Enabled. Per-IP keying applies; OCSP/CRL/EST/SCEP
    are unauth.
  docs/security.md (NEW):
    Operator runbook documenting Must-Staple TLS Feature extension
    RFC 7633 as the architectural fix for fail-open relying parties.
    Profile-flip guidance + nginx/Apache/HAProxy/Envoy stapling
    snippets + explicit scope statement on what the rate limiter
    alone does NOT solve.

Audit deliverables:
  cowork/comprehensive-audit-2026-04-25/audit-report.md: score
    31/55 -> 38/55 closed (Medium 13/27 -> 20/27).
  cowork/comprehensive-audit-2026-04-25/findings.yaml: 7 status
    flips open -> closed with closure notes citing the Bundle C
    mechanism.
  certctl/CHANGELOG.md: Bundle C section under [unreleased].

Verification:
  go vet ./internal/service ./internal/scheduler ./internal/connector/issuer/acme
    ./internal/api/handler ./internal/domain ./cmd/server     clean
  go test -count=1 -short on the same packages              all green
  helm template + helm lint                                 clean
  internal/repository/postgres setup-fail                   sandbox disk
    pressure (same on master HEAD before this branch)
This commit is contained in:
Shankar
2026-04-27 00:08:25 +00:00
parent a24fe45aa1
commit 345bafe5aa
18 changed files with 1034 additions and 18 deletions
+12
View File
@@ -66,6 +66,18 @@ type Config struct {
// When enabled, the connector queries the CA's ARI endpoint to get CA-directed renewal timing.
ARIEnabled bool `json:"ari_enabled,omitempty"`
// ARIHTTPTimeoutSeconds bounds the per-request timeout on ARI HTTP calls.
// Bundle C / Audit M-019: a CA whose ARI endpoint is unreachable or
// stalls indefinitely must not stall the renewal scheduler — the
// fallback path is threshold-based renewal, which only kicks in once
// the ARI request errors out. The audit's "no fallback timeout" claim
// was wrong (a 15s default has been in place since the ARI feature
// shipped), but the previous timeout was hardcoded; this knob makes
// it configurable per-issuer for operators on flaky-CA networks.
// Defaults to 15 when zero. CERTCTL_ACME_ARI_HTTP_TIMEOUT_SECONDS in
// the env-driven build path.
ARIHTTPTimeoutSeconds int `json:"ari_http_timeout_seconds,omitempty"`
// Insecure skips TLS certificate verification when connecting to the ACME directory.
// Only use for testing with self-signed ACME servers like Pebble.
Insecure bool `json:"insecure,omitempty"`
+12 -2
View File
@@ -49,7 +49,7 @@ func (c *Connector) GetRenewalInfo(ctx context.Context, certPEM string) (*issuer
return nil, fmt.Errorf("create ARI request: %w", err)
}
httpClient := &http.Client{Timeout: 15 * time.Second}
httpClient := &http.Client{Timeout: c.ariHTTPTimeout()}
resp, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("ARI request failed: %w", err)
@@ -115,12 +115,22 @@ func computeARICertID(certPEM string) (string, error) {
return certID, nil
}
// ariHTTPTimeout returns the per-request timeout for ARI HTTP calls. Bundle C
// / Audit M-019: configurable via Config.ARIHTTPTimeoutSeconds (env var
// CERTCTL_ACME_ARI_HTTP_TIMEOUT_SECONDS), defaults to 15 seconds.
func (c *Connector) ariHTTPTimeout() time.Duration {
if c.config != nil && c.config.ARIHTTPTimeoutSeconds > 0 {
return time.Duration(c.config.ARIHTTPTimeoutSeconds) * time.Second
}
return 15 * time.Second
}
// getARIEndpoint constructs the ARI endpoint URL from the ACME directory.
// It fetches the directory JSON and extracts the "renewalInfo" field if available.
// Falls back to a standard URL pattern if the directory doesn't advertise renewalInfo.
func (c *Connector) getARIEndpoint(ctx context.Context, certID string) (string, error) {
// Try to fetch and parse the directory
httpClient := &http.Client{Timeout: 15 * time.Second}
httpClient := &http.Client{Timeout: c.ariHTTPTimeout()}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.config.DirectoryURL, nil)
if err != nil {
return "", fmt.Errorf("create directory request: %w", err)
@@ -0,0 +1,69 @@
package acme
import (
"log/slog"
"testing"
"time"
)
// Bundle C / Audit M-019 (CWE-400): pin the ARI HTTP timeout dispatch
// contract. Config.ARIHTTPTimeoutSeconds = 0 → 15s default. Non-zero
// values override. The 15s default predates Bundle C and is preserved
// byte-for-byte; this test guards against a future refactor that drops
// the default and silently configures HTTP clients with no timeout
// (which would re-open the M-019 stall risk).
func newARITestConnector(t *testing.T, timeoutSec int) *Connector {
t.Helper()
cfg := &Config{
DirectoryURL: "https://acme.example.invalid/directory",
ARIEnabled: true,
ARIHTTPTimeoutSeconds: timeoutSec,
}
return New(cfg, slog.New(slog.NewTextHandler(testDiscardWriter{}, nil)))
}
type testDiscardWriter struct{}
func (testDiscardWriter) Write(p []byte) (int, error) { return len(p), nil }
func TestARIHTTPTimeout_DefaultIs15s(t *testing.T) {
c := newARITestConnector(t, 0)
got := c.ariHTTPTimeout()
want := 15 * time.Second
if got != want {
t.Errorf("ariHTTPTimeout default: got %s, want %s", got, want)
}
}
func TestARIHTTPTimeout_NonZeroOverridesDefault(t *testing.T) {
c := newARITestConnector(t, 45)
got := c.ariHTTPTimeout()
want := 45 * time.Second
if got != want {
t.Errorf("ariHTTPTimeout override: got %s, want %s", got, want)
}
}
func TestARIHTTPTimeout_NegativeValuesUseDefault(t *testing.T) {
// Negative values are nonsensical but should fall back to the
// default rather than producing an immediate-timeout client.
c := newARITestConnector(t, -1)
got := c.ariHTTPTimeout()
want := 15 * time.Second
if got != want {
t.Errorf("negative ariHTTPTimeout should fall back to default: got %s, want %s", got, want)
}
}
func TestARIHTTPTimeout_NilConfigSafeDefault(t *testing.T) {
// Defensive: a connector with nil config must not panic and must
// return the documented default. This is a guard for tests / DI
// callers that hand in a partially-built Connector.
c := &Connector{}
got := c.ariHTTPTimeout()
want := 15 * time.Second
if got != want {
t.Errorf("nil-config ariHTTPTimeout: got %s, want %s", got, want)
}
}