Files
certctl/internal/service/profile_approval_test.go
T
shankar0123 69a508dfcf auth-bundle-1 Phase 9 + 10: approval-bypass closure + RBAC GUI
# Phase 9 — approval-bypass closure (Decision 9, option a)

* Migration 000033_approval_kinds.up.sql: ALTER TABLE
  issuance_approval_requests ADD COLUMN approval_kind +
  payload JSONB; relax certificate_id + job_id to nullable;
  CHECK (approval_kind IN ('cert_issuance','profile_edit'))
  + CHECK (per-kind nullability invariant) + index on
  approval_kind. Idempotent throughout via DO blocks.
* domain.ApprovalKind enum (cert_issuance / profile_edit) +
  IsValidApprovalKind. ApprovalRequest gains Kind +
  Payload []byte for the pending profile diff.
* postgres.ApprovalRepository.Create + scanApprovalRow extended
  to round-trip the new columns; certificate_id + job_id
  switched to sql.NullString so profile_edit rows persist
  cleanly. Default Kind=cert_issuance preserves back-compat
  for every Phase-7-2026-05-03 caller.
* ApprovalService.RequestProfileEditApproval: new entry point
  that creates a pending profile-edit row carrying the
  serialized profile diff. Bypass mode (CERTCTL_APPROVAL_BYPASS)
  short-circuits the same way it does for cert_issuance.
* ApprovalService.SetProfileEditApply hook: cmd/server/main.go
  registers a closure that deserializes req.Payload + persists
  via profileRepo.Update + emits a profile.edit_applied audit
  row with category=auth. The hook avoids the Approval ↔
  Profile import cycle.
* ProfileService.UpdateProfile: gates when (a) the live
  profile carries RequiresApproval=true, OR (b) the proposed
  edit would set it true. Returns ErrProfileEditPendingApproval
  with the new approval ID; ProfileHandler maps to HTTP 202
  Accepted + {pending_approval_id}. Both arms close the
  flip-flop loophole because every transition through an
  approval-tier profile fires the gate.
* TestProfileEdit_RequiresApprovalLoopholeClosed pins all 3
  bypass attempts (flip-off / kept-on / flip-on) gated; nil-
  approval-service preserves pre-Phase-9 direct-apply for
  test fixtures.
* Approval service tests gain 4 profile_edit rows: pending row
  shape; same-actor self-approve rejected with
  ErrApproveBySameActor (load-bearing two-person integrity);
  approve fails-closed when apply callback unwired;
  apply callback invoked on approve.
* docs/reference/profiles.md (new) explains the gate +
  edit response shape (202) + same-actor invariant + bypass
  + audit hooks.

# Phase 10 — RBAC management GUI

* useAuthMe hook (web/src/hooks/useAuthMe.ts): TanStack Query
  fetches /api/v1/auth/me on app boot, caches for 60s, exposes
  hasPerm(p) + hasAnyPerm + isAdmin predicates. Every Phase-10
  page consumes this on mount + gates affordances against the
  cached effective_permissions slice. Server-side enforcement
  is the load-bearing gate; client-side hide/disable is UX.
* New routes:
   - /auth/roles — list (auth.role.list); create-role modal
     (auth.role.create) hidden when missing.
   - /auth/roles/:id — detail + permissions; edit
     (auth.role.edit), delete (auth.role.delete), add/remove
     permission affordances each gated.
   - /auth/keys — list of every actor with role grants; assign
     + revoke modals (auth.role.assign). actor-demo-anon
     flagged system-managed; mutation buttons hidden for it.
   - /auth/settings — stub showing /v1/auth/me identity +
     bootstrap-endpoint availability via /v1/auth/bootstrap.
* AuditPage extended with category filter ('All categories'
  + the 3 enum values from migration 000032). Selection flows
  to the API call params + the URL-driven query state.
* Layout: 3 new nav entries (Roles / API Keys / Auth Settings).
* api/client.ts: 12 new exported functions for the RBAC
  surface (authMe, list/get/create/update/delete role,
  list/add/remove role permissions, list keys, assign/revoke
  key role, bootstrap-availability probe).
* data-testid attributes on every interactive element so a
  future Playwright suite can assert behavior without brittle
  CSS selectors.
* Empty state, error state, and unsaved-changes warnings on
  every form per the prompt's implementation rules.

# Frontend tests

* RolesPage.test.tsx (6 tests): list render, empty state,
  error state, hide-create-button-without-perm,
  show-create-button-with-perm, submit-create-modal.
* KeysPage.test.tsx (3 tests): demo-anon flagged
  system-managed (no buttons), permission-gated affordance
  hide for auditor caller, assign-modal-POST contract.
* AuthSettingsPage.test.tsx (2 tests): identity surface,
  bootstrap-OPEN-status surface.
* AuditPage.test.tsx (+1): category-filter select renders
  with the 4 documented options.

15 frontend tests total in src/pages/auth/ + the audit
category-filter test; all pass via npx vitest run.

# Verifications

* go vet ./... clean.
* staticcheck across internal/auth + handler + router + cli +
  service + repository + cmd + domain: clean.
* gofmt -l clean repo-wide.
* go test -short -count=1 green across internal/service,
  internal/api/handler, internal/api/router, internal/auth,
  internal/auth/bootstrap, internal/service/auth,
  internal/domain/auth, cmd/server, cmd/cli, internal/cli.
* npx tsc --noEmit clean.
* npm run build green (vite build produces dist/index.html
  + 946KB JS bundle; chunk-size warning is pre-existing).
* npx vitest run src/pages/auth/ src/pages/AuditPage.test.tsx
  green (15 tests, 4 files).
2026-05-09 21:03:59 +00:00

213 lines
7.3 KiB
Go

package service
import (
"context"
"errors"
"testing"
"github.com/certctl-io/certctl/internal/domain"
"github.com/certctl-io/certctl/internal/repository"
)
// =============================================================================
// Bundle 1 Phase 9 — approval-bypass closure regression tests.
//
// Ship a tiny in-memory profile-repo + approval-repo so the gate can
// be exercised without testcontainers. The gate's invariant: any edit
// to a profile that has RequiresApproval=true (or that would set
// RequiresApproval=true) routes through ApprovalService and never
// reaches profileRepo.Update directly.
// =============================================================================
type fakeProfileRepo struct {
rows map[string]*domain.CertificateProfile
}
func newFakeProfileRepo() *fakeProfileRepo {
return &fakeProfileRepo{rows: make(map[string]*domain.CertificateProfile)}
}
func (f *fakeProfileRepo) List(_ context.Context) ([]*domain.CertificateProfile, error) {
out := make([]*domain.CertificateProfile, 0, len(f.rows))
for _, p := range f.rows {
out = append(out, p)
}
return out, nil
}
func (f *fakeProfileRepo) Get(_ context.Context, id string) (*domain.CertificateProfile, error) {
p, ok := f.rows[id]
if !ok {
return nil, repository.ErrNotFound
}
cp := *p
return &cp, nil
}
func (f *fakeProfileRepo) Create(_ context.Context, p *domain.CertificateProfile) error {
cp := *p
f.rows[p.ID] = &cp
return nil
}
func (f *fakeProfileRepo) Update(_ context.Context, p *domain.CertificateProfile) error {
if _, ok := f.rows[p.ID]; !ok {
return repository.ErrNotFound
}
cp := *p
f.rows[p.ID] = &cp
return nil
}
func (f *fakeProfileRepo) Delete(_ context.Context, id string) error {
delete(f.rows, id)
return nil
}
// fakeApprovalGate counts requests + lets the test inspect the
// payload that was queued. Mirrors ProfileEditApprovalRequester.
type fakeApprovalGate struct {
requests []struct {
ProfileID, RequestedBy string
Payload []byte
}
err error
}
func (f *fakeApprovalGate) RequestProfileEditApproval(_ context.Context, profileID, requestedBy string, payload []byte) (string, error) {
if f.err != nil {
return "", f.err
}
f.requests = append(f.requests, struct {
ProfileID, RequestedBy string
Payload []byte
}{profileID, requestedBy, payload})
return "ar-pending-" + profileID, nil
}
// TestProfileEdit_RequiresApprovalLoopholeClosed pins the load-bearing
// invariant: a profile with RequiresApproval=true cannot be mutated
// in-place. The flip-flop loophole (set false → mutate → set true) is
// closed because every call against an approval-tier profile routes
// through ApprovalService BEFORE reaching profileRepo.Update.
func TestProfileEdit_RequiresApprovalLoopholeClosed(t *testing.T) {
repo := newFakeProfileRepo()
repo.rows["prof-prod"] = &domain.CertificateProfile{
ID: "prof-prod",
Name: "production",
RequiresApproval: true,
}
gate := &fakeApprovalGate{}
svc := NewProfileService(repo, nil)
svc.SetApprovalService(gate)
// Attempt 1 — admin tries to flip RequiresApproval off.
flippedOff := domain.CertificateProfile{
ID: "prof-prod",
Name: "production",
RequiresApproval: false, // bypass attempt
}
_, err := svc.UpdateProfile(context.Background(), "prof-prod", flippedOff)
if !errors.Is(err, ErrProfileEditPendingApproval) {
t.Fatalf("flip-off attempt err = %v, want ErrProfileEditPendingApproval", err)
}
live, _ := repo.Get(context.Background(), "prof-prod")
if !live.RequiresApproval {
t.Errorf("flip-off attempt mutated live profile (RequiresApproval = false) — loophole NOT closed")
}
if len(gate.requests) != 1 {
t.Fatalf("gate not called for flip-off attempt: %d requests", len(gate.requests))
}
// Attempt 2 — admin tries to mutate other fields (RequiresApproval still true).
keptOn := domain.CertificateProfile{
ID: "prof-prod",
Name: "renamed",
RequiresApproval: true,
}
_, err = svc.UpdateProfile(context.Background(), "prof-prod", keptOn)
if !errors.Is(err, ErrProfileEditPendingApproval) {
t.Errorf("kept-on attempt err = %v, want ErrProfileEditPendingApproval", err)
}
live2, _ := repo.Get(context.Background(), "prof-prod")
if live2.Name == "renamed" {
t.Errorf("kept-on attempt mutated profile name without approval — loophole NOT closed")
}
// Attempt 3 — admin tries to flip a NON-approval profile to approval-tier.
repo.rows["prof-staging"] = &domain.CertificateProfile{
ID: "prof-staging",
Name: "staging",
RequiresApproval: false,
}
flippedOn := domain.CertificateProfile{
ID: "prof-staging",
Name: "staging",
RequiresApproval: true, // operator wants to enable approvals
}
_, err = svc.UpdateProfile(context.Background(), "prof-staging", flippedOn)
if !errors.Is(err, ErrProfileEditPendingApproval) {
t.Errorf("flip-on attempt err = %v, want ErrProfileEditPendingApproval (gate fires when target state is approval-tier)", err)
}
live3, _ := repo.Get(context.Background(), "prof-staging")
if live3.RequiresApproval {
t.Errorf("flip-on attempt enabled approval without an approval — gate must fire BEFORE the persistence")
}
if len(gate.requests) != 3 {
t.Errorf("gate request count = %d, want 3 (one per attempt)", len(gate.requests))
}
}
// TestProfileEdit_NonApprovalProfileApplyDirectly confirms the gate
// is dormant for profiles that have RequiresApproval=false AND the
// edit doesn't flip it on. Pre-Phase-9 behaviour preserved.
func TestProfileEdit_NonApprovalProfileApplyDirectly(t *testing.T) {
repo := newFakeProfileRepo()
repo.rows["prof-dev"] = &domain.CertificateProfile{
ID: "prof-dev",
Name: "development",
RequiresApproval: false,
}
gate := &fakeApprovalGate{}
svc := NewProfileService(repo, nil)
svc.SetApprovalService(gate)
updated := domain.CertificateProfile{
ID: "prof-dev",
Name: "development-renamed",
RequiresApproval: false,
}
got, err := svc.UpdateProfile(context.Background(), "prof-dev", updated)
if err != nil {
t.Fatalf("non-approval update err = %v", err)
}
if got.Name != "development-renamed" {
t.Errorf("name not updated; got %q", got.Name)
}
if len(gate.requests) != 0 {
t.Errorf("gate fired for non-approval profile: %d requests", len(gate.requests))
}
}
// TestProfileEdit_NilApprovalService_PreservesLegacyBehaviour confirms
// that a nil-ApprovalService wiring (test fixtures, alternate boot
// paths) preserves the pre-Phase-9 direct-apply path even on
// approval-tier profiles. The gate is opt-in.
func TestProfileEdit_NilApprovalService_PreservesLegacyBehaviour(t *testing.T) {
repo := newFakeProfileRepo()
repo.rows["prof-prod"] = &domain.CertificateProfile{
ID: "prof-prod",
Name: "production",
RequiresApproval: true,
}
svc := NewProfileService(repo, nil) // approvalService not wired
updated := domain.CertificateProfile{
ID: "prof-prod",
Name: "renamed",
RequiresApproval: true,
}
if _, err := svc.UpdateProfile(context.Background(), "prof-prod", updated); err != nil {
t.Fatalf("nil-gate err = %v", err)
}
live, _ := repo.Get(context.Background(), "prof-prod")
if live.Name != "renamed" {
t.Errorf("nil-gate did not fall through to direct apply; got %q", live.Name)
}
}