Files
certctl/internal/repository/postgres/profile.go
T
shankar0123 8bc9f4eed8 EST RFC 7030 hardening master bundle Phases 5-7: end-to-end serverkeygen
+ profile-driven csrattrs + admin observability with per-status
counters + reload-trust endpoint.

Phase 5 — RFC 7030 §4.4 server-driven key generation:
- internal/pkcs7/envelopeddata_builder.go is the inverse of the
  existing parser/decryptor: AES-256-CBC content cipher + RSA PKCS#1
  v1.5 keyTrans + per-call random IV. Round-trip pinned in test
  (BuildEnvelopedData → ParseEnvelopedData → Decrypt returns the
  original plaintext byte-for-byte).
- ESTService.SimpleServerKeygen runs the full §4.4 flow: parse client
  CSR → require RSA pubkey for keyTrans → resolve per-profile
  algorithm (RSA-2048 default; honors AllowedKeyAlgorithms) → in-
  memory keygen → re-build CSR with server pubkey → run existing
  issuer pipeline → marshal PKCS#8 → CMS-EnvelopedData wrap to a
  synthetic recipient cert wrapping the device's CSR-supplied pubkey
  → zeroize plaintext + PKCS#8 bytes → return CertPEM + ChainPEM
  + EncryptedKey. Typed sentinels ErrServerKeygenRequiresKey-
  Encipherment / ErrServerKeygenUnsupportedAlgorithm /
  ErrServerKeygenDisabled.
- ESTHandler.ServerKeygen + ServerKeygenMTLS emit RFC 7030 §4.4.2
  multipart/mixed with random per-response boundary; per-profile
  SetServerKeygenEnabled gate returns 404 when off (defense in depth
  even if the route was registered).
- New routes POST /.well-known/est/[<PathID>/]serverkeygen +
  /.well-known/est-mtls/<PathID>/serverkeygen; openapi.yaml +
  openapi-parity guard updated.

Phase 6 — Real csrattrs implementation:
- New CertificateProfile.RequiredCSRAttributes []string + migration
  000022_certificate_profiles_csrattrs.up.sql. The migration also
  lands the previously-unwired must_staple column (closes the 5.6
  follow-up loop where the field shipped at the domain + service
  layer but the postgres scan/insert/update never persisted it).
- domain.EKUStringToOID + AttributeStringToOID lookup tables: id-kp-*
  EKUs (RFC 5280 §4.2.1.12) + RFC 5280 DN attributes + RFC 2985
  PKCS#10 attributes + Microsoft Intune device-serial OID.
- ESTService.GetCSRAttrs replaces the v2.0.x nil/204 stub with a
  profile-derived SEQUENCE OF OID ASN.1 marshal. Unknown EKU /
  attribute strings dropped + warning-logged so a typo doesn't take
  down the entire endpoint.

Phase 7 — Admin observability + counters + reload-trust:
- internal/service/est_counters.go: estCounterTab (sync/atomic; 12
  named labels) + ESTStatsSnapshot per-profile shape +
  ESTService.Stats(now) zero-allocation accessor + ReloadTrust()
  SIGHUP-equivalent + SetESTAdminMetadata setter.
- Counter ticks wired into processEnrollment + SimpleServerKeygen at
  every success/failure leg.
- internal/api/handler/admin_est.go mirrors AdminSCEPIntune verbatim:
  Profiles + ReloadTrust handlers + AdminESTServiceImpl. Both
  endpoints admin-gated (M-008 triplet pinned + admin_est.go added
  to AdminGatedHandlers).
- New routes GET /api/v1/admin/est/profiles + POST /api/v1/admin/
  est/reload-trust; openapi.yaml documented; openapi-parity guard
  reproduced clean.
- cmd/server/main.go grows estServices map populated by the per-
  profile EST loop + handed to AdminEST. New MTLSTrust() +
  HasMTLSTrust() accessors on ESTHandler so main.go can pull the
  trust holder for the admin-metadata wire-up.
- Per-profile counter isolation regression test
  (internal/service/est_profile_counter_isolation_test.go) proves
  a future shared-counter refactor would fail at compile-time
  pointer-identity check.

Pre-commit verification (sandbox): gofmt clean, go vet clean
(excluding repository/postgres which the sandbox can't build —
disk-space testcontainers download), staticcheck clean across
cms/trustanchor/api/handler/api/router/scep/intune/ratelimit/
service/pkcs7/domain/cmd/server, go test -short -count=1 green
for every non-postgres package. G-3 docs-drift guard reproduced
locally clean (Phases 5-7 added zero new env vars; Phase 1
already documented per-profile SERVER_KEYGEN_ENABLED).

Spec preserved at cowork/est-rfc7030-hardening-prompt.md. Phases
8-13 (GUI ESTAdminPage / CLI+MCP / libest e2e / bulk revocation /
docs/est.md / release prep) remain — post-2.1.0 work.
2026-04-29 23:57:45 +00:00

255 lines
7.7 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,
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,
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.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
}