mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 12:41:30 +00:00
7ff2e2de08
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.
130 lines
4.5 KiB
Go
130 lines
4.5 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")
|
|
}
|
|
}
|