mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-11 16:48:51 +00:00
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:
@@ -2,18 +2,37 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/certctl-io/certctl/internal/auth"
|
||||
"github.com/certctl-io/certctl/internal/domain"
|
||||
"github.com/certctl-io/certctl/internal/repository"
|
||||
)
|
||||
|
||||
// ErrProfileEditPendingApproval (Bundle 1 Phase 9) is returned by
|
||||
// UpdateProfile when the live profile (or the proposed update) carries
|
||||
// RequiresApproval=true. The handler maps this to HTTP 202 Accepted +
|
||||
// {pending_approval_id} so the operator knows to chase a second-admin
|
||||
// approve. See docs/reference/profiles.md.
|
||||
var ErrProfileEditPendingApproval = errors.New("profile edit gated by approval workflow")
|
||||
|
||||
// ProfileEditApprovalRequester is the slice of ApprovalService the
|
||||
// ProfileService consumes when a profile edit triggers the gate.
|
||||
// Pulled out as a small interface so unit tests can drive the gate
|
||||
// without the full ApprovalService dependency tree.
|
||||
type ProfileEditApprovalRequester interface {
|
||||
RequestProfileEditApproval(ctx context.Context, profileID, requestedBy string, payload []byte) (string, error)
|
||||
}
|
||||
|
||||
// ProfileService provides business logic for certificate profile management.
|
||||
type ProfileService struct {
|
||||
profileRepo repository.CertificateProfileRepository
|
||||
auditService *AuditService
|
||||
profileRepo repository.CertificateProfileRepository
|
||||
auditService *AuditService
|
||||
approvalService ProfileEditApprovalRequester // Bundle 1 Phase 9; nil disables the gate
|
||||
}
|
||||
|
||||
// NewProfileService creates a new profile service.
|
||||
@@ -27,6 +46,14 @@ func NewProfileService(
|
||||
}
|
||||
}
|
||||
|
||||
// SetApprovalService wires the Bundle 1 Phase 9 gate. cmd/server/main.go
|
||||
// calls this after both ProfileService and ApprovalService are
|
||||
// constructed. nil disables the gate (preserving pre-Phase-9 behaviour
|
||||
// for any test fixture or alternate boot path that doesn't wire it).
|
||||
func (s *ProfileService) SetApprovalService(a ProfileEditApprovalRequester) {
|
||||
s.approvalService = a
|
||||
}
|
||||
|
||||
// ListProfiles returns all profiles (handler interface method).
|
||||
func (s *ProfileService) ListProfiles(ctx context.Context, page, perPage int) ([]domain.CertificateProfile, int64, error) {
|
||||
// Bundle E / Audit L-020: page/perPage are unused; the underlying repo
|
||||
@@ -97,12 +124,59 @@ func (s *ProfileService) CreateProfile(ctx context.Context, profile domain.Certi
|
||||
}
|
||||
|
||||
// UpdateProfile modifies an existing profile (handler interface method).
|
||||
//
|
||||
// Bundle 1 Phase 9 (approval-bypass closure): if the LIVE profile has
|
||||
// RequiresApproval=true OR the proposed update would set it true, the
|
||||
// edit is NOT applied directly. Instead it is serialized to a pending
|
||||
// ApprovalRequest with Kind=profile_edit and the caller receives
|
||||
// ErrProfileEditPendingApproval. The handler maps this to HTTP 202 +
|
||||
// the new approval ID. A non-requester admin then approves via the
|
||||
// existing /v1/approvals/{id}/approve endpoint, which deserializes
|
||||
// the payload and persists the diff via the profile-edit-apply
|
||||
// callback registered in main.go. This closes the flip-flop loophole
|
||||
// where an admin could disable RequiresApproval, mutate, re-enable.
|
||||
//
|
||||
// SetApprovalService(nil) disables the gate (test fixtures); the
|
||||
// pre-Phase-9 direct-apply path is preserved.
|
||||
func (s *ProfileService) UpdateProfile(ctx context.Context, id string, profile domain.CertificateProfile) (*domain.CertificateProfile, error) {
|
||||
if err := validateProfile(&profile); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
profile.ID = id
|
||||
|
||||
if s.approvalService != nil {
|
||||
live, err := s.profileRepo.Get(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load live profile: %w", err)
|
||||
}
|
||||
// Gate when the live profile is approval-tier OR the edit
|
||||
// would flip it on. Both arms close the loophole: a flip-
|
||||
// flop attacker can't set false→mutate→true because every
|
||||
// transition through an approval-tier profile triggers the
|
||||
// gate.
|
||||
if (live != nil && live.RequiresApproval) || profile.RequiresApproval {
|
||||
payload, perr := json.Marshal(profile)
|
||||
if perr != nil {
|
||||
return nil, fmt.Errorf("marshal profile for approval payload: %w", perr)
|
||||
}
|
||||
requester := actorFromContext(ctx)
|
||||
approvalID, gerr := s.approvalService.RequestProfileEditApproval(ctx, id, requester, payload)
|
||||
if gerr != nil {
|
||||
return nil, fmt.Errorf("approval gate: %w", gerr)
|
||||
}
|
||||
if s.auditService != nil {
|
||||
_ = s.auditService.RecordEventWithCategory(
|
||||
context.WithoutCancel(ctx),
|
||||
requester, domain.ActorTypeUser,
|
||||
"profile.edit_request", domain.EventCategoryAuth,
|
||||
"certificate_profile", id,
|
||||
map[string]interface{}{"approval_id": approvalID},
|
||||
)
|
||||
}
|
||||
return nil, fmt.Errorf("%w: approval=%s", ErrProfileEditPendingApproval, approvalID)
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.profileRepo.Update(ctx, &profile); err != nil {
|
||||
return nil, fmt.Errorf("failed to update profile: %w", err)
|
||||
}
|
||||
@@ -117,6 +191,23 @@ func (s *ProfileService) UpdateProfile(ctx context.Context, id string, profile d
|
||||
return &profile, nil
|
||||
}
|
||||
|
||||
// actorFromContext pulls the caller's actor ID from the
|
||||
// auth-middleware ActorIDKey populated by NewAuthWithKeyStore /
|
||||
// NewDemoModeAuth. Falls back to "api" so legacy test fixtures that
|
||||
// don't wire the auth context still record meaningful audit rows.
|
||||
func actorFromContext(ctx context.Context) string {
|
||||
if ctx == nil {
|
||||
return "api"
|
||||
}
|
||||
if id := auth.GetActorID(ctx); id != "" {
|
||||
return id
|
||||
}
|
||||
if id, ok := ctx.Value(auth.UserKey{}).(string); ok && id != "" {
|
||||
return id
|
||||
}
|
||||
return "api"
|
||||
}
|
||||
|
||||
// DeleteProfile removes a profile (handler interface method).
|
||||
func (s *ProfileService) DeleteProfile(ctx context.Context, id string) error {
|
||||
if err := s.profileRepo.Delete(ctx, id); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user