Files
certctl/web/src/pages/auth/RolesPage.test.tsx
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

172 lines
5.7 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MemoryRouter } from 'react-router-dom';
import type { ReactNode } from 'react';
// =============================================================================
// Bundle 1 Phase 10 — RolesPage Vitest coverage. Pins:
// - List renders when authListRoles resolves.
// - Empty state renders when the list is empty.
// - "Create role" button is HIDDEN when the caller lacks
// auth.role.create. Server-side enforcement is the load-bearing
// gate; this test pins the UX hide.
// - "Create role" button is SHOWN when the caller has the perm.
// - Submitting the create modal calls authCreateRole.
// - Error state renders when authListRoles rejects.
// =============================================================================
vi.mock('../../api/client', () => ({
authListRoles: vi.fn(),
authCreateRole: vi.fn(),
authMe: vi.fn(),
}));
import RolesPage from './RolesPage';
import * as client from '../../api/client';
function renderWithProviders(ui: ReactNode) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
return render(
<QueryClientProvider client={queryClient}>
<MemoryRouter>{ui}</MemoryRouter>
</QueryClientProvider>,
);
}
beforeEach(() => {
vi.clearAllMocks();
cleanup();
});
const sampleRoles = [
{ id: 'r-admin', tenant_id: 't-default', name: 'admin', description: 'Full access' },
{ id: 'r-viewer', tenant_id: 't-default', name: 'viewer', description: 'Read-only' },
];
describe('RolesPage', () => {
it('renders the role list from authListRoles', async () => {
vi.mocked(client.authListRoles).mockResolvedValue(sampleRoles);
vi.mocked(client.authMe).mockResolvedValue({
actor_id: 'alice',
actor_type: 'APIKey',
tenant_id: 't-default',
admin: true,
roles: ['r-admin'],
effective_permissions: [{ permission: 'auth.role.create', scope_type: 'global' }],
});
renderWithProviders(<RolesPage />);
await waitFor(() => {
expect(screen.getByTestId('roles-table')).toBeTruthy();
});
expect(screen.getByText('admin')).toBeTruthy();
expect(screen.getByText('viewer')).toBeTruthy();
});
it('shows the create button when the caller has auth.role.create', async () => {
vi.mocked(client.authListRoles).mockResolvedValue([]);
vi.mocked(client.authMe).mockResolvedValue({
actor_id: 'alice',
actor_type: 'APIKey',
tenant_id: 't-default',
admin: false,
roles: ['r-operator'],
effective_permissions: [{ permission: 'auth.role.create', scope_type: 'global' }],
});
renderWithProviders(<RolesPage />);
await waitFor(() => {
expect(screen.queryByTestId('roles-create-button')).toBeTruthy();
});
});
it('hides the create button when the caller lacks auth.role.create', async () => {
vi.mocked(client.authListRoles).mockResolvedValue([]);
vi.mocked(client.authMe).mockResolvedValue({
actor_id: 'audrey',
actor_type: 'APIKey',
tenant_id: 't-default',
admin: false,
roles: ['r-auditor'],
effective_permissions: [{ permission: 'audit.read', scope_type: 'global' }],
});
renderWithProviders(<RolesPage />);
await waitFor(() => expect(screen.getByTestId('roles-empty')).toBeTruthy());
expect(screen.queryByTestId('roles-create-button')).toBeNull();
});
it('renders the empty state when the list is empty', async () => {
vi.mocked(client.authListRoles).mockResolvedValue([]);
vi.mocked(client.authMe).mockResolvedValue({
actor_id: 'alice',
actor_type: 'APIKey',
tenant_id: 't-default',
admin: true,
roles: ['r-admin'],
effective_permissions: [],
});
renderWithProviders(<RolesPage />);
await waitFor(() => expect(screen.getByTestId('roles-empty')).toBeTruthy());
});
it('submits the create modal via authCreateRole', async () => {
vi.mocked(client.authListRoles).mockResolvedValue([]);
vi.mocked(client.authCreateRole).mockResolvedValue({
id: 'r-release',
tenant_id: 't-default',
name: 'release-manager',
});
vi.mocked(client.authMe).mockResolvedValue({
actor_id: 'alice',
actor_type: 'APIKey',
tenant_id: 't-default',
admin: true,
roles: ['r-admin'],
effective_permissions: [{ permission: 'auth.role.create', scope_type: 'global' }],
});
renderWithProviders(<RolesPage />);
await waitFor(() => screen.getByTestId('roles-create-button'));
fireEvent.click(screen.getByTestId('roles-create-button'));
await waitFor(() => screen.getByTestId('create-role-modal'));
fireEvent.change(screen.getByTestId('create-role-name'), {
target: { value: 'release-manager' },
});
fireEvent.change(screen.getByTestId('create-role-description'), {
target: { value: 'Cuts releases' },
});
fireEvent.click(screen.getByTestId('create-role-submit'));
await waitFor(() => {
expect(client.authCreateRole).toHaveBeenCalledWith({
name: 'release-manager',
description: 'Cuts releases',
});
});
});
it('renders the error state when authListRoles rejects', async () => {
vi.mocked(client.authListRoles).mockRejectedValue(new Error('boom'));
vi.mocked(client.authMe).mockResolvedValue({
actor_id: 'alice',
actor_type: 'APIKey',
tenant_id: 't-default',
admin: true,
roles: ['r-admin'],
effective_permissions: [],
});
renderWithProviders(<RolesPage />);
await waitFor(() => expect(screen.getByText(/failed to load/i)).toBeTruthy());
});
});