2 Commits

Author SHA1 Message Date
shankar0123 5ea45a19b9 feat(security): Sprint 5 ACQ — RED-003 deny-empty flip + SEC-009/RED-005 RFC1918 opt-in
Acquisition-audit Sprint 5 ACQ closure (2026-05-16). Two
independent findings ship together because they share Load() /
main.go wiring; the closure comments tie each line to its finding.

PART A — RED-003 (agent-bootstrap deny-empty cutover)
=====================================================

Phase 2 SEC-H1 closure (2026-05-13) introduced the
CERTCTL_AGENT_BOOTSTRAP_TOKEN_DENY_EMPTY staged feature flag with
default `false` so v2.1.x operators wouldn't get a surprise
fail-closed on upgrade. This commit flips the default to `true`
(per the staged plan in the existing CHANGELOG "Breaking changes
(scheduled for v2.2.0)" block). Operators who haven't generated a
real bootstrap token yet keep the v2.1.x warn-mode pass-through
for one upgrade window by setting
CERTCTL_AGENT_BOOTSTRAP_TOKEN_DENY_EMPTY=false explicitly.

Demo-mode escape hatch: CERTCTL_DEMO_MODE_ACK=true skips the
fail-closed gate so the screenshot/demo path stays one-command-up.
The accompanying boot-banner WARN at cmd/server/main.go:124-126
keeps demo mode visible in every log scraper, so this override
cannot silently re-enable warn-mode in production.

internal/config/config.go
  - Load() default for AgentBootstrapTokenDenyEmpty flipped to true
  - Validate() gate now also checks !c.Auth.DemoModeAck so the demo
    override line up with the boot-banner WARN
  - Closure comment block updated to cross-reference Sprint 5 ACQ
    and the CHANGELOG v2.2.0 entry

cmd/server/main.go
  - Updated boot-time WARN message to reflect the new default
    (deny-empty=true) — the warn now fires only in the two
    explicit override scenarios (warn-mode opt-back or demo mode),
    and explains the operator action either way
  - Info-line on configured-token path unchanged

PART B — SEC-009 + RED-005 (opt-in RFC1918 outbound block)
==========================================================

internal/validation/ssrf.go::IsReservedIP has always intentionally
left RFC 1918 ranges (10/8, 172.16/12, 192.168/16) NOT-reserved
because certctl is designed to manage certificates inside private
networks. For operators on hosted IaaS where RFC1918 IS internal
trust (kubeadm-default 10.96.0.0/12 service CIDR exposes the
Kubernetes API on 10.96.0.1; cloud-provider internal monitoring;
hosted-bastion subnets), this default is a real exposure path.

Add a package-level atomic.Bool toggle in internal/validation/ssrf.go
that, when on, extends IsReservedIP to ALSO return true for the
three RFC1918 ranges. Every IsReservedIP-derived path
(SafeHTTPDialContext, ValidateSafeURL, the network scanner, the
webhook + OIDC + ACME callers) picks up the new policy
transitively without per-call-site changes.

internal/validation/ssrf.go
  - blockRFC1918Outbound atomic.Bool + SetBlockRFC1918Outbound /
    BlockRFC1918OutboundEnabled accessor pair
  - rfc1918Nets pre-parsed at package init (panic on parse failure
    surfaces a misconfigured ssrf package immediately, not via a
    silently disabled toggle)
  - IsReservedIP checks the toggle after the existing reserved-IP
    checks
  - Header comment rewritten to document the toggle + the
    transitive coverage

internal/config/config.go
  - New NetworkConfig sub-config; Config gains a Network field
  - Load() reads CERTCTL_BLOCK_RFC1918_OUTBOUND env var (default
    false; preserves the existing self-hosted threat model)
  - NetworkConfig docstring lists the operator-trap (enabling this
    also blocks RFC1918 from the network scanner) so an operator
    cert-discovering their own RFC1918 space doesn't get a
    silently-empty scan result

cmd/server/main.go
  - Wires validation.SetBlockRFC1918Outbound after config.Load and
    near the demo-mode banner / agent-bootstrap-token block; emits
    a one-shot INFO line when the toggle is enabled so the policy
    is visible in journals

Tests
=====

internal/config/config_test.go
  - TestLoad_AgentBootstrapTokenDenyEmpty_DefaultIsTrue — pins the
    default flip at the boot path (Load returns the flipped value)
  - TestValidate_DenyEmptyDefault_RefusesWithoutToken — pins the
    fail-closed behavior under the new default
  - TestValidate_DenyEmptyExplicitFalse_AllowsEmpty — pins the
    v2.1.x back-compat escape hatch
  - TestValidate_DenyEmpty_DemoModeAckOverride_AllowsEmpty — pins
    the demo-mode override

internal/validation/ssrf_test.go
  - TestIsReservedIP_RFC1918_OptIn — pins toggle-off / toggle-on
    behavior across all three RFC1918 ranges, edge cases
    immediately outside the ranges, and the toggle-back-off path
  - TestSafeHTTPDialContext_RFC1918_OptIn — pins that the toggle
    reaches the dial-time SSRF check transitively (not just
    IsReservedIP in isolation)

Test-helper updates (Sprint-5-induced churn):
  - internal/config/config_test.go::setMinimalValidEnv now sets
    CERTCTL_AGENT_BOOTSTRAP_TOKEN to a placeholder so Load()-based
    tests that don't specifically exercise the empty-token gate
    keep passing under the new fail-closed default. Tests that DO
    exercise the empty-token path explicitly override back to "".
  - internal/config/config_est_profiles_test.go +
    internal/config/config_scep_profiles_test.go: same placeholder
    fix for the four Load()-based EST/SCEP profile tests.
  - cmd/server/main_test.go::TestMain_ServerConfigFromEnvironment +
    TestMain_AuthTypeConfiguration: same fix at the main.go test
    layer with prior-value restore.

Verified locally: gofmt -l clean; go vet clean; staticcheck clean
across internal/config, internal/validation, cmd/server; short
tests green on all three packages; targeted -v run of all six new
test names confirms PASS.
2026-05-16 19:13:52 +00:00
shankar0123 a808948397 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.
2026-04-29 22:17:52 +00:00