mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 18:51:32 +00:00
c351bba41a
Closes the issuance loop in trust_authenticated mode (commitsec88a61+44a85d6wired the foundation + JWS-verified account resource). After this commit, an ACME client running against a profile with acme_auth_mode='trust_authenticated' end-to-end-issues a real cert: POST /acme/profile/<id>/new-order → 201 + order URL (status=ready) POST /acme/profile/<id>/order/<oid> → POST-as-GET fetch POST /acme/profile/<id>/order/<oid>/finalize → 200 + status=valid + cert URL POST /acme/profile/<id>/cert/<cid> → 200 + PEM chain Profiles with acme_auth_mode='challenge' get the same code path with authz/challenge rows in `pending` state until Phase 3's validators wire up. The mode is read from the bound profile's column at request time, NOT cached at server start — operators flipping the column via SQL take effect on the next order without restart. Architecture (the load-bearing part): - Finalize routes through service.CertificateService.Create — the canonical certctl issuance entry point that wraps the managed_certificates row insert + audit row in s.tx.WithinTx. RenewalPolicy / CertificateProfile / per-issuer-type Prometheus metrics / audit rows all apply uniformly to ACME-issued certs via the same code path that already serves EST/SCEP/agent/REST issuance. - Identifier validation runs BEFORE order creation. Rejected identifiers return RFC 7807 with per-identifier subproblems and create no order row. - Source stamp on managed_certificates: domain.CertificateSourceACME. Operators bulk-revoke ACME-issued certs by filtering on Source=ACME. - 3-step atomicity boundary documented in code + this commit msg: (A) WithinTx-A marks order processing + audit row. (B) IssuerConnector.IssueCertificate + CertificateService.Create (each in its own WithinTx — Create wraps cert row + audit atomically). (C) WithinTx-C creates certificate_versions row + transitions order to valid + sets certificate_id + audit row. The brief window between B and C can leave a managed_certificates row whose order is still in `processing`. Phase 5's GC scheduler reconciles. Documented inline. What ships: - internal/api/acme/order.go: OrderResponseJSON + AuthorizationResponseJSON + ChallengeResponseJSON + NewOrderRequest + FinalizeRequest wire shapes; ValidateIdentifiers (Phase 2 syntactic checks, dns-only); CSRMatchesIdentifiers (RFC 8555 §7.4 strict equality, case-folded). - internal/domain/acme.go: ACMEOrder + ACMEAuthorization + ACMEChallenge + ACMEIdentifier + ACMEProblem domain types + closed status enums for each (order: pending|ready|processing|valid|invalid; authz: pending|valid|invalid|deactivated|expired|revoked; challenge: pending|processing|valid|invalid; challenge type: http-01|dns-01| tls-alpn-01). - internal/domain/profile.go: new ACMEAuthMode field reading from certificate_profiles.acme_auth_mode (added in migration 25). - internal/domain/certificate.go: new CertificateSourceACME enum value. - internal/repository/postgres/profile.go: extended SELECT/scanProfile to read the per-profile acme_auth_mode column with a COALESCE default of trust_authenticated. - internal/repository/postgres/acme.go: full order/authz/challenge CRUD (CreateOrderWithTx + GetOrderByID + UpdateOrderWithTx + CreateAuthzWithTx + GetAuthzByID + ListAuthzsByOrder + ListChallengesByAuthz + CreateChallengeWithTx) with proper sql.NullTime + JSONB handling. scanACMEOrder / scanACMEAuthz / scanACMEChallenge helpers. - internal/service/acme.go: extended ACMERepo interface; new SetIssuancePipeline wires certificateService + certificateRepo + issuerRegistry. CreateOrder (auth-mode-dispatched: trust_authenticated auto-marks order ready + authz valid + 1 placeholder http-01 challenge valid; challenge mode keeps everything pending). LookupOrder (with account-ownership assertion). LookupAuthz. ListAuthzsByOrder. FinalizeOrder (3-step atomicity boundary as above; CSR-vs-order SAN strict-equality check before issuance; persists FinalizeOrderResult {Order, CertID}). LookupCertificate. randIDSuffix + base32encode helpers for the human-readable acme-ord-* / acme-authz-* / acme-chall-* prefixes (CLAUDE.md "TEXT primary keys with human- readable prefixes" architecture decision). 8 new per-op metrics. - internal/service/acme_test.go: extended fakeACMERepo with Phase 2 interface stubs; new orderTrackingRepo for observable persistence; 2 new tests asserting trust_authenticated → auto-ready/valid and challenge → stays-pending. - internal/api/handler/acme.go: NewOrder + Order + OrderFinalize + Authz + Cert handler methods. orderURL / authzURL / certURL / challengeURLBuilder helpers; marshalOrderForResponse fetches per-order authzs to populate the URL list. parseOptionalTime for notBefore / notAfter. - internal/api/handler/acme_handler_test.go: extended mockACMEService with Phase 2 method stubs; 4 new handler tests (NewOrder happy + rejected-identifier + OrderFinalize bad-CSR + Cert happy). - internal/api/router/router.go: 10 new Register calls (5 per-profile + 5 shorthand) for new-order, order/{ord_id}, order/{ord_id}/finalize, authz/{authz_id}, cert/{cert_id}. - internal/api/router/openapi_parity_test.go + api/openapi-handler-exceptions.yaml: 10 new exception entries. - cmd/server/main.go: SetIssuancePipeline at startup, threading certificateService + certificateRepo + issuerRegistry into ACMEService. - docs/acme-server.md: phase status updated; endpoints table grows 5 rows for new-order/order/finalize/authz/cert (per-profile + shorthand variants); new section "Finalize routing through CertificateService.Create" documenting the 3-step atomicity boundary + the actor-string convention `acme:<account-id>`. Tests: ACME package + service + handler + router + config + domain all green under -short. New cases: - TestCreateOrder_TrustAuthenticated_AutoReady (asserts auto-ready transition + valid-status authz/challenge + audit row + metric bump). - TestCreateOrder_ChallengeMode_StaysPending (asserts pending-status cascading authz/challenge for challenge mode). - TestACMEHandler_NewOrder_HappyPath (asserts 201 + Location + finalize URL shape). - TestACMEHandler_NewOrder_RejectedIdentifier (asserts 400 + RFC 7807 rejectedIdentifier + per-identifier subproblems for type=ip). - TestACMEHandler_OrderFinalize_BadCSR (asserts 400 + badCSR for non-base64 CSR field). - TestACMEHandler_Cert_HappyPath (asserts 200 + PEM content-type + PEM chain in body). Engineering history: cowork/WORKSPACE-CHANGELOG.md "ACME-Server-2".
258 lines
7.8 KiB
Go
258 lines
7.8 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/shankar0123/certctl/internal/repository"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/shankar0123/certctl/internal/domain"
|
|
)
|
|
|
|
// ProfileRepository implements repository.CertificateProfileRepository
|
|
type ProfileRepository struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
// NewProfileRepository creates a new ProfileRepository
|
|
func NewProfileRepository(db *sql.DB) *ProfileRepository {
|
|
return &ProfileRepository{db: db}
|
|
}
|
|
|
|
// List returns all certificate profiles
|
|
func (r *ProfileRepository) List(ctx context.Context) ([]*domain.CertificateProfile, error) {
|
|
rows, err := r.db.QueryContext(ctx, `
|
|
SELECT id, name, description, allowed_key_algorithms, max_ttl_seconds,
|
|
allowed_ekus, required_san_patterns, spiffe_uri_pattern,
|
|
allow_short_lived, must_staple, required_csr_attributes,
|
|
COALESCE(acme_auth_mode, 'trust_authenticated'),
|
|
enabled, created_at, updated_at
|
|
FROM certificate_profiles
|
|
ORDER BY created_at DESC
|
|
`)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to query profiles: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var profiles []*domain.CertificateProfile
|
|
for rows.Next() {
|
|
p, err := scanProfile(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
profiles = append(profiles, p)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("error iterating profile rows: %w", err)
|
|
}
|
|
|
|
return profiles, nil
|
|
}
|
|
|
|
// Get retrieves a certificate profile by ID
|
|
func (r *ProfileRepository) Get(ctx context.Context, id string) (*domain.CertificateProfile, error) {
|
|
row := r.db.QueryRowContext(ctx, `
|
|
SELECT id, name, description, allowed_key_algorithms, max_ttl_seconds,
|
|
allowed_ekus, required_san_patterns, spiffe_uri_pattern,
|
|
allow_short_lived, must_staple, required_csr_attributes,
|
|
COALESCE(acme_auth_mode, 'trust_authenticated'),
|
|
enabled, created_at, updated_at
|
|
FROM certificate_profiles
|
|
WHERE id = $1
|
|
`, id)
|
|
|
|
p, err := scanProfile(row)
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
return nil, fmt.Errorf("profile not found: %w", repository.ErrNotFound)
|
|
}
|
|
return nil, fmt.Errorf("failed to query profile: %w", err)
|
|
}
|
|
|
|
return p, nil
|
|
}
|
|
|
|
// Create stores a new certificate profile
|
|
func (r *ProfileRepository) Create(ctx context.Context, profile *domain.CertificateProfile) error {
|
|
if profile.ID == "" {
|
|
profile.ID = uuid.New().String()
|
|
}
|
|
if profile.CreatedAt.IsZero() {
|
|
profile.CreatedAt = time.Now()
|
|
}
|
|
if profile.UpdatedAt.IsZero() {
|
|
profile.UpdatedAt = time.Now()
|
|
}
|
|
|
|
algJSON, err := json.Marshal(profile.AllowedKeyAlgorithms)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal allowed_key_algorithms: %w", err)
|
|
}
|
|
ekuJSON, err := json.Marshal(profile.AllowedEKUs)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal allowed_ekus: %w", err)
|
|
}
|
|
sanJSON, err := json.Marshal(profile.RequiredSANPatterns)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal required_san_patterns: %w", err)
|
|
}
|
|
// Phase 6.1: required_csr_attributes is the per-profile EST csrattrs hint
|
|
// list. Marshal as JSONB; nil → "[]" via the json.Marshal stdlib contract.
|
|
csrAttrsJSON, err := json.Marshal(profile.RequiredCSRAttributes)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal required_csr_attributes: %w", err)
|
|
}
|
|
|
|
err = r.db.QueryRowContext(ctx, `
|
|
INSERT INTO certificate_profiles (
|
|
id, name, description, allowed_key_algorithms, max_ttl_seconds,
|
|
allowed_ekus, required_san_patterns, spiffe_uri_pattern,
|
|
allow_short_lived, must_staple, required_csr_attributes,
|
|
enabled, created_at, updated_at
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
|
RETURNING id
|
|
`, profile.ID, profile.Name, profile.Description, algJSON, profile.MaxTTLSeconds,
|
|
ekuJSON, sanJSON, profile.SPIFFEURIPattern,
|
|
profile.AllowShortLived, profile.MustStaple, csrAttrsJSON,
|
|
profile.Enabled, profile.CreatedAt, profile.UpdatedAt).Scan(&profile.ID)
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create profile: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Update modifies an existing certificate profile
|
|
func (r *ProfileRepository) Update(ctx context.Context, profile *domain.CertificateProfile) error {
|
|
profile.UpdatedAt = time.Now()
|
|
|
|
algJSON, err := json.Marshal(profile.AllowedKeyAlgorithms)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal allowed_key_algorithms: %w", err)
|
|
}
|
|
ekuJSON, err := json.Marshal(profile.AllowedEKUs)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal allowed_ekus: %w", err)
|
|
}
|
|
sanJSON, err := json.Marshal(profile.RequiredSANPatterns)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal required_san_patterns: %w", err)
|
|
}
|
|
csrAttrsJSON, err := json.Marshal(profile.RequiredCSRAttributes)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to marshal required_csr_attributes: %w", err)
|
|
}
|
|
|
|
result, err := r.db.ExecContext(ctx, `
|
|
UPDATE certificate_profiles SET
|
|
name = $1,
|
|
description = $2,
|
|
allowed_key_algorithms = $3,
|
|
max_ttl_seconds = $4,
|
|
allowed_ekus = $5,
|
|
required_san_patterns = $6,
|
|
spiffe_uri_pattern = $7,
|
|
allow_short_lived = $8,
|
|
must_staple = $9,
|
|
required_csr_attributes = $10,
|
|
enabled = $11,
|
|
updated_at = $12
|
|
WHERE id = $13
|
|
`, profile.Name, profile.Description, algJSON, profile.MaxTTLSeconds,
|
|
ekuJSON, sanJSON, profile.SPIFFEURIPattern,
|
|
profile.AllowShortLived, profile.MustStaple, csrAttrsJSON,
|
|
profile.Enabled, profile.UpdatedAt, profile.ID)
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("failed to update profile: %w", err)
|
|
}
|
|
|
|
rows, err := result.RowsAffected()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get rows affected: %w", err)
|
|
}
|
|
|
|
if rows == 0 {
|
|
return fmt.Errorf("profile not found: %w", repository.ErrNotFound)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Delete removes a certificate profile
|
|
func (r *ProfileRepository) Delete(ctx context.Context, id string) error {
|
|
result, err := r.db.ExecContext(ctx, "DELETE FROM certificate_profiles WHERE id = $1", id)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to delete profile: %w", err)
|
|
}
|
|
|
|
rows, err := result.RowsAffected()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get rows affected: %w", err)
|
|
}
|
|
|
|
if rows == 0 {
|
|
return fmt.Errorf("profile not found: %w", repository.ErrNotFound)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// scanProfile scans a certificate profile from a row or rows
|
|
func scanProfile(scanner interface {
|
|
Scan(...interface{}) error
|
|
}) (*domain.CertificateProfile, error) {
|
|
var p domain.CertificateProfile
|
|
var algJSON, ekuJSON, sanJSON, csrAttrsJSON []byte
|
|
|
|
err := scanner.Scan(
|
|
&p.ID, &p.Name, &p.Description, &algJSON, &p.MaxTTLSeconds,
|
|
&ekuJSON, &sanJSON, &p.SPIFFEURIPattern,
|
|
&p.AllowShortLived, &p.MustStaple, &csrAttrsJSON,
|
|
&p.ACMEAuthMode,
|
|
&p.Enabled, &p.CreatedAt, &p.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to scan profile: %w", err)
|
|
}
|
|
|
|
if len(algJSON) > 0 {
|
|
if err := json.Unmarshal(algJSON, &p.AllowedKeyAlgorithms); err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal allowed_key_algorithms: %w", err)
|
|
}
|
|
} else {
|
|
p.AllowedKeyAlgorithms = domain.DefaultKeyAlgorithms()
|
|
}
|
|
|
|
if len(ekuJSON) > 0 {
|
|
if err := json.Unmarshal(ekuJSON, &p.AllowedEKUs); err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal allowed_ekus: %w", err)
|
|
}
|
|
} else {
|
|
p.AllowedEKUs = domain.DefaultEKUs()
|
|
}
|
|
|
|
if len(sanJSON) > 0 {
|
|
if err := json.Unmarshal(sanJSON, &p.RequiredSANPatterns); err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal required_san_patterns: %w", err)
|
|
}
|
|
}
|
|
// Phase 6.1: required_csr_attributes column ships with default '[]', so
|
|
// every existing row scans into an empty slice (back-compat 204 stub
|
|
// behavior). Older rows from before the migration could land here as
|
|
// empty bytes — guard against that with the same len() check pattern.
|
|
if len(csrAttrsJSON) > 0 {
|
|
if err := json.Unmarshal(csrAttrsJSON, &p.RequiredCSRAttributes); err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal required_csr_attributes: %w", err)
|
|
}
|
|
}
|
|
|
|
return &p, nil
|
|
}
|