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).
This commit is contained in:
shankar0123
2026-05-09 21:03:59 +00:00
parent af4fa12724
commit 69a508dfcf
24 changed files with 2413 additions and 29 deletions
+91
View File
@@ -39,6 +39,25 @@ type ApprovalService struct {
metrics *ApprovalMetrics
bypassEnabled bool
// profileEditApply is the Bundle 1 Phase 9 hook the approve
// path invokes when req.Kind=profile_edit. Registered by
// cmd/server/main.go via SetProfileEditApply so the service
// doesn't import internal/service/profile.go (would create a
// cycle: ApprovalService -> ProfileService -> ApprovalService).
profileEditApply ProfileEditApplyFunc
}
// ProfileEditApplyFunc deserializes the pending profile diff stored
// in req.Payload and persists it via the profile repository. The
// caller registers this once at boot via SetProfileEditApply.
type ProfileEditApplyFunc func(ctx context.Context, req *domain.ApprovalRequest) error
// SetProfileEditApply registers the profile-edit apply callback. Called
// from main.go after both the ApprovalService and ProfileService are
// constructed; the closure captures the profile repo + audit service.
func (s *ApprovalService) SetProfileEditApply(f ProfileEditApplyFunc) {
s.profileEditApply = f
}
// JobStatusUpdater is the narrow interface ApprovalService depends on
@@ -139,6 +158,53 @@ func (s *ApprovalService) RequestApproval(
return req.ID, nil
}
// RequestProfileEditApproval is the Bundle 1 Phase 9 entry point for
// gated profile mutations. ProfileService.UpdateProfile calls this
// when the live profile (or the proposed update) carries
// RequiresApproval=true. Returns the new pending approval ID.
//
// The pending diff is serialized to req.Payload as JSON; the
// profile-edit-apply callback (registered by main.go) deserializes
// and persists when an approver decides.
//
// In bypass mode (CERTCTL_APPROVAL_BYPASS=true) the call short-
// circuits via approveInternal — the same dev/CI escape hatch as
// cert_issuance — so renewal-loop tests remain fast.
func (s *ApprovalService) RequestProfileEditApproval(
ctx context.Context,
profileID, requestedBy string,
payload []byte,
) (string, error) {
if profileID == "" || requestedBy == "" {
return "", fmt.Errorf("approval: profileID + requestedBy required")
}
if len(payload) == 0 {
return "", fmt.Errorf("approval: payload required for profile_edit")
}
now := time.Now().UTC()
req := &domain.ApprovalRequest{
Kind: domain.ApprovalKindProfileEdit,
ProfileID: profileID,
RequestedBy: requestedBy,
State: domain.ApprovalStatePending,
Payload: payload,
CreatedAt: now,
UpdatedAt: now,
}
if err := s.approvalRepo.Create(ctx, req); err != nil {
return "", fmt.Errorf("approval: create profile_edit request: %w", err)
}
s.recordAudit(ctx, requestedBy, domain.ActorTypeUser, "approval_profile_edit_requested", req, nil)
if s.bypassEnabled {
if err := s.approveInternal(ctx, req.ID, domain.ApprovalActorSystemBypass,
"auto-approved by CERTCTL_APPROVAL_BYPASS — dev/CI mode",
domain.ApprovalOutcomeBypassed, domain.ActorTypeSystem); err != nil {
return req.ID, fmt.Errorf("approval: bypass auto-approve profile_edit: %w", err)
}
}
return req.ID, nil
}
// Approve transitions a pending request to approved AND the linked Job
// from AwaitingApproval to Pending so the job processor picks it up.
// RBAC: rejects if decidedBy == request.RequestedBy.
@@ -194,6 +260,31 @@ func (s *ApprovalService) approveInternal(
return fmt.Errorf("approval: update state to approved: %w", err)
}
// Bundle 1 Phase 9: profile_edit kind requires the apply
// callback to deserialize req.Payload + persist the profile
// diff. cert_issuance kind continues through the existing job-
// transition path. The kind discriminator is the load-bearing
// dispatch — adding a future ApprovalKind goes here.
if req.Kind == domain.ApprovalKindProfileEdit {
if s.profileEditApply == nil {
s.recordAudit(ctx, decidedBy, actorType, "approval_profile_apply_missing", req,
map[string]interface{}{"error": "profileEditApply callback not wired"})
return fmt.Errorf("approval: profile-edit apply callback not registered")
}
if err := s.profileEditApply(ctx, req); err != nil {
s.recordAudit(ctx, decidedBy, actorType, "approval_profile_apply_failed", req,
map[string]interface{}{"error": err.Error()})
return fmt.Errorf("approval: apply profile edit: %w", err)
}
s.recordAudit(ctx, decidedBy, actorType, "approval_"+outcome, req,
map[string]interface{}{"note": note, "outcome": outcome, "kind": string(req.Kind)})
if s.metrics != nil {
s.metrics.RecordDecision(outcome, req.ProfileID)
s.metrics.ObservePendingAge(now.Sub(req.CreatedAt).Seconds())
}
return nil
}
// Transition the linked Job from AwaitingApproval to Pending so the
// scheduler picks it up. Best-effort — if the Job has already been
// cancelled or otherwise mutated externally, log via audit and move on.