Files
certctl/internal/api/router/rbac_gate_integration_test.go
T
shankar0123 60a589ab96 auth-bundle-1 Phase 0-5 closure: demo-mode wire, named-key backfill, AuthCheck enrichment, OpenAPI schema, intermediate-ca comment refresh
Closes the 5 gaps the post-Phase-5 audit flagged on dev/auth-bundle-1.

C1: cmd/server/main.go now selects auth.NewDemoModeAuth() when
CERTCTL_AUTH_TYPE=none and falls back to auth.NewAuthWithNamedKeys
otherwise. Pre-closure, the no-op pass-through that
NewAuthWithNamedKeys returns for empty keys would have left
ActorIDKey / ActorTypeKey / TenantIDKey unpopulated and 401'd
every Phase-3.5 rbacGate-wrapped admin route + every Phase-4
RBAC handler in demo deployments. NewDemoModeAuth injects the
synthetic 'actor-demo-anon' actor seeded by migration 000029,
which holds r-admin at global scope.

C2: backfillNamedKeyActorRoles startup hook (cmd/server/auth_backfill.go)
iterates CERTCTL_API_KEYS_NAMED entries (and legacy
CERTCTL_AUTH_SECRET synthesized fallbacks) and grants r-admin
or r-viewer to each via authActorRoleRepo.Grant before the
HTTP server starts accepting requests. Idempotent via
ON CONFLICT DO NOTHING in the repo. Failures log a warning but
are non-fatal — the server still starts and the operator can
fix grants via /v1/auth/keys. Helper extracted from main.go so
the role-mapping invariant is pinned by 4 focused unit tests
(admin->r-admin, non-admin->r-viewer, empty no-op,
grant-error non-fatal, nil-logger safe).

M1: HealthHandler.AuthCheck now returns actor_id, actor_type,
tenant_id, roles, effective_permissions, and admin_via_role
when the optional AuthCheckResolver is wired (production path:
authCheckResolverAdapter wraps the postgres ActorRoleRepository
in main.go). Nil resolver preserves the legacy {status, user,
admin} contract for back-compat with pre-Bundle-1 GUIs and
test fixtures. Adds 2 regression tests + 1 fake resolver shim.

M2: refreshes the stale 'Admin gate: every method calls
auth.IsAdmin first' comment on IntermediateCAHandler — the gate
moved to router.go::rbacGate via auth.RequirePermission
middleware in Phase 3.5; the new comment block points readers
there.

M4: 11 RBAC routes (auth/me, auth/permissions, 5 role lifecycle,
2 role-permission grant/revoke, 2 actor-role grant/revoke) added
to api/openapi.yaml under the [Auth] tag with operationIds and
shared AuthRole / AuthRolePermission schemas. AuthCheck path
extended with the Bundle-1 enrichment fields. The 11 entries
removed from openapi_parity_test.go::SpecParityExceptions.

Tests: go vet + staticcheck + go test -short -count=1 green
across cmd/server/, internal/auth/, internal/api/router/, and
internal/api/handler/. New tests: 4 backfill unit tests,
2 AuthCheck M1 enrichment tests, 1 demo-mode + rbacGate chain
integration test (TestRBACGate_DemoModeChainReachesHandler).

Branch SECURITY.md (cowork/auth-bundle-1-SECURITY.md, not part
of this commit) captures the full posture of dev/auth-bundle-1
as of this closure for the operator's pre-merge review.
2026-05-09 19:33:07 +00:00

164 lines
6.0 KiB
Go

package router
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/certctl-io/certctl/internal/auth"
)
// =============================================================================
// Bundle 1 Phase 3.5 integration tests for the rbacGate wraps. The
// pre-Phase-3.5 in-handler auth.IsAdmin checks moved to the router via
// auth.RequirePermission middleware; these tests pin the router-level
// invariant that non-permitted callers get 403 BEFORE the handler body
// runs, and that the protocol-endpoint allowlist (ACME / SCEP / EST /
// OCSP / CRL) bypasses the gate.
// =============================================================================
// fakeChecker satisfies auth.PermissionChecker. permFn returns the
// canned (allowed, error) tuple per call.
type fakeChecker struct {
permFn func(ctx context.Context, actorID, actorType, tenantID, perm, scopeType string, scopeID *string) (bool, error)
}
func (f *fakeChecker) CheckPermission(ctx context.Context, actorID, actorType, tenantID, perm, scopeType string, scopeID *string) (bool, error) {
if f.permFn == nil {
return true, nil
}
return f.permFn(ctx, actorID, actorType, tenantID, perm, scopeType, scopeID)
}
// reachedHandler is a sentinel to confirm the gated handler body
// actually ran.
type reachedHandler struct{ called bool }
func (rh *reachedHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
rh.called = true
w.WriteHeader(http.StatusOK)
}
// withActor is a tiny test helper: builds a request with the Phase 3
// auth-context keys populated.
func withActor(req *http.Request, actorID, actorType string) *http.Request {
ctx := req.Context()
ctx = context.WithValue(ctx, auth.ActorIDKey{}, actorID)
ctx = context.WithValue(ctx, auth.ActorTypeKey{}, actorType)
return req.WithContext(ctx)
}
func TestRBACGate_DeniedActorReturns403_HandlerNotReached(t *testing.T) {
rh := &reachedHandler{}
checker := &fakeChecker{permFn: func(_ context.Context, _, _, _, perm, _ string, _ *string) (bool, error) {
if perm != "cert.bulk_revoke" {
t.Errorf("perm = %q, want cert.bulk_revoke", perm)
}
return false, nil
}}
gated := rbacGate(checker, "cert.bulk_revoke", rh.ServeHTTP)
req := withActor(httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", nil), "bob", auth.ActorTypeAPIKey)
rec := httptest.NewRecorder()
gated.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Errorf("non-permitted caller should get 403; got %d", rec.Code)
}
if rh.called {
t.Errorf("handler body must NOT run when middleware denies the request")
}
}
func TestRBACGate_PermittedActorReachesHandler(t *testing.T) {
rh := &reachedHandler{}
checker := &fakeChecker{permFn: func(_ context.Context, _, _, _, _, _ string, _ *string) (bool, error) {
return true, nil
}}
gated := rbacGate(checker, "cert.bulk_revoke", rh.ServeHTTP)
req := withActor(httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", nil), "alice", auth.ActorTypeAPIKey)
rec := httptest.NewRecorder()
gated.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("permitted caller should reach handler 200; got %d", rec.Code)
}
if !rh.called {
t.Errorf("handler body must run when middleware allows the request")
}
}
func TestRBACGate_NoCheckerNoOps(t *testing.T) {
// Test deployments / demo configs may construct HandlerRegistry
// without a Checker. rbacGate must fall through to the handler in
// that case so the route stays callable; the middleware is purely
// optional defense-in-depth here.
rh := &reachedHandler{}
gated := rbacGate(nil, "cert.bulk_revoke", rh.ServeHTTP)
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", nil)
rec := httptest.NewRecorder()
gated.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("nil-checker rbacGate should fall through; got %d", rec.Code)
}
if !rh.called {
t.Errorf("nil-checker rbacGate should reach handler unconditionally")
}
}
func TestRBACGate_NoActorReturns401(t *testing.T) {
rh := &reachedHandler{}
checker := &fakeChecker{} // permFn nil -> always allow; never called
gated := rbacGate(checker, "cert.bulk_revoke", rh.ServeHTTP)
// No ActorIDKey in context.
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", nil)
rec := httptest.NewRecorder()
gated.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("missing actor should yield 401; got %d", rec.Code)
}
if rh.called {
t.Errorf("handler body must NOT run when no actor in context")
}
}
// TestRBACGate_DemoModeChainReachesHandler is the end-to-end Bundle 1
// Phase 3 closure (C1) regression: when CERTCTL_AUTH_TYPE=none, the
// auth.NewDemoModeAuth middleware injects the synthetic actor-demo-anon
// actor into context. The rbacGate downstream sees a populated actor +
// the fake checker (standing in for the seeded admin grant on the
// demo actor) and forwards the request. Without the C1 fix, the
// pre-closure NewAuthWithNamedKeys no-op pass-through would have left
// context unpopulated and the rbacGate would 401 every demo request.
func TestRBACGate_DemoModeChainReachesHandler(t *testing.T) {
rh := &reachedHandler{}
// Mirror the seeded admin grant on actor-demo-anon: the checker
// allows every permission for the demo actor (matches the data
// migration seeds in 000029_rbac.up.sql).
checker := &fakeChecker{permFn: func(_ context.Context, actorID, _, _, _, _ string, _ *string) (bool, error) {
if actorID != auth.DemoAnonActorID {
t.Errorf("checker called for unexpected actor %q (want demo-anon)", actorID)
}
return true, nil
}}
gated := rbacGate(checker, "cert.bulk_revoke", rh.ServeHTTP)
chain := auth.NewDemoModeAuth()(gated)
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", nil)
rec := httptest.NewRecorder()
chain.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("demo-mode caller against admin route should reach handler 200; got %d", rec.Code)
}
if !rh.called {
t.Errorf("handler body must run for demo-mode caller (C1 closure regression)")
}
}