Files
certctl/internal/service/bulk_revocation.go
T
shankar0123 5a682db8e2 EST RFC 7030 hardening master bundle Phases 10-11: libest sidecar e2e
+ Cisco IOS quirk fixtures + ManagedCertificate.Source provenance +
EST bulk-revoke endpoint + 13 typed audit action codes.

Phase 10.1 — libest reference-client sidecar:
- deploy/test/libest/Dockerfile: multi-stage Debian-bookworm-slim
  build of Cisco's libest v3.2.0-2 from source (autoconf/automake/
  libtool + libcurl4-openssl-dev + libssl-dev). Runtime stage
  carries only estclient + bash + openssl + ca-certificates so the
  exec surface stays small + predictable.
- docker-compose.test.yml libest-client entry (profiles: [est-e2e])
  with bind mounts for /config/est (test workspace) + /config/certs
  (certctl CA bundle for TLS pinning); IP 10.30.50.9 (10.30.50.8
  was already taken by certctl-agent).
- deploy/test/est/.gitkeep keeps the bind-mount target tracked.

Phase 10.2 — 5 integration tests (//go:build integration) in
deploy/test/est_e2e_test.go:
- TestEST_LibESTClient_Enrollment_Integration (cacerts → simpleenroll
  → cert-shape assertion)
- TestEST_LibESTClient_MTLSEnrollment_Integration (mTLS sibling-route
  cert auth; skip when bootstrap cert absent)
- TestEST_LibESTClient_ServerKeygen_Integration (RFC 7030 §4.4
  multipart; skip when profile gate disabled)
- TestEST_LibESTClient_RateLimited_Integration (4th enroll trips
  per-principal cap, asserts 429-shaped error)
- TestEST_LibESTClient_ChannelBinding_Integration (libest
  --tls-exporter; skip when libest build lacks the flag).
- requireESTSidecar guard skips the suite when the operator forgot
  --profile est-e2e; helpful error message includes the exact
  command to bring the sidecar up.

Phase 10.3 — Cisco IOS quirk fixtures + 3 unit tests in
internal/api/handler/cisco_ios_quirks_test.go:
- testdata/cisco_ios_15x_pem_csr.txt: PEM body sent with
  Content-Type application/x-pem-file. Handler dispatches on
  body-prefix not Content-Type — accepts cleanly.
- testdata/cisco_ios_16x_trailing_newline_csr.txt: extra trailing
  newlines after base64 body. strings.TrimSpace tolerates.
- testdata/cisco_ios_crlf_b64_csr.txt: CRLF-wrapped base64.
  base64.StdEncoding handles CRLF + LF identically.

Phase 11.1 — ManagedCertificate.Source provenance:
- New domain.CertificateSource enum (Unspecified/EST/SCEP/API/Agent).
- Migration 000023_managed_certificates_source.up.sql adds source
  TEXT NOT NULL DEFAULT '' so existing rows scan as
  CertificateSourceUnspecified — back-compat: bulk-revoke filter
  treats empty as "any source".
- Postgres repo Insert/Update/scan paths all wire the new column.

Phase 11.2 — EST bulk-revoke endpoint:
- BulkRevocationCriteria.Source field (Source-only requests rejected
  as too broad — must accompany at least one narrower criterion).
- service.bulk_revocation.resolveCertificates post-filter by Source
  (empty=any, no SQL change so existing CertificateFilter callers
  unaffected).
- New BulkRevocationHandler.BulkRevokeEST method pins Source=EST +
  dispatches; new route POST /api/v1/est/certificates/bulk-revoke
  (M-008 admin-gated). openapi.yaml documented + parity-guard green.

Phase 11.3 — 13 typed audit action codes in
internal/service/est_audit_actions.go:
- est_simple_enroll_success / _failed
- est_simple_reenroll_success / _failed
- est_server_keygen_success / _failed
- est_auth_failed_basic / _mtls / _channel_binding
- est_rate_limited
- est_csr_policy_violation
- est_bulk_revoke
- est_trust_anchor_reloaded
- ESTService.processEnrollment + SimpleServerKeygen + ReloadTrust
  split-emit BOTH the legacy bare action codes (back-compat for the
  GUI activity-tab chip filters that match by exact string +
  existing audit-log analysers) AND the new typed _success / _failed
  variants (operator grep target + per-failure-mode counter).

Tests:
- internal/api/handler/bulk_revocation_est_test.go — 5 cases
  (admin-true happy path pins Source=EST + non-admin 403 +
  empty-criteria 400 + invalid-reason 400 + method-not-allowed).
- internal/service/est_audit_actions_test.go — 5 cases (SimpleEnroll
  legacy+typed emission / SimpleReEnroll typed / IssuerError
  typed-failed / PolicyViolation triple-emit /
  unique-string invariant).

Pre-commit verification (sandbox): gofmt clean, go vet clean
(excluding repository/postgres testcontainers limit), staticcheck
clean across api/handler/api/router/domain/service/deploy/test,
go test -short -count=1 green for every non-postgres Go package +
integration build (`go build -tags integration ./deploy/test/...`)
clean. G-3 docs-drift guard reproduced locally clean (Phases 10-11
added zero new env vars).

Spec preserved at cowork/est-rfc7030-hardening-prompt.md. Phases
12-13 (docs/est.md + WiFi/802.1X / IoT bootstrap / FreeRADIUS
recipes; release prep + tag) remain — post-2.1.0 work.
2026-04-30 00:52:43 +00:00

200 lines
6.3 KiB
Go

package service
import (
"context"
"fmt"
"log/slog"
"strings"
"github.com/shankar0123/certctl/internal/domain"
"github.com/shankar0123/certctl/internal/repository"
)
// BulkRevocationService coordinates bulk certificate revocation operations.
// It builds on the single-cert RevokeCertificateWithActor flow — no duplicate logic.
type BulkRevocationService struct {
revSvc *RevocationSvc
certRepo repository.CertificateRepository
auditService *AuditService
logger *slog.Logger
}
// NewBulkRevocationService creates a new BulkRevocationService.
func NewBulkRevocationService(
revSvc *RevocationSvc,
certRepo repository.CertificateRepository,
auditService *AuditService,
logger *slog.Logger,
) *BulkRevocationService {
return &BulkRevocationService{
revSvc: revSvc,
certRepo: certRepo,
auditService: auditService,
logger: logger,
}
}
// BulkRevoke revokes all certificates matching the given criteria.
// It reuses RevokeCertificateWithActor for each cert — partial failures don't abort the batch.
func (s *BulkRevocationService) BulkRevoke(ctx context.Context, criteria domain.BulkRevocationCriteria, reason string, actor string) (*domain.BulkRevocationResult, error) {
// Validate inputs
if criteria.IsEmpty() {
return nil, fmt.Errorf("at least one filter criterion is required")
}
if reason == "" {
return nil, fmt.Errorf("revocation reason is required")
}
if !domain.IsValidRevocationReason(reason) {
return nil, fmt.Errorf("invalid revocation reason: %s", reason)
}
// Resolve matching certificates
certs, err := s.resolveCertificates(ctx, criteria)
if err != nil {
return nil, fmt.Errorf("failed to resolve certificates: %w", err)
}
result := &domain.BulkRevocationResult{
TotalMatched: len(certs),
}
// Revoke each certificate, continuing on individual failures
for _, cert := range certs {
// Skip already-revoked or archived certs
if cert.Status == domain.CertificateStatusRevoked {
result.TotalSkipped++
continue
}
if cert.Status == domain.CertificateStatusArchived {
result.TotalSkipped++
continue
}
err := s.revSvc.RevokeCertificateWithActor(ctx, cert.ID, reason, actor)
if err != nil {
result.TotalFailed++
result.Errors = append(result.Errors, domain.BulkRevocationError{
CertificateID: cert.ID,
Error: err.Error(),
})
s.logger.Warn("bulk revocation: individual cert failed",
"certificate_id", cert.ID,
"error", err)
} else {
result.TotalRevoked++
}
}
// Record audit event for the bulk operation
criteriaDetails := s.buildAuditDetails(criteria)
criteriaDetails["reason"] = reason
criteriaDetails["total_matched"] = result.TotalMatched
criteriaDetails["total_revoked"] = result.TotalRevoked
criteriaDetails["total_skipped"] = result.TotalSkipped
criteriaDetails["total_failed"] = result.TotalFailed
if err := s.auditService.RecordEvent(ctx, actor, domain.ActorTypeUser,
"bulk_revocation_initiated", "certificate", "bulk",
criteriaDetails); err != nil {
s.logger.Error("failed to record bulk revocation audit event", "error", err)
}
return result, nil
}
// resolveCertificates fetches the set of certificates matching the bulk revocation criteria.
// When CertificateIDs are provided, it fetches each cert by ID individually.
// When filter criteria (profile, owner, etc.) are provided, it uses the repository List method.
// When both are provided, it intersects: only IDs that also match the filter criteria.
func (s *BulkRevocationService) resolveCertificates(ctx context.Context, criteria domain.BulkRevocationCriteria) ([]*domain.ManagedCertificate, error) {
hasFilterCriteria := criteria.ProfileID != "" || criteria.OwnerID != "" ||
criteria.AgentID != "" || criteria.IssuerID != "" || criteria.TeamID != ""
hasExplicitIDs := len(criteria.CertificateIDs) > 0
if hasExplicitIDs && !hasFilterCriteria {
// Only explicit IDs — fetch each cert by ID
var certs []*domain.ManagedCertificate
for _, id := range criteria.CertificateIDs {
cert, err := s.certRepo.Get(ctx, id)
if err != nil {
// Skip not-found certs — they'll count as "matched" but skipped
continue
}
certs = append(certs, cert)
}
return certs, nil
}
// Use filter-based query
filter := &repository.CertificateFilter{
OwnerID: criteria.OwnerID,
TeamID: criteria.TeamID,
IssuerID: criteria.IssuerID,
AgentID: criteria.AgentID,
ProfileID: criteria.ProfileID,
PerPage: 10000, // High limit to get all matching certs in one query
}
certs, _, err := s.certRepo.List(ctx, filter)
if err != nil {
return nil, err
}
// If explicit IDs also provided, intersect
if hasExplicitIDs {
idSet := make(map[string]bool, len(criteria.CertificateIDs))
for _, id := range criteria.CertificateIDs {
idSet[id] = true
}
var filtered []*domain.ManagedCertificate
for _, cert := range certs {
if idSet[cert.ID] {
filtered = append(filtered, cert)
}
}
certs = filtered
}
// EST RFC 7030 hardening master bundle Phase 11.2: per-source
// post-filter. Empty Source matches anything (back-compat); a
// non-empty Source narrows the result set to only certs stamped
// with that provenance value. Filter is applied here rather than
// in the SQL query so existing CertificateFilter callers are
// unaffected; the small per-cert pass is fine because bulk-revoke
// is already a low-frequency operation.
if criteria.Source != "" {
var bySource []*domain.ManagedCertificate
for _, cert := range certs {
if cert.Source == criteria.Source {
bySource = append(bySource, cert)
}
}
certs = bySource
}
return certs, nil
}
// buildAuditDetails constructs a map of criteria fields for the audit event.
func (s *BulkRevocationService) buildAuditDetails(criteria domain.BulkRevocationCriteria) map[string]interface{} {
details := map[string]interface{}{}
if criteria.ProfileID != "" {
details["profile_id"] = criteria.ProfileID
}
if criteria.OwnerID != "" {
details["owner_id"] = criteria.OwnerID
}
if criteria.AgentID != "" {
details["agent_id"] = criteria.AgentID
}
if criteria.IssuerID != "" {
details["issuer_id"] = criteria.IssuerID
}
if criteria.TeamID != "" {
details["team_id"] = criteria.TeamID
}
if len(criteria.CertificateIDs) > 0 {
details["certificate_ids"] = strings.Join(criteria.CertificateIDs, ",")
}
return details
}