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
+62 -26
View File
@@ -721,35 +721,71 @@ func main() {
handler.NewAdminSCEPIntuneServiceImpl(scepServices),
),
})
// Register EST (RFC 7030) handlers if enabled
// Register EST (RFC 7030) handlers if enabled.
//
// EST RFC 7030 hardening master bundle Phase 1: multi-profile dispatch.
// Config.Validate() guarantees cfg.EST.Profiles is non-empty when
// cfg.EST.Enabled is true (the legacy single-issuer flat fields are
// merged into Profiles[0] by mergeESTLegacyIntoProfiles in Load()).
// Each profile gets its own service + handler instance, registered at
// /.well-known/est/ (PathID="") or /.well-known/est/<PathID>/.
//
// Per-profile preflight gates (issuer reachable, CA serves cacerts)
// run inside the loop. Failures log the offending PathID so a
// multi-profile deploy can pinpoint which profile broke startup —
// mirrors the SCEP audit-closure pattern (cmd/server/main.go::
// preflightSCEPIntuneTrustAnchor signature took pathID for exactly
// this reason).
if cfg.EST.Enabled {
issuerConn, ok := issuerRegistry.Get(cfg.EST.IssuerID)
if !ok {
logger.Error("EST issuer not found in registry", "issuer_id", cfg.EST.IssuerID)
os.Exit(1)
}
// Bundle-4 / L-005: validate the issuer can actually serve a CA certificate
// at startup, not at first request time. ACME / DigiCert / Sectigo etc.
// return an error from GetCACertPEM because they don't expose a static
// CA chain; binding EST to one of those would silently degrade enrollment.
preflightCtx, preflightCancel := context.WithTimeout(context.Background(), 10*time.Second)
if err := preflightEnrollmentIssuer(preflightCtx, "EST", cfg.EST.IssuerID, issuerConn); err != nil {
estHandlers := make(map[string]handler.ESTHandler, len(cfg.EST.Profiles))
for i, profile := range cfg.EST.Profiles {
profile := profile // shadow for closure-safety
profileLog := logger.With(
"est_profile_index", i,
"est_profile_pathid", profile.PathID,
"est_profile_issuer", profile.IssuerID,
)
issuerConn, ok := issuerRegistry.Get(profile.IssuerID)
if !ok {
profileLog.Error("startup refused: EST profile issuer not found in registry",
"hint", "EST profile must reference a configured issuer ID; check CERTCTL_ISSUERS_ENABLED + the issuer factory")
os.Exit(1)
}
// Bundle-4 / L-005: validate the issuer can actually serve a CA certificate
// at startup, not at first request time. ACME / DigiCert / Sectigo etc.
// return an error from GetCACertPEM because they don't expose a static
// CA chain; binding EST to one of those would silently degrade enrollment.
preflightCtx, preflightCancel := context.WithTimeout(context.Background(), 10*time.Second)
if err := preflightEnrollmentIssuer(preflightCtx, "EST", profile.IssuerID, issuerConn); err != nil {
preflightCancel()
profileLog.Error("startup refused: EST profile issuer cannot serve CA certificate", "error", err)
os.Exit(1)
}
preflightCancel()
logger.Error("startup refused: EST issuer cannot serve CA certificate", "error", err)
os.Exit(1)
estService := service.NewESTService(profile.IssuerID, issuerConn, auditService, profileLog)
estService.SetProfileRepo(profileRepo)
if profile.ProfileID != "" {
estService.SetProfileID(profile.ProfileID)
}
estHandlers[profile.PathID] = handler.NewESTHandler(estService)
endpoint := "/.well-known/est"
if profile.PathID != "" {
endpoint = "/.well-known/est/" + profile.PathID
}
profileLog.Info("EST profile enabled",
"endpoints", endpoint+"/{cacerts,simpleenroll,simplereenroll,csrattrs}",
"server_keygen_enabled", profile.ServerKeygenEnabled,
"mtls_enabled", profile.MTLSEnabled,
"basic_auth_configured", profile.EnrollmentPassword != "",
"allowed_auth_modes", profile.AllowedAuthModes,
"rate_limit_per_principal_24h", profile.RateLimitPerPrincipal24h,
)
}
preflightCancel()
estService := service.NewESTService(cfg.EST.IssuerID, issuerConn, auditService, logger)
estService.SetProfileRepo(profileRepo)
if cfg.EST.ProfileID != "" {
estService.SetProfileID(cfg.EST.ProfileID)
}
estHandler := handler.NewESTHandler(estService)
apiRouter.RegisterESTHandlers(estHandler)
logger.Info("EST server enabled",
"issuer_id", cfg.EST.IssuerID,
"profile_id", cfg.EST.ProfileID,
"endpoints", "/.well-known/est/{cacerts,simpleenroll,simplereenroll,csrattrs}")
apiRouter.RegisterESTHandlers(estHandlers)
logger.Info("EST server enabled", "profile_count", len(cfg.EST.Profiles))
}
// SCEP RFC 8894 Phase 6.5: union pool of every enabled mTLS profile's