Files
certctl/internal/api/handler/admin_est_test.go
T
shankar0123 e413e1762d 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: 69f8601 (Phase 0 extract) -> 52adec1 (Phase 1 schema + repo) -> e4a5eb7 (Phase 2 service) -> 791659e (Phase 3 primitive) -> 37c43e5 (Phase 4 + 5) -> THIS (Phase 3.5 conversion). Phase 6+ (bootstrap, scope-down, auditor, approval-bypass closure, GUI, docs) on subsequent sessions.
2026-05-09 17:00:30 +00:00

226 lines
7.8 KiB
Go

package handler
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/certctl-io/certctl/internal/api/middleware"
"github.com/certctl-io/certctl/internal/auth"
"github.com/certctl-io/certctl/internal/service"
)
// EST RFC 7030 hardening master bundle Phase 7.4 — admin handler tests.
// Mirrors admin_scep_intune_test.go's structure verbatim:
// - M-008 admin-gate triplet for both endpoints (non-admin / admin=false / admin=true).
// - Method-not-allowed gates.
// - Error mapping (404 unknown PathID / 409 mTLS-disabled / 500 underlying parse error).
// fakeAdminESTService is the test stub. Records call observations so the
// M-008 admin-gate triplet can pin "service was never invoked" when the
// gate rejects the caller.
type fakeAdminESTService struct {
profilesCalled bool
reloadCalled bool
rows []service.ESTStatsSnapshot
profilesErr error
reloadPathID string
reloadErr error
}
func (f *fakeAdminESTService) Profiles(_ context.Context, _ time.Time) ([]service.ESTStatsSnapshot, error) {
f.profilesCalled = true
return f.rows, f.profilesErr
}
func (f *fakeAdminESTService) ReloadTrust(_ context.Context, pathID string) error {
f.reloadCalled = true
f.reloadPathID = pathID
return f.reloadErr
}
// ----- M-008 admin-gate triplet for Profiles (GET) -----
func TestAdminEST_Profiles_AdminTrue_Returns200(t *testing.T) {
svc := &fakeAdminESTService{
rows: []service.ESTStatsSnapshot{
{PathID: "corp", IssuerID: "iss-corp"},
},
}
h := NewAdminESTHandler(svc)
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/est/profiles", nil)
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
ctx = context.WithValue(ctx, auth.AdminKey{}, true)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
h.Profiles(w, req)
if w.Code != http.StatusOK {
t.Fatalf("admin status = %d, want 200; body = %q", w.Code, w.Body.String())
}
var resp map[string]any
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("decode response: %v", err)
}
if pc, _ := resp["profile_count"].(float64); int(pc) != 1 {
t.Errorf("profile_count = %v, want 1", resp["profile_count"])
}
if !svc.profilesCalled {
t.Error("service should have been called")
}
}
func TestAdminEST_Profiles_MethodNotAllowed(t *testing.T) {
svc := &fakeAdminESTService{}
h := NewAdminESTHandler(svc)
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/est/profiles", nil)
w := httptest.NewRecorder()
h.Profiles(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("POST against GET-only endpoint status = %d, want 405", w.Code)
}
}
func TestAdminEST_Profiles_NilRowsSerializedAsEmptyArray(t *testing.T) {
svc := &fakeAdminESTService{rows: nil}
h := NewAdminESTHandler(svc)
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/est/profiles", nil)
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
ctx = context.WithValue(ctx, auth.AdminKey{}, true)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
h.Profiles(w, req)
body := w.Body.String()
if strings.Contains(body, `"profiles":null`) {
t.Errorf("profiles serialised as null; want []. body=%q", body)
}
}
// ----- M-008 admin-gate triplet for ReloadTrust (POST) -----
func TestAdminEST_ReloadTrust_HappyPath(t *testing.T) {
svc := &fakeAdminESTService{}
h := NewAdminESTHandler(svc)
body := `{"path_id":"corp"}`
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/est/reload-trust",
strings.NewReader(body))
req.ContentLength = int64(len(body))
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
ctx = context.WithValue(ctx, auth.AdminKey{}, true)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
h.ReloadTrust(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %q", w.Code, w.Body.String())
}
if svc.reloadPathID != "corp" {
t.Errorf("reloadPathID = %q, want %q", svc.reloadPathID, "corp")
}
}
func TestAdminEST_ReloadTrust_UnknownPathID_Returns404(t *testing.T) {
svc := &fakeAdminESTService{reloadErr: ErrAdminESTProfileNotFound}
h := NewAdminESTHandler(svc)
body := `{"path_id":"nope"}`
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/est/reload-trust",
strings.NewReader(body))
req.ContentLength = int64(len(body))
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
ctx = context.WithValue(ctx, auth.AdminKey{}, true)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
h.ReloadTrust(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("unknown path_id status = %d, want 404", w.Code)
}
}
func TestAdminEST_ReloadTrust_MTLSDisabled_Returns409(t *testing.T) {
svc := &fakeAdminESTService{reloadErr: service.ErrESTMTLSDisabled}
h := NewAdminESTHandler(svc)
body := `{"path_id":"static-only"}`
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/est/reload-trust",
strings.NewReader(body))
req.ContentLength = int64(len(body))
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
ctx = context.WithValue(ctx, auth.AdminKey{}, true)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
h.ReloadTrust(w, req)
if w.Code != http.StatusConflict {
t.Errorf("mTLS-disabled status = %d, want 409", w.Code)
}
}
func TestAdminEST_ReloadTrust_ParseError_Returns500(t *testing.T) {
svc := &fakeAdminESTService{reloadErr: errors.New("trustanchor: cert in /etc/est-corp.pem expired at 2020-01-01")}
h := NewAdminESTHandler(svc)
body := `{"path_id":"corp"}`
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/est/reload-trust",
strings.NewReader(body))
req.ContentLength = int64(len(body))
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
ctx = context.WithValue(ctx, auth.AdminKey{}, true)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
h.ReloadTrust(w, req)
if w.Code != http.StatusInternalServerError {
t.Errorf("parse-error status = %d, want 500", w.Code)
}
}
func TestAdminEST_ReloadTrust_MalformedJSON_Returns400(t *testing.T) {
svc := &fakeAdminESTService{}
h := NewAdminESTHandler(svc)
body := `not-json`
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/est/reload-trust",
strings.NewReader(body))
req.ContentLength = int64(len(body))
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
ctx = context.WithValue(ctx, auth.AdminKey{}, true)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
h.ReloadTrust(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("malformed-JSON status = %d, want 400", w.Code)
}
if svc.reloadCalled {
t.Errorf("service called despite malformed body")
}
}
func TestAdminEST_ReloadTrust_MethodNotAllowed(t *testing.T) {
svc := &fakeAdminESTService{}
h := NewAdminESTHandler(svc)
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/est/reload-trust", nil)
w := httptest.NewRecorder()
h.ReloadTrust(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("GET against POST-only endpoint status = %d, want 405", w.Code)
}
}
// ----- AdminESTServiceImpl plumbing -----
func TestAdminESTServiceImpl_NilMapAccepted(t *testing.T) {
svc := NewAdminESTServiceImpl(nil)
rows, err := svc.Profiles(context.Background(), time.Now())
if err != nil {
t.Fatalf("Profiles: %v", err)
}
if len(rows) != 0 {
t.Errorf("nil-map should produce empty profile list; got %d", len(rows))
}
}
func TestAdminESTServiceImpl_ReloadTrust_UnknownPath_NotFound(t *testing.T) {
svc := NewAdminESTServiceImpl(map[string]*service.ESTService{})
if err := svc.ReloadTrust(context.Background(), "nonexistent"); !errors.Is(err, ErrAdminESTProfileNotFound) {
t.Errorf("unknown path_id err = %v, want ErrAdminESTProfileNotFound", err)
}
}