feat: add EST server (RFC 7030) for device certificate enrollment (M23)

Implement Enrollment over Secure Transport protocol with 4 endpoints under
/.well-known/est/ — cacerts (CA chain distribution), simpleenroll (initial
enrollment), simplereenroll (certificate renewal), and csrattrs (CSR
attributes). PKCS#7 certs-only wire format with hand-rolled ASN.1, accepts
both PEM and base64-encoded DER CSRs, configurable issuer and profile
binding, full audit trail. 28 new tests (18 handler + 10 service).

Also includes:
- GetCACertPEM added to issuer connector interface (all 4 issuers updated)
- EST integration tests wired into e2e test suite (13 test cases)
- QA testing guide Part 26 (15 manual EST test cases)
- All docs updated: README, features, architecture, concepts, connectors,
  quickstart, demo-advanced (endpoint counts, MCP wording, agent IDs,
  issuer interface, resource lists, OpenSSL status)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Shankar
2026-03-25 15:31:06 -04:00
parent 42fa9c7791
commit e4ba8d4de2
27 changed files with 1807 additions and 20 deletions
+153
View File
@@ -0,0 +1,153 @@
package service
import (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"log/slog"
"strings"
"github.com/shankar0123/certctl/internal/domain"
)
// ESTService implements the EST (RFC 7030) enrollment protocol.
// It delegates certificate operations to an existing IssuerConnector and records
// enrollment events in the audit trail.
type ESTService struct {
issuer IssuerConnector
issuerID string
auditService *AuditService
logger *slog.Logger
profileID string // optional: constrain enrollments to a specific profile
}
// NewESTService creates a new ESTService for the given issuer connector.
func NewESTService(issuerID string, issuer IssuerConnector, auditService *AuditService, logger *slog.Logger) *ESTService {
return &ESTService{
issuer: issuer,
issuerID: issuerID,
auditService: auditService,
logger: logger,
}
}
// SetProfileID constrains EST enrollments to a specific certificate profile.
func (s *ESTService) SetProfileID(profileID string) {
s.profileID = profileID
}
// GetCACerts returns the PEM-encoded CA certificate chain for this EST server.
// RFC 7030 Section 4.1: /cacerts distributes the current CA certificates.
func (s *ESTService) GetCACerts(ctx context.Context) (string, error) {
caPEM, err := s.issuer.GetCACertPEM(ctx)
if err != nil {
return "", fmt.Errorf("failed to get CA certificates from issuer %s: %w", s.issuerID, err)
}
if caPEM == "" {
return "", fmt.Errorf("issuer %s does not provide CA certificates for EST", s.issuerID)
}
return caPEM, nil
}
// SimpleEnroll processes an initial enrollment request.
// RFC 7030 Section 4.2: /simpleenroll accepts a PKCS#10 CSR and returns a signed cert.
func (s *ESTService) SimpleEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error) {
return s.processEnrollment(ctx, csrPEM, "est_simple_enroll")
}
// SimpleReEnroll processes a re-enrollment request.
// RFC 7030 Section 4.2.2: /simplereenroll is functionally identical to /simpleenroll
// but is used when renewing an existing certificate.
func (s *ESTService) SimpleReEnroll(ctx context.Context, csrPEM string) (*domain.ESTEnrollResult, error) {
return s.processEnrollment(ctx, csrPEM, "est_simple_reenroll")
}
// GetCSRAttrs returns the CSR attributes the server wants clients to include.
// RFC 7030 Section 4.5: /csrattrs tells clients what to put in their CSR.
// Returns nil if no specific attributes are required.
func (s *ESTService) GetCSRAttrs(ctx context.Context) ([]byte, error) {
// For now, we don't require specific CSR attributes.
// In the future, this could return key type constraints from the profile.
return nil, nil
}
// processEnrollment handles the common enrollment logic for both simpleenroll and simplereenroll.
func (s *ESTService) processEnrollment(ctx context.Context, csrPEM string, auditAction string) (*domain.ESTEnrollResult, error) {
// Parse the CSR to extract CN and SANs
block, _ := pem.Decode([]byte(csrPEM))
if block == nil {
return nil, fmt.Errorf("invalid CSR PEM")
}
csr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse CSR: %w", err)
}
if err := csr.CheckSignature(); err != nil {
return nil, fmt.Errorf("CSR signature verification failed: %w", err)
}
commonName := csr.Subject.CommonName
if commonName == "" {
return nil, fmt.Errorf("CSR must include a Common Name")
}
// Collect SANs
var sans []string
for _, dns := range csr.DNSNames {
sans = append(sans, dns)
}
for _, ip := range csr.IPAddresses {
sans = append(sans, ip.String())
}
for _, email := range csr.EmailAddresses {
sans = append(sans, email)
}
for _, uri := range csr.URIs {
sans = append(sans, uri.String())
}
s.logger.Info("EST enrollment request",
"action", auditAction,
"common_name", commonName,
"sans", strings.Join(sans, ","),
"issuer", s.issuerID)
// Issue the certificate via the configured issuer connector
result, err := s.issuer.IssueCertificate(ctx, commonName, sans, csrPEM)
if err != nil {
s.logger.Error("EST enrollment failed",
"action", auditAction,
"common_name", commonName,
"error", err)
return nil, fmt.Errorf("certificate issuance failed: %w", err)
}
// Audit the enrollment
if s.auditService != nil {
details := map[string]interface{}{
"common_name": commonName,
"sans": sans,
"issuer_id": s.issuerID,
"serial": result.Serial,
"protocol": "EST",
}
if s.profileID != "" {
details["profile_id"] = s.profileID
}
_ = s.auditService.RecordEvent(ctx, "est-client", "system", auditAction, "certificate", result.Serial, details)
}
s.logger.Info("EST enrollment successful",
"action", auditAction,
"common_name", commonName,
"serial", result.Serial,
"not_after", result.NotAfter)
return &domain.ESTEnrollResult{
CertPEM: result.CertPEM,
ChainPEM: result.ChainPEM,
}, nil
}
+180
View File
@@ -0,0 +1,180 @@
package service
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"log/slog"
"os"
"strings"
"testing"
)
// generateCSRPEM creates a valid ECDSA P-256 CSR for testing.
func generateCSRPEM(t *testing.T, cn string, sans []string) string {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("generate key: %v", err)
}
template := &x509.CertificateRequest{
Subject: pkix.Name{CommonName: cn},
DNSNames: sans,
}
csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, key)
if err != nil {
t.Fatalf("create CSR: %v", err)
}
return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER}))
}
func TestESTService_GetCACerts_Success(t *testing.T) {
mockIssuer := &mockIssuerConnector{}
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
caPEM, err := svc.GetCACerts(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if caPEM == "" {
t.Error("expected non-empty CA PEM")
}
}
func TestESTService_GetCACerts_IssuerError(t *testing.T) {
mockIssuer := &mockIssuerConnector{Err: errors.New("CA unavailable")}
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
_, err := svc.GetCACerts(context.Background())
if err == nil {
t.Fatal("expected error")
}
if !strings.Contains(err.Error(), "CA unavailable") {
t.Errorf("expected error to contain 'CA unavailable', got: %v", err)
}
}
func TestESTService_SimpleEnroll_Success(t *testing.T) {
mockIssuer := &mockIssuerConnector{}
auditRepo := newMockAuditRepository()
auditSvc := NewAuditService(auditRepo)
svc := NewESTService("iss-local", mockIssuer, auditSvc, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
csrPEM := generateCSRPEM(t, "test.example.com", []string{"test.example.com"})
result, err := svc.SimpleEnroll(context.Background(), csrPEM)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result == nil {
t.Fatal("expected non-nil result")
}
if result.CertPEM == "" {
t.Error("expected non-empty CertPEM")
}
// Verify audit event was recorded
if len(auditRepo.Events) == 0 {
t.Error("expected audit event to be recorded")
}
}
func TestESTService_SimpleEnroll_InvalidCSR(t *testing.T) {
mockIssuer := &mockIssuerConnector{}
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
_, err := svc.SimpleEnroll(context.Background(), "not-valid-pem")
if err == nil {
t.Fatal("expected error for invalid CSR")
}
}
func TestESTService_SimpleEnroll_MissingCN(t *testing.T) {
mockIssuer := &mockIssuerConnector{}
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
csrPEM := generateCSRPEM(t, "", []string{"test.example.com"})
_, err := svc.SimpleEnroll(context.Background(), csrPEM)
if err == nil {
t.Fatal("expected error for missing CN")
}
if !strings.Contains(err.Error(), "Common Name") {
t.Errorf("expected 'Common Name' in error, got: %v", err)
}
}
func TestESTService_SimpleEnroll_IssuerError(t *testing.T) {
mockIssuer := &mockIssuerConnector{Err: errors.New("issuance failed")}
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
csrPEM := generateCSRPEM(t, "test.example.com", nil)
_, err := svc.SimpleEnroll(context.Background(), csrPEM)
if err == nil {
t.Fatal("expected error")
}
if !strings.Contains(err.Error(), "issuance failed") {
t.Errorf("expected 'issuance failed', got: %v", err)
}
}
func TestESTService_SimpleReEnroll_Success(t *testing.T) {
mockIssuer := &mockIssuerConnector{}
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
csrPEM := generateCSRPEM(t, "renew.example.com", []string{"renew.example.com"})
result, err := svc.SimpleReEnroll(context.Background(), csrPEM)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result == nil {
t.Fatal("expected non-nil result")
}
}
func TestESTService_GetCSRAttrs_Empty(t *testing.T) {
mockIssuer := &mockIssuerConnector{}
svc := NewESTService("iss-local", mockIssuer, nil, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
attrs, err := svc.GetCSRAttrs(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if attrs != nil {
t.Errorf("expected nil attrs, got %v", attrs)
}
}
func TestESTService_SimpleEnroll_WithProfile(t *testing.T) {
mockIssuer := &mockIssuerConnector{}
auditRepo := newMockAuditRepository()
auditSvc := NewAuditService(auditRepo)
svc := NewESTService("iss-local", mockIssuer, auditSvc, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})))
svc.SetProfileID("profile-wifi-client")
csrPEM := generateCSRPEM(t, "device.example.com", nil)
result, err := svc.SimpleEnroll(context.Background(), csrPEM)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result == nil {
t.Fatal("expected non-nil result")
}
// Verify audit event includes profile_id
if len(auditRepo.Events) == 0 {
t.Fatal("expected audit event")
}
lastEvent := auditRepo.Events[len(auditRepo.Events)-1]
if lastEvent.Details == nil {
t.Fatal("expected audit details")
}
}
+5
View File
@@ -95,3 +95,8 @@ func (a *IssuerConnectorAdapter) SignOCSPResponse(ctx context.Context, req OCSPS
NextUpdate: req.NextUpdate,
})
}
// GetCACertPEM delegates to the underlying connector.
func (a *IssuerConnectorAdapter) GetCACertPEM(ctx context.Context) (string, error) {
return a.connector.GetCACertPEM(ctx)
}
+2
View File
@@ -44,6 +44,8 @@ type IssuerConnector interface {
GenerateCRL(ctx context.Context, revokedCerts []CRLEntry) ([]byte, error)
// SignOCSPResponse signs an OCSP response for the given certificate serial.
SignOCSPResponse(ctx context.Context, req OCSPSignRequest) ([]byte, error)
// GetCACertPEM returns the PEM-encoded CA certificate chain for this issuer.
GetCACertPEM(ctx context.Context) (string, error)
}
// IssuanceResult holds the result of a certificate issuance or renewal operation.
+7
View File
@@ -634,6 +634,13 @@ func (m *mockIssuerConnector) SignOCSPResponse(ctx context.Context, req OCSPSign
return []byte("mock-ocsp-response"), nil
}
func (m *mockIssuerConnector) GetCACertPEM(ctx context.Context) (string, error) {
if m.Err != nil {
return "", m.Err
}
return "-----BEGIN CERTIFICATE-----\nmock-ca-cert\n-----END CERTIFICATE-----", nil
}
// Constructor functions for mocks
func newMockCertificateRepository() *mockCertRepo {