feat(est): per-profile dispatch — multi-profile env-var family + back-compat shim

EST RFC 7030 hardening master bundle Phases 0 + 1 of 13. Lays the
foundation for the remaining hardening phases (mTLS auth, HTTP Basic
auth, channel binding, server-keygen, admin observability, GUI, libest
e2e) without changing existing operator behavior — backward-compat
shim preserves the v2.0.66 single-issuer flat env-var setup.

WHAT LANDS:

Phase 0 — Frozen decisions
  9 frozen decisions documented in
  cowork/est-rfc7030-hardening-prompt.md::Phase 0 frozen decisions
  (auth modes mTLS+Basic at GA; RFC 9266 channel binding; multi-profile
  env-var family CERTCTL_EST_PROFILES; mTLS sibling URL
  /.well-known/est-mtls/<pathID>; serverkeygen ships V2; fullcmc
  deferred; renewal device-driven per RFC 7030 §4.2.2; csrattrs
  algorithm allow-list profile-derived; libest as e2e reference).

Phase 1 — Multi-profile config + per-profile dispatch
  internal/config/config.go: extended ESTConfig with Profiles slice;
  added ESTProfileConfig struct with all field contracts (PathID +
  IssuerID + ProfileID + EnrollmentPassword + MTLSEnabled +
  MTLSClientCATrustBundlePath + ChannelBindingRequired +
  AllowedAuthModes + RateLimitPerPrincipal24h + ServerKeygenEnabled).
  Forward-looking fields (mTLS, HTTP Basic, channel binding,
  rate limit, server-keygen) are dormant in Phase 1 — Phase 2-5 wire
  the corresponding handlers; Validate() gates ensure operators can't
  set incoherent combinations (MTLSEnabled=true without bundle path,
  basic auth without password, mtls auth mode without MTLSEnabled,
  ChannelBindingRequired without mTLS, ServerKeygenEnabled without
  ProfileID).

  loadESTProfilesFromEnv: mirrors loadSCEPProfilesFromEnv exactly.
  Reads CERTCTL_EST_PROFILES=corp,iot,wifi and per-profile env vars
  CERTCTL_EST_PROFILE_<NAME>_*. Lowercase PathID, uppercase env-var
  name. parseAuthModes handles comma-separated normalization.

  mergeESTLegacyIntoProfiles: back-compat shim. When CERTCTL_EST_PROFILES
  is unset AND CERTCTL_EST_ENABLED=true, synthesizes a single-element
  Profiles[0] with PathID="" so existing /.well-known/est/
  operators see no behavior change.

  validESTPathID + validESTAuthMode: shape validators. PathID matches
  [a-z0-9-]+ with no leading/trailing hyphen (mirrors validSCEPPathID
  exactly). Auth mode is one of {mtls, basic}.

  Per-profile Validate(): refuses every documented misconfiguration
  with operator-greppable error messages naming the offending profile
  index + PathID + field. Mirrors the SCEP audit-closure pattern.

internal/api/router/router.go: refactored RegisterESTHandlers from
  single-handler to map[string]ESTHandler. Empty PathID maps to legacy
  /.well-known/est/ root (literal-string r.Register calls preserve
  openapi-parity scanner behavior). Non-empty PathIDs dynamic-register
  /.well-known/est/<pathID>/{cacerts,simpleenroll,simplereenroll,csrattrs}.
  Mirrors the SCEP per-profile dispatch from commit fdd424b.

cmd/server/main.go: refactored EST startup block to iterate
  cfg.EST.Profiles. Per-profile preflight (issuer-in-registry,
  preflightEnrollmentIssuer L-005 gate) runs in the loop with
  per-profile structured logging including PathID. Failures log the
  offending PathID so multi-profile deploys can pinpoint which broke
  startup. Mirrors the SCEP per-profile loop from commit fdd424b.

Updated 3 callers of the old single-handler signature:
  - internal/api/router/router_test.go::TestRegisterESTHandlers_AllPaths
  - internal/integration/lifecycle_test.go::setupTestServer
  - internal/integration/negative_test.go::setupTestServer
  Each wraps the existing single ESTHandler in a single-element
  map[string]handler.ESTHandler{"": estHandler} preserving exact
  legacy behavior.

NEW TESTS:

internal/config/config_est_profiles_test.go (12 tests):
  - LegacyFlatFields_SynthesizeSingleProfile (back-compat shim)
  - DisabledNoLegacyShim
  - MultipleProfiles_LoadFromEnv (3 profiles: corp+mtls+basic+keygen,
    iot+basic, wifi+mtls; verifies every field round-trips)
  - StructuredFormBeatsLegacy
  - PathIDValidation (12 sub-cases: empty/valid/leading-hyphen/
    trailing-hyphen/uppercase/slash/dot/underscore/space/percent)
  - DuplicatePathID_Refuses
  - MissingPerProfileIssuerID
  - MTLSEnabledRequiresBundlePath
  - ChannelBindingWithoutMTLS_Refuses (cross-check)
  - BasicAuthInModesRequiresPassword (cross-check)
  - MTLSAuthModeRequiresMTLSEnabled (cross-check)
  - UnknownAuthModeRefused
  - NegativeRateLimitRefused
  - ServerKeygenRequiresProfileID
  - DisabledIgnoresProfiles
  - ParseAuthModes_Normalization (8 sub-cases)

internal/api/router/router_est_profiles_test.go (4 tests):
  - LegacyEmptyPathIDMapsToRoot
  - NonEmptyPathIDMapsToSubpath
  - MultipleProfilesNoCrossBleed (the load-bearing dispatch invariant —
    each profile's PathID routes to its OWN handler instance,
    proven via per-profile-tagged mock responses with base64 prefix
    matching)
  - EmptyMapRegistersNoRoutes

VERIFICATION (sandbox, Go 1.25.9):
  gofmt -l                — clean for all changed files
  staticcheck             — clean for config + router + handler +
                            integration + cmd/server packages
  go vet                  — clean for the same packages
  go test -short -count=1 — green for config, router, handler,
                            service, integration, cmd/server

NEXT (Phase 2): mTLS client cert auth + TrustAnchorHolder + RFC 9266
tls-exporter channel binding. Phase 1's Validate gates already refuse
the incoherent configurations Phase 2 must defend against; Phase 2
adds the actual TLS-listener wiring + handler-side cert validation +
channel-binding extraction.

Spec preserved at cowork/est-rfc7030-hardening-prompt.md.
This commit is contained in:
shankar0123
2026-04-29 22:17:52 +00:00
parent 530593507b
commit a808948397
8 changed files with 1270 additions and 75 deletions
+65 -18
View File
@@ -376,26 +376,73 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
r.Register("POST /api/v1/health-checks/{id}/acknowledge", http.HandlerFunc(reg.HealthChecks.AcknowledgeHealthCheck))
}
// RegisterESTHandlers sets up EST (RFC 7030) routes under /.well-known/est/.
// RegisterESTHandlers sets up EST (RFC 7030) routes under
// /.well-known/est/[<pathID>/].
//
// EST endpoints are intentionally unauthenticated at the HTTP layer. Per RFC 7030
// §3.2.3, authentication and authorization for enrollment are deployment-specific;
// certctl relies on CSR signature verification, profile policy enforcement (allowed
// key types, max TTL, permitted EKUs), and the underlying issuer connector's own
// policy. Per RFC 7030 §4.1.1, /.well-known/est/cacerts is explicitly anonymous.
// EST RFC 7030 hardening master bundle Phase 1: this signature was originally
// `RegisterESTHandlers(est handler.ESTHandler)` — a single handler installed
// at the legacy /.well-known/est/ root. The per-profile dispatch refactor
// takes a map keyed by ESTProfileConfig.PathID. Empty PathID maps to the
// legacy /.well-known/est/ root for backward compatibility (existing
// operators with the flat single-issuer config see no URL change);
// non-empty PathID values map to /.well-known/est/<pathID>/. Validate()
// guards PathID uniqueness + slug-shape so this loop never gets a
// collision or an invalid path segment.
//
// cmd/server/main.go's finalHandler dispatches /.well-known/est/* to a dedicated
// no-auth middleware chain (RequestID, structuredLogger, Recovery only) so EST
// clients — IoT devices, 802.1X supplicants, MDM-enrolled laptops — never hit the
// Bearer-token auth middleware they cannot satisfy. See M-001 audit 2026-04-19
// (option D): prior builds routed EST through the authenticated apiHandler chain,
// which reduced every enrollment to a 401 before the handler was reached.
func (r *Router) RegisterESTHandlers(est handler.ESTHandler) {
// EST endpoints per RFC 7030 Section 3.2.2
r.Register("GET /.well-known/est/cacerts", http.HandlerFunc(est.CACerts))
r.Register("POST /.well-known/est/simpleenroll", http.HandlerFunc(est.SimpleEnroll))
r.Register("POST /.well-known/est/simplereenroll", http.HandlerFunc(est.SimpleReEnroll))
r.Register("GET /.well-known/est/csrattrs", http.HandlerFunc(est.CSRAttrs))
// EST endpoints are intentionally unauthenticated at the HTTP middleware
// layer. Per RFC 7030 §3.2.3, authentication and authorization for
// enrollment are deployment-specific; pre-Phase-2 certctl relies on CSR
// signature verification, profile policy enforcement (allowed key types,
// max TTL, permitted EKUs), and the underlying issuer connector's own
// policy. Per RFC 7030 §4.1.1, /.well-known/est/<pathID>/cacerts is
// explicitly anonymous. Phase 2 + 3 of the EST hardening bundle add
// per-profile mTLS + HTTP Basic auth at the HANDLER layer (not the
// middleware layer) so the existing no-auth dispatch in
// cmd/server/main.go's finalHandler stays correct — auth is per-profile,
// not per-prefix.
//
// cmd/server/main.go's finalHandler dispatches /.well-known/est/* to a
// dedicated no-auth middleware chain (RequestID, structuredLogger,
// Recovery only) so EST clients — IoT devices, 802.1X supplicants,
// MDM-enrolled laptops — never hit the Bearer-token auth middleware they
// cannot satisfy. See M-001 audit 2026-04-19 (option D): prior builds
// routed EST through the authenticated apiHandler chain, which reduced
// every enrollment to a 401 before the handler was reached.
func (r *Router) RegisterESTHandlers(handlers map[string]handler.ESTHandler) {
// Legacy /.well-known/est/ route for the empty-PathID profile is
// registered with literal strings so the openapi-parity scanner
// (Bundle D / Audit M-027, see openapi_parity_test.go) sees the four
// EST operations as AST literals exactly the way it did pre-Phase-1.
// The scanner walks for *ast.BasicLit string args to r.Register, so
// dynamically-built paths would not appear in its index. Keeping the
// empty-PathID case static preserves the spec parity contract for the
// documented /.well-known/est/ endpoints that openapi.yaml describes.
if h, ok := handlers[""]; ok {
r.Register("GET /.well-known/est/cacerts", http.HandlerFunc(h.CACerts))
r.Register("POST /.well-known/est/simpleenroll", http.HandlerFunc(h.SimpleEnroll))
r.Register("POST /.well-known/est/simplereenroll", http.HandlerFunc(h.SimpleReEnroll))
r.Register("GET /.well-known/est/csrattrs", http.HandlerFunc(h.CSRAttrs))
}
// Multi-profile routes register dynamically. These per-deployment
// paths (/.well-known/est/<pathID>/) aren't in openapi.yaml because
// the path segment is operator-defined; the spec covers the canonical
// /.well-known/est/ root only. The parity scanner correctly skips
// dynamic routes (it only checks literals). Mirrors the SCEP dispatch
// pattern at RegisterSCEPHandlers above (commit 6d30493).
for pathID, h := range handlers {
if pathID == "" {
continue // already handled by the static block above
}
hCopy := h // h is captured by value — ESTHandler is a small
// struct (one interface field) so the per-iteration copy is
// cheap and avoids any loop-variable-capture surprise if
// ESTHandler ever grows pointer receivers in the future.
prefix := "/.well-known/est/" + pathID
r.Register("GET "+prefix+"/cacerts", http.HandlerFunc(hCopy.CACerts))
r.Register("POST "+prefix+"/simpleenroll", http.HandlerFunc(hCopy.SimpleEnroll))
r.Register("POST "+prefix+"/simplereenroll", http.HandlerFunc(hCopy.SimpleReEnroll))
r.Register("GET "+prefix+"/csrattrs", http.HandlerFunc(hCopy.CSRAttrs))
}
}
// RegisterSCEPHandlers sets up SCEP (RFC 8894) routes.
@@ -0,0 +1,188 @@
package router
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/shankar0123/certctl/internal/api/handler"
"github.com/shankar0123/certctl/internal/domain"
)
// EST RFC 7030 hardening master bundle Phase 1: per-profile EST router
// registration. Pins:
//
// 1. Empty PathID maps to /.well-known/est/ (legacy backward-compat).
// 2. Non-empty PathID maps to /.well-known/est/<pathID>/.
// 3. Multi-profile registration produces 4N routes (cacerts + simpleenroll
// + simplereenroll + csrattrs per profile).
// 4. Each registered route reaches the right handler instance — no
// cross-profile bleed-through (proven by the per-profile mock
// GetCACerts response carrying the profile tag).
//
// The mock service is a minimal ESTService implementation that records
// which profile served the request via the GetCACerts response — the test
// asserts it sees the right per-profile string echoed back, which would
// only happen if the right handler was wired to the right path.
// estProfileMockService is a per-profile-tagged mock ESTService for
// router-level tests. The CA cert PEM string carries the profile tag so
// the caller can verify which profile's handler served a given request.
type estProfileMockService struct {
tag string
}
func (s *estProfileMockService) GetCACerts(_ context.Context) (string, error) {
// Return a syntactically-valid PEM that embeds the profile tag in the
// cert body. The handler converts this PEM to PKCS#7 via PEMToDERChain
// — for the cross-bleed test we only need to confirm the right service
// was reached. Use a minimal PEM that won't parse as a real cert (the
// test asserts on the error path, which still routes through the right
// service mock).
return "-----BEGIN CERTIFICATE-----\nPROFILE=" + s.tag + "\n-----END CERTIFICATE-----\n", nil
}
func (s *estProfileMockService) SimpleEnroll(_ context.Context, _ string) (*domain.ESTEnrollResult, error) {
return &domain.ESTEnrollResult{CertPEM: "-----BEGIN CERTIFICATE-----\nPROFILE=" + s.tag + "\n-----END CERTIFICATE-----\n"}, nil
}
func (s *estProfileMockService) SimpleReEnroll(_ context.Context, _ string) (*domain.ESTEnrollResult, error) {
return &domain.ESTEnrollResult{CertPEM: "-----BEGIN CERTIFICATE-----\nPROFILE=" + s.tag + "\n-----END CERTIFICATE-----\n"}, nil
}
func (s *estProfileMockService) GetCSRAttrs(_ context.Context) ([]byte, error) {
// Return non-empty bytes so the handler returns 200 + the body. The body
// won't carry a profile tag (csrattrs is base64-encoded ASN.1; sticking
// a literal in here would not survive the encoding round-trip), but the
// 200 vs 204 status itself is enough to prove the right service was
// reached — the legacy mock returns 204 (nil bytes), this mock returns
// 200, and a wrong-handler bleed would produce the wrong status.
return []byte("PROFILE=" + s.tag), nil
}
func TestRouter_RegisterESTHandlers_LegacyEmptyPathIDMapsToRoot(t *testing.T) {
r := New()
svc := &estProfileMockService{tag: "legacy"}
r.RegisterESTHandlers(map[string]handler.ESTHandler{
"": handler.NewESTHandler(svc),
})
// /.well-known/est/cacerts is a GET. The handler will fail at the
// PEM-to-DER step because our mock returns a malformed PEM, but the
// service WAS reached (the 500 we get back is from the handler's
// pkcs7 conversion, not from a routing error). Use csrattrs instead
// — it's GET and our mock returns clean bytes.
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/csrattrs", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("GET /.well-known/est/csrattrs — code %d, want 200 (legacy root should be registered; body=%q)", w.Code, w.Body.String())
}
}
func TestRouter_RegisterESTHandlers_NonEmptyPathIDMapsToSubpath(t *testing.T) {
r := New()
r.RegisterESTHandlers(map[string]handler.ESTHandler{
"corp": handler.NewESTHandler(&estProfileMockService{tag: "corp"}),
})
// /.well-known/est/corp/csrattrs should reach the corp handler.
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/corp/csrattrs", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("GET /.well-known/est/corp/csrattrs — code %d, want 200 (per-profile route should be registered; body=%q)", w.Code, w.Body.String())
}
// /.well-known/est/ root must NOT be registered when only non-empty PathIDs exist.
req = httptest.NewRequest(http.MethodGet, "/.well-known/est/csrattrs", nil)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound && w.Code != http.StatusMethodNotAllowed {
t.Errorf("/.well-known/est/csrattrs without legacy profile — code %d, want 404 or 405 (no handler should be registered)", w.Code)
}
}
// TestRouter_RegisterESTHandlers_MultipleProfilesNoCrossBleed pins the
// load-bearing dispatch invariant: each profile's PathID routes to its OWN
// handler instance. A regression that mis-wired the dispatch would surface
// as profile A's traffic hitting profile B's mock, observable here because
// each mock embeds its tag in the response.
func TestRouter_RegisterESTHandlers_MultipleProfilesNoCrossBleed(t *testing.T) {
r := New()
r.RegisterESTHandlers(map[string]handler.ESTHandler{
"": handler.NewESTHandler(&estProfileMockService{tag: "default"}),
"corp": handler.NewESTHandler(&estProfileMockService{tag: "corp"}),
"iot": handler.NewESTHandler(&estProfileMockService{tag: "iot"}),
})
cases := []struct {
path string
wantTag string
}{
{"/.well-known/est/csrattrs", "default"},
{"/.well-known/est/corp/csrattrs", "corp"},
{"/.well-known/est/iot/csrattrs", "iot"},
}
for _, tc := range cases {
t.Run(tc.path, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, tc.path, nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("code %d, want 200 (body=%q)", w.Code, w.Body.String())
}
// The handler base64-encodes csrattrs bytes; decode our literal
// to confirm the right profile's mock was hit.
body := w.Body.String()
// PROFILE=<tag> is emitted by the mock; the handler base64-
// encodes the bytes in the body. Two checks: status was 200
// (above) AND the base64-decoded body would carry the tag.
// We don't decode here — the SCEP equivalent uses substring
// match against the raw body too; for EST the raw body IS
// base64 of "PROFILE=<tag>". Decode-and-match is the
// same verification operation; substring against the raw
// base64 works because each profile's tag has a unique
// base64 prefix.
if !contains(body, base64Tag(tc.wantTag)) {
t.Errorf("body = %q, want base64-encoded PROFILE=%s prefix", body, tc.wantTag)
}
})
}
}
func TestRouter_RegisterESTHandlers_EmptyMapRegistersNoRoutes(t *testing.T) {
r := New()
r.RegisterESTHandlers(map[string]handler.ESTHandler{})
req := httptest.NewRequest(http.MethodGet, "/.well-known/est/csrattrs", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound && w.Code != http.StatusMethodNotAllowed {
t.Errorf("/.well-known/est/csrattrs with no profiles registered — code %d, want 404 or 405", w.Code)
}
}
// base64Tag returns the base64-encoded form of "PROFILE=<tag>" — used by
// the cross-bleed test to verify the mock's response made it through the
// handler's base64 encoding step. Local helper to avoid importing
// encoding/base64 just for this; the encoding is tiny and stable.
func base64Tag(tag string) string {
// stdlib produces "UFJPRklMRT0=" for "PROFILE=" — but each tag
// changes the suffix, so we match on the stable prefix only.
// "PROFILE=" → standard base64 "UFJPRklMRT0=" (when alone).
// "PROFILE=corp" → "UFJPRklMRT1jb3Jw"
// "PROFILE=iot" → "UFJPRklMRT1pb3Q="
// "PROFILE=default" → "UFJPRklMRT1kZWZhdWx0"
// All share the prefix "UFJPRklMRT" (= base64 of "PROFILE"). The tag
// suffix differs, which is what cross-bleed would change.
switch tag {
case "default":
return "UFJPRklMRT1kZWZhdWx0"
case "corp":
return "UFJPRklMRT1jb3Jw"
case "iot":
return "UFJPRklMRT1pb3Q"
}
return "UFJPRklMRT" // safe fallback prefix
}
+5 -1
View File
@@ -304,8 +304,12 @@ func TestRegisterESTHandlers_AllPaths(t *testing.T) {
})
}
// EST RFC 7030 hardening Phase 1: RegisterESTHandlers signature
// changed from `(handler.ESTHandler)` to `(map[string]handler.ESTHandler)`.
// The empty-PathID key preserves the legacy /.well-known/est/ root
// routes this test asserts.
est := handler.ESTHandler{}
r.RegisterESTHandlers(est)
r.RegisterESTHandlers(map[string]handler.ESTHandler{"": est})
testHandler := recoverMW(r)