Files
certctl/internal/service/verification_test.go
T
Shankar 345bafe5aa 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)
2026-04-27 00:08:25 +00:00

290 lines
8.0 KiB
Go

package service
import (
"context"
"errors"
"log/slog"
"testing"
"time"
"github.com/shankar0123/certctl/internal/domain"
)
// mockVerificationJobRepo is a test double for JobRepository used by verification tests.
type mockVerificationJobRepo struct {
jobs map[string]*domain.Job
err error
}
func (m *mockVerificationJobRepo) Get(ctx context.Context, id string) (*domain.Job, error) {
if m.err != nil {
return nil, m.err
}
job, ok := m.jobs[id]
if !ok {
return nil, errors.New("job not found")
}
return job, nil
}
func (m *mockVerificationJobRepo) Create(ctx context.Context, job *domain.Job) error {
m.jobs[job.ID] = job
return nil
}
func (m *mockVerificationJobRepo) Update(ctx context.Context, job *domain.Job) error {
if m.err != nil {
return m.err
}
m.jobs[job.ID] = job
return nil
}
func (m *mockVerificationJobRepo) List(ctx context.Context) ([]*domain.Job, error) {
return nil, nil
}
func (m *mockVerificationJobRepo) Delete(ctx context.Context, id string) error {
delete(m.jobs, id)
return nil
}
func (m *mockVerificationJobRepo) ListByStatus(ctx context.Context, status domain.JobStatus) ([]*domain.Job, error) {
return nil, nil
}
func (m *mockVerificationJobRepo) ListByCertificate(ctx context.Context, certID string) ([]*domain.Job, error) {
return nil, nil
}
func (m *mockVerificationJobRepo) UpdateStatus(ctx context.Context, id string, status domain.JobStatus, errMsg string) error {
return nil
}
func (m *mockVerificationJobRepo) GetPendingJobs(ctx context.Context, jobType domain.JobType) ([]*domain.Job, error) {
return nil, nil
}
func (m *mockVerificationJobRepo) ListPendingByAgentID(ctx context.Context, agentID string) ([]*domain.Job, error) {
return nil, nil
}
func (m *mockVerificationJobRepo) ClaimPendingJobs(ctx context.Context, jobType domain.JobType, limit int) ([]*domain.Job, error) {
return nil, nil
}
func (m *mockVerificationJobRepo) ClaimPendingByAgentID(ctx context.Context, agentID string) ([]*domain.Job, error) {
return nil, nil
}
func (m *mockVerificationJobRepo) ListTimedOutAwaitingJobs(ctx context.Context, csrCutoff, approvalCutoff time.Time) ([]*domain.Job, error) {
return nil, nil
}
// Bundle C / Audit M-016: stub for the new offline-agent reaper repo method.
func (m *mockVerificationJobRepo) ListJobsWithOfflineAgents(ctx context.Context, agentCutoff time.Time) ([]*domain.Job, error) {
return nil, nil
}
// newVerificationTestService creates a VerificationService wired with test doubles.
func newVerificationTestService(jobs map[string]*domain.Job, jobRepoErr error) (*VerificationService, *mockVerificationJobRepo, *mockAuditRepo) {
jobRepo := &mockVerificationJobRepo{jobs: jobs, err: jobRepoErr}
auditRepo := newMockAuditRepository()
auditService := NewAuditService(auditRepo)
svc := NewVerificationService(jobRepo, auditService, slog.Default())
return svc, jobRepo, auditRepo
}
func TestVerificationService_RecordVerificationResult_Success(t *testing.T) {
ctx := context.Background()
jobs := map[string]*domain.Job{
"j-test1": {
ID: "j-test1",
Status: domain.JobStatusCompleted,
},
}
svc, jobRepo, auditRepo := newVerificationTestService(jobs, nil)
result := &domain.VerificationResult{
JobID: "j-test1",
TargetID: "t-nginx1",
ExpectedFingerprint: "abc123",
ActualFingerprint: "abc123",
Verified: true,
VerifiedAt: time.Now().UTC(),
}
err := svc.RecordVerificationResult(ctx, result)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Check job was updated
job, _ := jobRepo.Get(ctx, "j-test1")
if job.VerificationStatus != domain.VerificationSuccess {
t.Errorf("expected VerificationSuccess, got %s", job.VerificationStatus)
}
if job.VerifiedAt == nil {
t.Error("expected verified_at to be set")
}
// Check audit event was recorded
if len(auditRepo.Events) == 0 {
t.Error("expected at least 1 audit event")
}
}
func TestVerificationService_RecordVerificationResult_Failed(t *testing.T) {
ctx := context.Background()
jobs := map[string]*domain.Job{
"j-test2": {
ID: "j-test2",
Status: domain.JobStatusCompleted,
},
}
svc, jobRepo, _ := newVerificationTestService(jobs, nil)
result := &domain.VerificationResult{
JobID: "j-test2",
TargetID: "t-apache1",
ExpectedFingerprint: "aaa111",
ActualFingerprint: "bbb222",
Verified: false,
VerifiedAt: time.Now().UTC(),
}
err := svc.RecordVerificationResult(ctx, result)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
job, _ := jobRepo.Get(ctx, "j-test2")
if job.VerificationStatus != domain.VerificationFailed {
t.Errorf("expected VerificationFailed, got %s", job.VerificationStatus)
}
}
func TestVerificationService_RecordVerificationResult_WithError(t *testing.T) {
ctx := context.Background()
jobs := map[string]*domain.Job{
"j-test3": {
ID: "j-test3",
Status: domain.JobStatusCompleted,
},
}
svc, jobRepo, _ := newVerificationTestService(jobs, nil)
result := &domain.VerificationResult{
JobID: "j-test3",
TargetID: "t-haproxy1",
VerifiedAt: time.Now().UTC(),
Error: "connection refused",
}
err := svc.RecordVerificationResult(ctx, result)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
job, _ := jobRepo.Get(ctx, "j-test3")
if job.VerificationStatus != domain.VerificationFailed {
t.Errorf("expected VerificationFailed, got %s", job.VerificationStatus)
}
if job.VerificationError == nil || *job.VerificationError != "connection refused" {
t.Error("expected verification error to be set")
}
}
func TestVerificationService_RecordVerificationResult_JobNotFound(t *testing.T) {
ctx := context.Background()
svc, _, _ := newVerificationTestService(map[string]*domain.Job{}, nil)
result := &domain.VerificationResult{
JobID: "j-nonexistent",
TargetID: "t-nginx1",
VerifiedAt: time.Now().UTC(),
}
err := svc.RecordVerificationResult(ctx, result)
if err == nil {
t.Error("expected error for nonexistent job")
}
}
func TestVerificationService_RecordVerificationResult_MissingJobID(t *testing.T) {
ctx := context.Background()
svc, _, _ := newVerificationTestService(map[string]*domain.Job{}, nil)
result := &domain.VerificationResult{
TargetID: "t-nginx1",
VerifiedAt: time.Now().UTC(),
}
err := svc.RecordVerificationResult(ctx, result)
if err == nil {
t.Error("expected error for missing job ID")
}
}
func TestVerificationService_RecordVerificationResult_NilResult(t *testing.T) {
ctx := context.Background()
svc, _, _ := newVerificationTestService(map[string]*domain.Job{}, nil)
err := svc.RecordVerificationResult(ctx, nil)
if err == nil {
t.Error("expected error for nil result")
}
}
func TestVerificationService_GetVerificationResult_Success(t *testing.T) {
ctx := context.Background()
now := time.Now().UTC()
targetID := "t-nginx1"
fp := "abc123"
jobs := map[string]*domain.Job{
"j-test1": {
ID: "j-test1",
TargetID: &targetID,
VerificationStatus: domain.VerificationSuccess,
VerifiedAt: &now,
VerificationFp: &fp,
},
}
svc, _, _ := newVerificationTestService(jobs, nil)
result, err := svc.GetVerificationResult(ctx, "j-test1")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if result.JobID != "j-test1" {
t.Errorf("expected job ID j-test1, got %s", result.JobID)
}
if !result.Verified {
t.Error("expected Verified to be true")
}
if result.ActualFingerprint != "abc123" {
t.Errorf("expected fingerprint abc123, got %s", result.ActualFingerprint)
}
}
func TestVerificationService_GetVerificationResult_NotFound(t *testing.T) {
ctx := context.Background()
svc, _, _ := newVerificationTestService(map[string]*domain.Job{}, nil)
_, err := svc.GetVerificationResult(ctx, "j-nonexistent")
if err == nil {
t.Error("expected error for nonexistent job")
}
}
func TestVerificationService_GetVerificationResult_EmptyJobID(t *testing.T) {
ctx := context.Background()
svc, _, _ := newVerificationTestService(map[string]*domain.Job{}, nil)
_, err := svc.GetVerificationResult(ctx, "")
if err == nil {
t.Error("expected error for empty job ID")
}
}