mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 13:51:36 +00:00
9c1d446e40
The pre-G-1 config validator accepted CERTCTL_AUTH_TYPE=jwt and the
startup log faithfully echoed 'authentication enabled type=jwt'.
Reasonable people read that and concluded JWT auth was on. It wasn't.
The auth-middleware wiring at cmd/server/main.go unconditionally routed
every request through the api-key bearer middleware regardless of
cfg.Auth.Type. So CERTCTL_AUTH_TYPE=jwt quietly compared the incoming
'Authorization: Bearer <token>' against whatever string the operator put
in CERTCTL_AUTH_SECRET — real JWT clients got 401, and operators who
treated CERTCTL_AUTH_SECRET as a *signing* secret (because they thought
they were configuring JWT) had effectively handed an attacker an api-key.
A security finding masquerading as a config option.
We chose the audit-recommended structural fix: remove the option, fail
fast at startup, and add the gateway-fronting pattern as the documented
forward path. Implementing JWT middleware would have meant jwks vs
static-secret rotation, claim mapping, expiry enforcement, audience and
issuer validation, key rollover semantics, and regression coverage at the
same depth as the existing api-key path — a feature, not a fix. Operators
who genuinely need JWT/OIDC front certctl with an authenticating gateway
(oauth2-proxy / Envoy ext_authz / Traefik ForwardAuth / Pomerium /
Authelia) and run the upstream certctl with CERTCTL_AUTH_TYPE=none. Same
shape works on docker-compose and Helm.
The change is comprehensive across 7 phases — every surface that
mentioned 'jwt' as a certctl-auth-type is updated, plus structural
backstops (typed enum, runtime guard, helm template validation, CI grep
guard) so the lie can't reappear.
Files changed:
Phase 1 — production code (typed enum + jwt removal):
- internal/config/config.go: AuthType typed alias + AuthTypeAPIKey /
AuthTypeNone constants + ValidAuthTypes() helper. Validate() routes
literal 'jwt' through a dedicated multi-line diagnostic naming the
authenticating-gateway pattern, then cross-checks against
ValidAuthTypes(). Secret-required branch simplified to api-key-only.
Field comment on AuthConfig.Type rewritten to drop jwt and point at
the gateway pattern.
- internal/api/middleware/middleware.go: AuthConfig.Type field comment
references the typed config.AuthType constants.
- internal/api/handler/health.go: same treatment for HealthHandler.AuthType.
- cmd/server/main.go: defense-in-depth runtime switch immediately after
config.Load() — exits 1 on any unsupported auth-type that bypassed the
validator. Auth-disabled startup log explicitly names the
authenticating-gateway pattern.
Phase 2 — tests (Red→Green, contract pinning):
- internal/config/config_test.go: TestValidate_JWTAuth_RejectedDedicated
(two table rows pinning the dedicated G-1 error fires regardless of
whether Secret is set), TestValidAuthTypesDoesNotContainJWT (property
guard against future re-introduction),
TestValidAuthTypesIsExactly_APIKey_None (allowed-set contract),
TestValidate_GenericInvalidAuthType (pins non-jwt invalid values still
hit the generic invalid-auth-type error). Removed the prior
TestValidate_JWTAuth_MissingSecret happy-path since its premise is
inverted post-G-1.
- internal/api/handler/health_test.go: removed
TestAuthInfo_ReturnsAuthType_JWT (which baked the silent-downgrade lie
into the regression suite). Pre-existing _APIKey test continues to
cover the api-key happy path.
Phase 3 — spec, docs, env templates:
- api/openapi.yaml: auth_type enum dropped to [api-key, none] with
inline comment naming the G-1 closure.
- .env.example (root): CERTCTL_AUTH_TYPE comment block rewritten to drop
jwt and point at the gateway pattern; secret-required conditional
simplified to api-key-only.
- docs/architecture.md: middleware-stack bullet rewritten to drop the
JWT mention; new H3 'Authenticating-gateway pattern (JWT, OIDC, mTLS)'
section explaining the design rationale and listing oauth2-proxy /
Envoy ext_authz / Traefik ForwardAuth / Pomerium / Authelia / Caddy
forward_auth / Apache mod_auth_openidc / nginx auth_request as the
standard fronting options.
- docs/upgrade-to-v2-jwt-removal.md (new ~125 lines): migration guide
with preconditions, what-changes, both recovery paths, complete
docker-compose oauth2-proxy walkthrough, Traefik ForwardAuth and Envoy
ext_authz patterns, rollback posture.
Phase 4 — Helm chart (template validation + docs):
- deploy/helm/certctl/templates/_helpers.tpl: new certctl.validateAuthType
helper mirroring the existing certctl.tls.required pattern. Fails
template render on any server.auth.type outside {api-key, none} with
a multi-line diagnostic.
- deploy/helm/certctl/templates/server-deployment.yaml,
server-configmap.yaml, server-secret.yaml: invoke the helper at the
top of each template that depends on .Values.server.auth.type.
- deploy/helm/certctl/values.yaml: auth: block comment expanded with the
G-1 rationale and gateway-pattern cross-reference.
- deploy/helm/CHART_SUMMARY.md: server.auth.type table row now surfaces
the allowed set and points at the upgrade doc.
- deploy/helm/certctl/README.md: new 'JWT / OIDC via authenticating
gateway' section with a Kubernetes-flavored oauth2-proxy + certctl
walkthrough.
Phase 5 — release surface:
- CHANGELOG.md: new [unreleased] top entry with Breaking / Removed /
Added / Changed sections; explicit pointer at
docs/upgrade-to-v2-jwt-removal.md from the Breaking subsection.
Phase 6 — CI guardrail:
- .github/workflows/ci.yml: new 'Forbidden auth-type literal regression
guard (G-1)' step. Scoped patterns catch the actual regression shapes
(map literal, slice literal, switch case, OpenAPI enum, env-file
default, AuthType('jwt') cast). Comments and the dedicated rejection
branch are intentionally exempt; connector-package JWT references
(Google OAuth2 / step-ca) are exempt as out-of-scope external
protocols. Verified locally: the guard passes on the actual tree and
fires on all 4 synthetic regression patterns.
Out of scope (explicitly untouched):
- internal/connector/discovery/gcpsm/gcpsm.go — Google OAuth2 service-
account JWT (external protocol).
- internal/connector/issuer/googlecas/googlecas.go — same.
- internal/connector/issuer/stepca/stepca.go — step-ca's provisioner
one-time-token JWT for /sign API.
- docs/test-env.md, docs/connectors.md, docs/features.md — describe
external CAs' use of JWT, not certctl's auth shape.
- Implementing actual JWT middleware. Feature, not a fix.
Verification (all gates pass):
- go build ./... — clean
- go vet ./... — clean
- go test -short ./... — every package green
- go test -short -race ./internal/config/... ./internal/api/... — clean
- govulncheck ./... — no vulnerabilities in our code
- helm lint deploy/helm/certctl/ — clean
- helm template with auth.type=api-key — renders OK
- helm template with auth.type=none — renders OK
- helm template with auth.type=jwt — fails with validateAuthType
diagnostic (exit 1)
- python3 yaml.safe_load on api/openapi.yaml — parses
- CI guardrail mirror — clean on real tree, fires on all 4 synthetic
regression patterns
- Smoke test: 'CERTCTL_AUTH_TYPE=jwt ./certctl-server' exits non-zero
with: 'Failed to load configuration: CERTCTL_AUTH_TYPE=jwt is no
longer accepted (G-1 silent auth downgrade): no JWT middleware ships
with certctl. To use JWT/OIDC, run an authenticating gateway
(oauth2-proxy / Envoy ext_authz / Traefik ForwardAuth / Pomerium) in
front of certctl and set CERTCTL_AUTH_TYPE=none on the upstream.
See docs/architecture.md "Authenticating-gateway pattern" and
docs/upgrade-to-v2-jwt-removal.md for the migration walkthrough'
config pkg coverage: ValidAuthTypes 100%, Validate 94.7%, total 75.5%.
Refs: coverage-gap-audit-2026-04-24-v5/unified-audit.md
§2 P1 cluster, cat-g-jwt_silent_auth_downgrade
Audit recommendation followed verbatim: 'Remove jwt from
validAuthTypes until middleware ships'.
332 lines
9.6 KiB
Go
332 lines
9.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/shankar0123/certctl/internal/api/middleware"
|
|
)
|
|
|
|
func TestHealth_ReturnsOK(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req, err := http.NewRequest(http.MethodGet, "/health", nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRequest failed: %v", err)
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.Health(w, req)
|
|
|
|
if status := w.Code; status != http.StatusOK {
|
|
t.Errorf("Health handler returned status %d, want %d", status, http.StatusOK)
|
|
}
|
|
|
|
// Check content type
|
|
if ct := w.Header().Get("Content-Type"); ct != "application/json" {
|
|
t.Errorf("Content-Type = %q, want application/json", ct)
|
|
}
|
|
|
|
// Check response body
|
|
var result map[string]string
|
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
if result["status"] != "healthy" {
|
|
t.Errorf("status = %q, want healthy", result["status"])
|
|
}
|
|
}
|
|
|
|
func TestHealth_MethodNotAllowed(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req, err := http.NewRequest(http.MethodPost, "/health", nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRequest failed: %v", err)
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.Health(w, req)
|
|
|
|
if status := w.Code; status != http.StatusMethodNotAllowed {
|
|
t.Errorf("Health handler returned status %d, want %d", status, http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
func TestReady_ReturnsOK(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req, err := http.NewRequest(http.MethodGet, "/ready", nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRequest failed: %v", err)
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.Ready(w, req)
|
|
|
|
if status := w.Code; status != http.StatusOK {
|
|
t.Errorf("Ready handler returned status %d, want %d", status, http.StatusOK)
|
|
}
|
|
|
|
// Check content type
|
|
if ct := w.Header().Get("Content-Type"); ct != "application/json" {
|
|
t.Errorf("Content-Type = %q, want application/json", ct)
|
|
}
|
|
|
|
// Check response body
|
|
var result map[string]string
|
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
if result["status"] != "ready" {
|
|
t.Errorf("status = %q, want ready", result["status"])
|
|
}
|
|
}
|
|
|
|
func TestReady_MethodNotAllowed(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req, err := http.NewRequest(http.MethodDelete, "/ready", nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRequest failed: %v", err)
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.Ready(w, req)
|
|
|
|
if status := w.Code; status != http.StatusMethodNotAllowed {
|
|
t.Errorf("Ready handler returned status %d, want %d", status, http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
func TestAuthInfo_ReturnsAuthType_APIKey(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req, err := http.NewRequest(http.MethodGet, "/api/v1/auth/info", nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRequest failed: %v", err)
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.AuthInfo(w, req)
|
|
|
|
if status := w.Code; status != http.StatusOK {
|
|
t.Errorf("AuthInfo handler returned status %d, want %d", status, http.StatusOK)
|
|
}
|
|
|
|
var result map[string]interface{}
|
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
if result["auth_type"] != "api-key" {
|
|
t.Errorf("auth_type = %q, want api-key", result["auth_type"])
|
|
}
|
|
|
|
if required, ok := result["required"].(bool); !ok || !required {
|
|
t.Errorf("required = %v, want true", result["required"])
|
|
}
|
|
}
|
|
|
|
func TestAuthInfo_ReturnsAuthType_None(t *testing.T) {
|
|
handler := NewHealthHandler("none")
|
|
|
|
req, err := http.NewRequest(http.MethodGet, "/api/v1/auth/info", nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRequest failed: %v", err)
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.AuthInfo(w, req)
|
|
|
|
if status := w.Code; status != http.StatusOK {
|
|
t.Errorf("AuthInfo handler returned status %d, want %d", status, http.StatusOK)
|
|
}
|
|
|
|
var result map[string]interface{}
|
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
if result["auth_type"] != "none" {
|
|
t.Errorf("auth_type = %q, want none", result["auth_type"])
|
|
}
|
|
|
|
if required, ok := result["required"].(bool); !ok || required {
|
|
t.Errorf("required = %v, want false", result["required"])
|
|
}
|
|
}
|
|
|
|
// G-1 (P1): the prior `TestAuthInfo_ReturnsAuthType_JWT` asserted the
|
|
// handler echoed "jwt" — using the silent-auth-downgrade value as a
|
|
// test fixture, which baked the lie into the regression suite. The
|
|
// test is removed because "jwt" is now rejected at config-load time
|
|
// (see internal/config/config_test.go::TestValidate_JWTAuth_RejectedDedicated)
|
|
// and never reaches this handler. The pre-existing
|
|
// `TestAuthInfo_ReturnsAuthType_APIKey` above (line ~107) covers the
|
|
// api-key happy path; nothing else needs replacing here.
|
|
|
|
func TestAuthCheck_ReturnsOK(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req, err := http.NewRequest(http.MethodGet, "/api/v1/auth/check", nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRequest failed: %v", err)
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.AuthCheck(w, req)
|
|
|
|
if status := w.Code; status != http.StatusOK {
|
|
t.Errorf("AuthCheck handler returned status %d, want %d", status, http.StatusOK)
|
|
}
|
|
|
|
// Check content type
|
|
if ct := w.Header().Get("Content-Type"); ct != "application/json" {
|
|
t.Errorf("Content-Type = %q, want application/json", ct)
|
|
}
|
|
|
|
// Check response body — mixed-value map (string + bool) post-Phase B.4.
|
|
var result map[string]any
|
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
if result["status"] != "authenticated" {
|
|
t.Errorf("status = %q, want authenticated", result["status"])
|
|
}
|
|
}
|
|
|
|
func TestAuthCheck_MethodNotAllowed(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req, err := http.NewRequest(http.MethodPost, "/api/v1/auth/check", nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRequest failed: %v", err)
|
|
}
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.AuthCheck(w, req)
|
|
|
|
// AuthCheck doesn't explicitly check method, so it will return 200
|
|
// But let's verify the response is still correct
|
|
if status := w.Code; status != http.StatusOK {
|
|
t.Logf("AuthCheck returned status %d (note: method not enforced in handler)", status)
|
|
}
|
|
}
|
|
|
|
// --- M-003 (Phase B.4): /auth/check surfaces admin flag + user identity ---
|
|
|
|
// TestAuthCheck_AdminCaller_ReportsAdminTrue confirms that when the auth
|
|
// middleware sets AdminKey{}=true (i.e., named key was admin-tagged), the
|
|
// /auth/check endpoint reports admin=true so the GUI can show admin-only
|
|
// affordances.
|
|
func TestAuthCheck_AdminCaller_ReportsAdminTrue(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/check", nil)
|
|
ctx := context.WithValue(req.Context(), middleware.AdminKey{}, true)
|
|
ctx = context.WithValue(ctx, middleware.UserKey{}, "ops-admin")
|
|
req = req.WithContext(ctx)
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.AuthCheck(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d", w.Code)
|
|
}
|
|
|
|
var result map[string]any
|
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
if result["status"] != "authenticated" {
|
|
t.Errorf("status = %q, want authenticated", result["status"])
|
|
}
|
|
admin, ok := result["admin"].(bool)
|
|
if !ok {
|
|
t.Fatalf("admin field missing or wrong type: %T", result["admin"])
|
|
}
|
|
if !admin {
|
|
t.Errorf("admin = false, want true")
|
|
}
|
|
if result["user"] != "ops-admin" {
|
|
t.Errorf("user = %q, want ops-admin", result["user"])
|
|
}
|
|
}
|
|
|
|
// TestAuthCheck_NonAdminCaller_ReportsAdminFalse pins the negative case: the
|
|
// auth middleware has stored AdminKey{}=false (non-admin named key) — the
|
|
// endpoint must report admin=false so the GUI hides admin-only affordances.
|
|
func TestAuthCheck_NonAdminCaller_ReportsAdminFalse(t *testing.T) {
|
|
handler := NewHealthHandler("api-key")
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/check", nil)
|
|
ctx := context.WithValue(req.Context(), middleware.AdminKey{}, false)
|
|
ctx = context.WithValue(ctx, middleware.UserKey{}, "alice")
|
|
req = req.WithContext(ctx)
|
|
|
|
w := httptest.NewRecorder()
|
|
handler.AuthCheck(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d", w.Code)
|
|
}
|
|
|
|
var result map[string]any
|
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
admin, ok := result["admin"].(bool)
|
|
if !ok {
|
|
t.Fatalf("admin field missing or wrong type: %T", result["admin"])
|
|
}
|
|
if admin {
|
|
t.Errorf("admin = true, want false")
|
|
}
|
|
if result["user"] != "alice" {
|
|
t.Errorf("user = %q, want alice", result["user"])
|
|
}
|
|
}
|
|
|
|
// TestAuthCheck_NoAuthContext_DefaultsToEmptyUserAndFalseAdmin covers the
|
|
// CERTCTL_AUTH_TYPE=none deployment, where the auth middleware doesn't set
|
|
// any keys. Response must still be well-formed with empty user + admin=false.
|
|
func TestAuthCheck_NoAuthContext_DefaultsToEmptyUserAndFalseAdmin(t *testing.T) {
|
|
handler := NewHealthHandler("none")
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/check", nil)
|
|
w := httptest.NewRecorder()
|
|
handler.AuthCheck(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d", w.Code)
|
|
}
|
|
|
|
var result map[string]any
|
|
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
|
t.Fatalf("failed to decode response: %v", err)
|
|
}
|
|
|
|
if result["status"] != "authenticated" {
|
|
t.Errorf("status = %q, want authenticated", result["status"])
|
|
}
|
|
admin, ok := result["admin"].(bool)
|
|
if !ok {
|
|
t.Fatalf("admin field missing or wrong type: %T", result["admin"])
|
|
}
|
|
if admin {
|
|
t.Errorf("admin = true for no-auth context, want false")
|
|
}
|
|
if result["user"] != "" {
|
|
t.Errorf("user = %q, want empty string", result["user"])
|
|
}
|
|
}
|