auth-bundle-1 Phase 3.5: handler IsAdmin -> router-wrapped RequirePermission

Phase 3.5 atomic conversion. The five legacy admin-gated handlers (bulk_revocation, admin_crl_cache, admin_scep_intune, admin_est, intermediate_ca) had their in-body auth.IsAdmin checks removed; the gate moved to router.go via auth.RequirePermission middleware wrapping each route. Non-admin operators with the right scoped permission can now reach these endpoints; legacy in-body admin checks no longer block them.

Migration 000030_rbac_admin_perms.up.sql ships five admin-only fine-grained permissions: cert.bulk_revoke, crl.admin, scep.admin, est.admin, ca.hierarchy.manage. All five are seeded into r-admin only; operator/viewer/agent/mcp/cli/auditor do not receive them by default. Operators can grant any of these to a custom role via the Phase 4 RBAC API. Idempotent + transaction-wrapped.

internal/domain/auth/validate.go::CanonicalPermissions extended with the five new entries so RoleService.AddPermission accepts them.

internal/api/router/router.go: HandlerRegistry gains a Checker field (auth.PermissionChecker). New rbacGate(checker, perm, handler) helper wraps a handler with auth.RequirePermission middleware; nil-checker fall-through preserves test/demo deployments without the RBAC stack. 12 admin routes wrapped: cert.bulk_revoke (POST /api/v1/certificates/bulk-revoke + POST /api/v1/est/certificates/bulk-revoke), crl.admin (GET /api/v1/admin/crl/cache), scep.admin (GET /api/v1/admin/scep/profiles + GET /api/v1/admin/scep/intune/stats + POST /api/v1/admin/scep/intune/reload-trust), est.admin (GET /api/v1/admin/est/profiles + POST /api/v1/admin/est/reload-trust), ca.hierarchy.manage (POST /api/v1/issuers/{id}/intermediates + GET /api/v1/issuers/{id}/intermediates + POST /api/v1/intermediates/{id}/retire + GET /api/v1/intermediates/{id}).

cmd/server/main.go: HandlerRegistry.Checker wired with the same authPermissionCheckerAdapter shim Phase 4 introduced for AuthHandler. Same adapter; one source of truth.

Handler bodies: removed eight in-body auth.IsAdmin checks across the 5 files. bulk_revocation.go's BulkRevoke + BulkRevokeEST, admin_crl_cache.go::ListCache, admin_scep_intune.go's three methods, admin_est.go's two methods, intermediate_ca.go's four methods. Replaced each with a comment naming the new gate location. Unused 'github.com/certctl-io/certctl/internal/auth' imports removed.

Test triplet rewrite: deleted obsolete _NonAdmin_Returns403 and _AdminExplicitFalse_Returns403 tests across 6 test files (5 handler tests + bulk_revocation_est_test.go) — they tested the now-removed in-body gate. _AdminPermitted_ForwardsActor tests stay intact: they pin the actor-passthrough invariant which is still relevant. Added internal/api/router/rbac_gate_integration_test.go with four router-level integration tests pinning the new gate: deny → 403 + handler not reached, permit → 200 + handler reached, nil-checker → fall-through, no-actor → 401.

M-008 admin-gate registry: AdminGatedHandlers map now empty (Phase 3.5 invariant: zero in-handler auth.IsAdmin call sites; only health.go's informational caller remains). m008_admin_gate_test.go retains the scan to enforce the invariant going forward; new admin-gated routes must wrap at router.go::rbacGate, not gate in-handler. Updated error message to direct future contributors to the new pattern.

Verifications: gofmt clean across all touched files; go vet ./... clean; go test -short across internal/auth, internal/service/auth, internal/api/handler, internal/api/router, cmd/server all green.

Branch: dev/auth-bundle-1. Commit chain: 99a012e (Phase 0 extract) -> 19497ee (Phase 1 schema + repo) -> bd54d5f (Phase 2 service) -> d473398 (Phase 3 primitive) -> b169f25 (Phase 4 + 5) -> THIS (Phase 3.5 conversion). Phase 6+ (bootstrap, scope-down, auditor, approval-bypass closure, GUI, docs) on subsequent sessions.
This commit is contained in:
shankar0123
2026-05-09 17:00:30 +00:00
parent b169f258de
commit 7ff2e2de08
19 changed files with 290 additions and 485 deletions
+11 -11
View File
@@ -99,17 +99,17 @@ var SpecParityExceptions = map[string]string{
// response shape is documented in internal/api/handler/auth.go's
// type definitions; the OpenAPI section lift will mirror those.
// Routes:
"GET /api/v1/auth/me": "Bundle 1 Phase 4 RBAC: current actor's effective permissions; OpenAPI follow-up.",
"GET /api/v1/auth/permissions": "Bundle 1 Phase 4 RBAC: canonical permission catalogue; OpenAPI follow-up.",
"GET /api/v1/auth/roles": "Bundle 1 Phase 4 RBAC: list roles; OpenAPI follow-up.",
"POST /api/v1/auth/roles": "Bundle 1 Phase 4 RBAC: create role; OpenAPI follow-up.",
"GET /api/v1/auth/roles/{id}": "Bundle 1 Phase 4 RBAC: get role + permissions; OpenAPI follow-up.",
"PUT /api/v1/auth/roles/{id}": "Bundle 1 Phase 4 RBAC: update role; OpenAPI follow-up.",
"DELETE /api/v1/auth/roles/{id}": "Bundle 1 Phase 4 RBAC: delete role; OpenAPI follow-up.",
"POST /api/v1/auth/roles/{id}/permissions": "Bundle 1 Phase 4 RBAC: grant permission to role; OpenAPI follow-up.",
"DELETE /api/v1/auth/roles/{id}/permissions/{perm}": "Bundle 1 Phase 4 RBAC: revoke permission from role; OpenAPI follow-up.",
"POST /api/v1/auth/keys/{id}/roles": "Bundle 1 Phase 4 RBAC: assign role to API key; OpenAPI follow-up.",
"DELETE /api/v1/auth/keys/{id}/roles/{role_id}": "Bundle 1 Phase 4 RBAC: revoke role from API key; OpenAPI follow-up.",
"GET /api/v1/auth/me": "Bundle 1 Phase 4 RBAC: current actor's effective permissions; OpenAPI follow-up.",
"GET /api/v1/auth/permissions": "Bundle 1 Phase 4 RBAC: canonical permission catalogue; OpenAPI follow-up.",
"GET /api/v1/auth/roles": "Bundle 1 Phase 4 RBAC: list roles; OpenAPI follow-up.",
"POST /api/v1/auth/roles": "Bundle 1 Phase 4 RBAC: create role; OpenAPI follow-up.",
"GET /api/v1/auth/roles/{id}": "Bundle 1 Phase 4 RBAC: get role + permissions; OpenAPI follow-up.",
"PUT /api/v1/auth/roles/{id}": "Bundle 1 Phase 4 RBAC: update role; OpenAPI follow-up.",
"DELETE /api/v1/auth/roles/{id}": "Bundle 1 Phase 4 RBAC: delete role; OpenAPI follow-up.",
"POST /api/v1/auth/roles/{id}/permissions": "Bundle 1 Phase 4 RBAC: grant permission to role; OpenAPI follow-up.",
"DELETE /api/v1/auth/roles/{id}/permissions/{perm}": "Bundle 1 Phase 4 RBAC: revoke permission from role; OpenAPI follow-up.",
"POST /api/v1/auth/keys/{id}/roles": "Bundle 1 Phase 4 RBAC: assign role to API key; OpenAPI follow-up.",
"DELETE /api/v1/auth/keys/{id}/roles/{role_id}": "Bundle 1 Phase 4 RBAC: revoke role from API key; OpenAPI follow-up.",
}
func TestRouter_OpenAPIParity(t *testing.T) {
@@ -0,0 +1,129 @@
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")
}
}
+33 -12
View File
@@ -5,8 +5,20 @@ import (
"github.com/certctl-io/certctl/internal/api/handler"
"github.com/certctl-io/certctl/internal/api/middleware"
"github.com/certctl-io/certctl/internal/auth"
)
// rbacGate wraps a handler with auth.RequirePermission(checker, perm,
// nil). Used by RegisterHandlers to gate the legacy admin routes
// (Bundle 1 Phase 3.5). When checker is nil the wrap is a no-op so
// tests / demo deployments without the RBAC stack continue to work.
func rbacGate(checker auth.PermissionChecker, perm string, h http.HandlerFunc) http.Handler {
if checker == nil {
return h
}
return auth.RequirePermission(checker, perm, nil)(h)
}
// Router wraps http.ServeMux and manages route registration with middleware.
type Router struct {
mux *http.ServeMux
@@ -118,6 +130,15 @@ type HandlerRegistry struct {
// the service-layer Authorizer + RoleService + ActorRoleService +
// PermissionService dependencies. Phase 5 ships the CLI mirror.
Auth handler.AuthHandler
// Checker is the load-bearing auth.PermissionChecker that
// auth.RequirePermission middleware uses to gate the legacy admin
// handlers (Bundle 1 Phase 3.5). cmd/server wires the postgres
// Authorizer here via the authPermissionCheckerAdapter shim. When
// nil, the wraps are no-ops and the routes fall through unguarded
// (only valid in tests / demo deployments — production MUST
// configure a Checker).
Checker auth.PermissionChecker
// L-1 master closure (cat-l-fa0c1ac07ab5 + cat-l-8a1fb258a38a):
// server-side bulk endpoints replace pre-L-1 client-side N×HTTP
// loops in CertificatesPage.tsx. See handler/bulk_renewal.go and
@@ -250,11 +271,11 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
// in, {total_matched, total_<verb>, total_skipped, total_failed,
// errors[]} out). L-1 master added bulk-renew + bulk-reassign
// alongside the pre-existing bulk-revoke.
r.Register("POST /api/v1/certificates/bulk-revoke", http.HandlerFunc(reg.BulkRevocation.BulkRevoke))
r.Register("POST /api/v1/certificates/bulk-revoke", rbacGate(reg.Checker, "cert.bulk_revoke", reg.BulkRevocation.BulkRevoke))
// EST RFC 7030 hardening Phase 11.2 — Source-scoped EST bulk-revoke.
// Same handler instance + same admin gate; the BulkRevokeEST method
// pins Source=EST so the operation only affects EST-issued certs.
r.Register("POST /api/v1/est/certificates/bulk-revoke", http.HandlerFunc(reg.BulkRevocation.BulkRevokeEST))
r.Register("POST /api/v1/est/certificates/bulk-revoke", rbacGate(reg.Checker, "cert.bulk_revoke", reg.BulkRevocation.BulkRevokeEST))
r.Register("POST /api/v1/certificates/bulk-renew", http.HandlerFunc(reg.BulkRenewal.BulkRenew))
r.Register("POST /api/v1/certificates/bulk-reassign", http.HandlerFunc(reg.BulkReassignment.BulkReassign))
r.Register("GET /api/v1/certificates", http.HandlerFunc(reg.Certificates.ListCertificates))
@@ -378,18 +399,18 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
// Bundle CRL/OCSP-Responder Phase 5: admin observability for the
// scheduler-driven CRL pre-generation cache. Admin-gated inside
// the handler (M-003 pattern); non-admin callers get 403.
r.Register("GET /api/v1/admin/crl/cache", http.HandlerFunc(reg.AdminCRLCache.ListCache))
r.Register("GET /api/v1/admin/crl/cache", rbacGate(reg.Checker, "crl.admin", reg.AdminCRLCache.ListCache))
// SCEP RFC 8894 + Intune master bundle Phase 9.2 + Phase 9 follow-up
// (the project's SCEP GUI restructure spec). All three endpoints are
// admin-gated at the handler layer; the M-008 regression scanner pins
// the gate set and TestM008_AdminGatedHandlers_HaveTripletTests
// enforces the per-handler test triplet.
r.Register("GET /api/v1/admin/scep/profiles", http.HandlerFunc(reg.AdminSCEPIntune.Profiles))
r.Register("GET /api/v1/admin/scep/intune/stats", http.HandlerFunc(reg.AdminSCEPIntune.Stats))
r.Register("POST /api/v1/admin/scep/intune/reload-trust", http.HandlerFunc(reg.AdminSCEPIntune.ReloadTrust))
r.Register("GET /api/v1/admin/scep/profiles", rbacGate(reg.Checker, "scep.admin", reg.AdminSCEPIntune.Profiles))
r.Register("GET /api/v1/admin/scep/intune/stats", rbacGate(reg.Checker, "scep.admin", reg.AdminSCEPIntune.Stats))
r.Register("POST /api/v1/admin/scep/intune/reload-trust", rbacGate(reg.Checker, "scep.admin", reg.AdminSCEPIntune.ReloadTrust))
// EST RFC 7030 hardening Phase 7.2 — admin-gated EST observability.
r.Register("GET /api/v1/admin/est/profiles", http.HandlerFunc(reg.AdminEST.Profiles))
r.Register("POST /api/v1/admin/est/reload-trust", http.HandlerFunc(reg.AdminEST.ReloadTrust))
r.Register("GET /api/v1/admin/est/profiles", rbacGate(reg.Checker, "est.admin", reg.AdminEST.Profiles))
r.Register("POST /api/v1/admin/est/reload-trust", rbacGate(reg.Checker, "est.admin", reg.AdminEST.ReloadTrust))
// Notifications routes: /api/v1/notifications
r.Register("GET /api/v1/notifications", http.HandlerFunc(reg.Notifications.ListNotifications))
@@ -415,10 +436,10 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
// /retire literal segment resolves before the {id} pattern-var
// route under Go 1.22 ServeMux precedence — the ordering below
// matches the notifications + approvals blocks above.
r.Register("POST /api/v1/issuers/{id}/intermediates", http.HandlerFunc(reg.IntermediateCAs.Create))
r.Register("GET /api/v1/issuers/{id}/intermediates", http.HandlerFunc(reg.IntermediateCAs.List))
r.Register("POST /api/v1/intermediates/{id}/retire", http.HandlerFunc(reg.IntermediateCAs.Retire))
r.Register("GET /api/v1/intermediates/{id}", http.HandlerFunc(reg.IntermediateCAs.Get))
r.Register("POST /api/v1/issuers/{id}/intermediates", rbacGate(reg.Checker, "ca.hierarchy.manage", reg.IntermediateCAs.Create))
r.Register("GET /api/v1/issuers/{id}/intermediates", rbacGate(reg.Checker, "ca.hierarchy.manage", reg.IntermediateCAs.List))
r.Register("POST /api/v1/intermediates/{id}/retire", rbacGate(reg.Checker, "ca.hierarchy.manage", reg.IntermediateCAs.Retire))
r.Register("GET /api/v1/intermediates/{id}", rbacGate(reg.Checker, "ca.hierarchy.manage", reg.IntermediateCAs.Get))
// Stats routes: /api/v1/stats
r.Register("GET /api/v1/stats/summary", http.HandlerFunc(reg.Stats.GetDashboardSummary))