domain, migrations: ApprovalRequest type + issuance_approval_requests + RequiresApproval

Rank 7 of the 2026-05-03 Infisical deep-research deliverable, commit 1 of 4
(cowork/rank-7-approval-workflow-primitive-prompt.md). The four-commit
chain ships the issuance approval-workflow primitive (request → human review
→ CA call) closing the two-person integrity / four-eyes principle
procurement gap for PCI-DSS Level 1, FedRAMP Moderate / High, SOC 2
Type II, and HIPAA-regulated PHI deployments.

This commit lands ONLY the foundation — schema, types, repository
interface, postgres implementation. No service / handler wiring yet.
The four-commit shape is bisectable: the schema can land in production
behind a flag (via the default RequiresApproval=false on every existing
profile) without any operator-visible behavior change until commits 2-4
wire the surrounding workflow.

Existing scaffolding REUSED (not redefined here):
  - JobStatusAwaitingApproval enum value (internal/domain/job.go).
  - JobRepository.ListTimedOutAwaitingJobs (postgres reaper query).
  - Config.Scheduler.AwaitingApprovalTimeout (env-mapped via
    CERTCTL_JOB_AWAITING_APPROVAL_TIMEOUT, default 168h = 7 days).
  - Scheduler.SetAwaitingApprovalTimeout wiring.

Files added:
  internal/domain/approval.go              - ApprovalRequest type,
                                              ApprovalState closed enum
                                              (pending/approved/rejected/
                                              expired), IsValidApprovalState +
                                              IsTerminal helpers, outcome
                                              const block + bypass-actor
                                              sentinel.
  internal/repository/postgres/approval.go - ApprovalRepository
                                              implementation: Create
                                              (ar-<slug> ID gen + JSONB
                                              metadata round-trip + lib/pq
                                              23505 → ErrAlreadyExists
                                              translation), Get, GetByJobID,
                                              List (paginated with state /
                                              cert / requester filters),
                                              UpdateState (pending→terminal
                                              transitions only, with
                                              already-terminal disambiguation),
                                              ExpireStale (bulk reaper,
                                              decided_by='system-reaper').
  migrations/000027_approval_workflow.{up,down}.sql
                                            - Idempotent IF NOT EXISTS /
                                              IF EXISTS. Adds
                                              certificate_profiles.requires_approval
                                              BOOLEAN NOT NULL DEFAULT false,
                                              issuance_approval_requests
                                              table with FK to
                                              managed_certificates / jobs /
                                              certificate_profiles, four
                                              indexes (state, certificate,
                                              pending-age, partial-unique
                                              pending-per-job), and the
                                              approval_decision_consistency
                                              CHECK constraint enforcing
                                              decided_by/decided_at must be
                                              non-null for terminal states.

Files modified:
  internal/domain/profile.go               - Adds CertificateProfile.RequiresApproval
                                              bool field with full doc
                                              comment + JSON tag. Defaults
                                              to false (back-compat — every
                                              existing profile keeps the
                                              unattended renewal path).
  internal/repository/interfaces.go        - Adds ApprovalRepository
                                              interface (6 methods) +
                                              ApprovalFilter struct.
  internal/repository/errors.go            - Adds ErrAlreadyExists sentinel
                                              for postgres SQLSTATE 23505
                                              (unique-constraint violations
                                              from the partial-unique
                                              pending-per-job index, plus
                                              the "already terminal" state-
                                              transition signal). Mirrors
                                              the existing ErrNotFound +
                                              ErrForeignKeyConstraint shape.

Verified:
  gofmt: clean.
  go vet ./internal/domain/... ./internal/repository/...: exit 0.
  go build ./internal/domain/... ./internal/repository/...: exit 0.

Out of scope for this commit (lands in commits 2-4):
  - service/approval.go (RequestApproval / Approve / Reject / ListPending
    / ExpireStale + same-actor RBAC + bypass mode + audit + metrics).
  - service/approval_metrics.go (decisions counter + pending-age histogram).
  - 8 service-level table-driven tests including the load-bearing
    TestApproval_Approve_RejectsSameActor two-person integrity pin.
  - api/handler/approval.go (5 endpoints + RBAC integration).
  - api/openapi.yaml (5 new operationIds).
  - Integration into CertificateService.TriggerRenewal +
    RenewalService.CheckExpiringCertificates + Scheduler.ReapTimedOutJobs.
  - cmd/server/main.go wiring.
  - Config.Approval.BypassEnabled + CERTCTL_APPROVAL_BYPASS env var.
  - docs/connectors.md CertificateProfile config-table row.
  - docs/approval-workflow.md operator playbook + compliance control mapping.

Reference: cowork/infisical-deep-research-results.md Part 5 Rank 7.
Acquisition prompt: cowork/rank-7-approval-workflow-primitive-prompt.md.
This commit is contained in:
shankar0123
2026-05-04 00:55:17 +00:00
parent 9c80894c3c
commit b4d1ad1c97
7 changed files with 579 additions and 0 deletions
+57
View File
@@ -713,3 +713,60 @@ type HealthCheckFilter struct {
// PerPage is the number of results per page.
PerPage int
}
// ApprovalRepository defines operations for managing issuance approval requests.
// Rank 7 of the 2026-05-03 Infisical deep-research deliverable — closes the
// two-person integrity / four-eyes principle procurement gap for PCI-DSS
// Level 1, FedRAMP Moderate / High, SOC 2 Type II, HIPAA-regulated PHI.
//
// Lifecycle: Create inserts a row at state=pending; UpdateState transitions
// to one of (approved, rejected, expired) with the decider identity +
// timestamp + optional note; ExpireStale is the bulk reaper called from
// the scheduler. Once terminal, rows are immutable via the
// approval_decision_consistency CHECK constraint at the schema layer.
type ApprovalRepository interface {
// Create inserts a new ApprovalRequest at state=pending. Returns
// ErrAlreadyExists if a pending request already exists for the
// job_id (the partial-unique index enforces at most one pending
// per job).
Create(ctx context.Context, req *domain.ApprovalRequest) error
// Get returns the request by ID or ErrNotFound.
Get(ctx context.Context, id string) (*domain.ApprovalRequest, error)
// GetByJobID returns the most-recently-created request for the
// given job_id, regardless of state. Used by the renewal entry
// point to detect "is there already a pending approval for this
// job?" and avoid creating a duplicate.
GetByJobID(ctx context.Context, jobID string) (*domain.ApprovalRequest, error)
// List returns approval requests filtered by ApprovalFilter.
// Supports paginated dashboard queries.
List(ctx context.Context, filter *ApprovalFilter) ([]*domain.ApprovalRequest, error)
// UpdateState transitions a row from state=pending to one of
// (approved, rejected, expired). Returns ErrNotFound if the ID
// does not exist; returns the schema's CHECK-violation as a
// repository error if the row is already terminal.
UpdateState(ctx context.Context, id string, state domain.ApprovalState,
decidedBy string, decidedAt time.Time, note string) error
// ExpireStale transitions every row with state=pending and
// created_at <= before to state=expired. Returns the number of
// rows transitioned. Called from the scheduler reaper loop.
ExpireStale(ctx context.Context, before time.Time) (int, error)
}
// ApprovalFilter filters approval-request queries.
type ApprovalFilter struct {
// State filters by lifecycle state (pending, approved, rejected, expired).
State string
// CertificateID filters by managed certificate ID.
CertificateID string
// RequestedBy filters to requests created by the given actor.
RequestedBy string
// Page is the page number (1-indexed).
Page int
// PerPage is the number of results per page.
PerPage int
}