Skip to content

feat(frontend): role-based access control UI — page guards, Users, API Tokens, Access Control #29

Open

Description

@SckyzO

feat(frontend): role-based access control UI — page guards, Users panel, API Tokens panel, role overrides

Context

This issue is the frontend counterpart of Issue C1 (backend RBAC) and Issue B (API tokens). Once the backend exposes user roles via GET /api/auth/me and CRUD endpoints under /api/auth/users and /api/auth/api-tokens, the React app must:

  1. Hide UI surfaces that the current user's role does not allow.
  2. Adapt navigation so viewers do not see editor menu items, editors do not see Settings.
  3. Provide admin UI to manage users.
  4. Provide admin UI to manage API tokens (NetBox / BlueBanquise / DCIM integrations).
  5. Provide admin UI for the three role override toggles.

Design Principles

  1. Defense in depth: the frontend hides UI, but the backend enforces. A viewer who hand-crafts a POST /api/sites request via curl is still rejected by require_role(Role.EDITOR) server-side. The frontend guards are UX, not security.
  2. Easter eggs accessible to all roles: the Konami code, 'toulouse'/'help'/'matrix' text triggers, Matrix rain palette, etc. (cf. audit AP-05 reframing) MUST remain available to viewers and editors. They are a feature of the product identity, not gated content.
  3. No new design system primitives invented: every UI uses existing components (PageHeader, SectionCard, Modal, Tabs, FormRow, ToggleSwitch, EmptyState, ConfirmationModal, SkeletonTable). Follow the conventions documented in Issue refactor(frontend): audit & standardize component usage across all pages #21 / MaintenancesPage.tsx reference.
  4. Cosmos forward-compat (cf. audit): every new component added here should be designed so the future migration to @sckyzo/cosmos-react lifts it as-is. No tight coupling to ad-hoc components.

Role Capability Matrix (UI-side)

Surface viewer editor admin
Dashboard ✅ ✅ ✅
WorldMap ✅ ✅ ✅
Site/Room/Aisle/Rack/Device views (read) ✅ ✅ ✅
About + Easter Eggs ✅ ✅ ✅
Cluster page ✅ ✅ ✅
Notifications ✅ ✅ ✅
Maintenances ✅ ✅ ✅
Topology editor ❌ ✅ ✅
Datacenter editor ❌ ✅ ✅
Rack editor ❌ ✅ ✅
Templates editor (depends on viewer_can_read_inventory) ✅ ✅
Checks editor ❌ ✅ ✅
Metrics editor (depends on viewer_can_read_metrics_config) ✅ ✅
Rack templates editor ❌ ✅ ✅
Slurm pages (alerts, nodes, partitions, wall) ✅ ✅ ✅
Logs ❌ (depends on editor_can_read_logs) ✅
Settings ❌ ❌ ✅
Settings > Users ❌ ❌ ✅
Settings > API Tokens ❌ ❌ ✅
Settings > Access Control (overrides) ❌ ❌ ✅

Frontend Changes

New module: frontend/src/app/auth/

frontend/src/app/auth/
├── AuthContext.tsx          # session, role, overrides, user-friendly helpers
├── useAuth.ts               # hook exposing { user, role, can, isAdmin, ... }
├── useRoleGuard.ts          # hook for page-level redirect when role insufficient
├── RoleGate.tsx             # component wrapping any element with a role check
└── roleCapabilities.ts      # pure mapping role + overrides → effective permissions

useAuth API

const { user, role, overrides, can, isAdmin, isEditor, isViewer } = useAuth();

// Examples:
can('edit:topology')           // true for editor/admin
can('read:templates')           // true for editor/admin, viewer iff override on
can('access:logs')              // true for admin, editor iff override on
can('access:settings')          // true for admin only

Capability strings are an internal frontend abstraction — they map to role + override evaluation. They never appear in API calls (the backend uses roles, not capabilities).

Navigation adaptation (AppSidebar.tsx, AppTopBar.tsx)

  • Items map declaratively to capabilities:
    const NAV_ITEMS = [
      { label: 'Dashboard',         path: '/',          capability: null },           // always
      { label: 'Topology editor',   path: '/topology',  capability: 'edit:topology' },
      { label: 'Templates',         path: '/templates', capability: 'read:templates' },
      { label: 'Logs',              path: '/logs',      capability: 'access:logs' },
      { label: 'Settings',          path: '/settings',  capability: 'access:settings' },
    ];
  • Filter NAV_ITEMS.filter(i => i.capability === null || can(i.capability)).

Page guards (replace ad-hoc checks)

Every page that requires a role wraps its export with the existing route component pattern + the new useRoleGuard:

// pages/editors/TopologyEditorPage.tsx
export default function TopologyEditorPage() {
  useRoleGuard('edit:topology');   // redirects to /not-authorized if not satisfied
  // ... rest of the page
}

Or for inline gating inside a page (e.g., hide an action button):

<RoleGate capability="edit:topology">
  <PageActionButton variant="primary">Add device</PageActionButton>
</RoleGate>

New page: /not-authorized

Simple page using EmptyState to communicate "Your role does not allow access to this section. Contact your admin if you believe this is wrong." with a "Back to Dashboard" CTA.

New panel: Settings > Users

Path: /settings/users, admin only.

UI structure:

  • PageHeader "User accounts"
  • SectionCard "Local users"
    • [+ New user] PageActionButton (top right)
    • Table:
      • Columns: username, role (pill: viewer=blue, editor=amber, admin=red), created, last login, actions
      • Action: [Reset password], [Change role], [Delete]
      • Delete on the last admin is disabled with a tooltip explaining why
  • [+ New user] opens Modal with form:
    • FormRow username (validated [a-zA-Z0-9_-]{3,32}, hint about case-sensitivity)
    • FormRow initial password (with password policy hints)
    • FormRow role (SegmentedControl viewer / editor / admin)
    • On submit: POST /api/auth/users, close modal, refresh list

Loading state: SkeletonTable (not LoadingState, per audit Issue #21 conventions).
Empty state: EmptyState with "No additional users yet. Add a user to share Rackscope access."

New panel: Settings > API Tokens

Path: /settings/api-tokens, admin only.

UI structure:

  • PageHeader "API tokens" with description "Tokens for external integrations (NetBox, BlueBanquise, ...)."
  • SectionCard "Active tokens"
    • [+ Create token] PageActionButton (top right)
    • Table:
      • Columns: name, role (pill), created, last used (relative time), expires, actions
      • Action: [Revoke] (red), opens ConfirmationModal
  • [+ Create token] opens Modal with form:
    • FormRow name (validated [a-zA-Z0-9_-]{3,64}, placeholder examples: netbox-sync, bluebanquise-inventory)
    • FormRow role (SegmentedControl viewer / editor / admin) — hint: "Use editor for DCIM sync tools."
    • FormRow expires_at (DatePicker, optional, default empty = no expiry)
  • On submit: POST /api/auth/api-tokens returns the plain token, modal switches to "save now" state:
    • Big AlertBanner (warning variant): "Save this token immediately. You will not be able to see it again."
    • Read-only input with the rsk_xxx token + copy-to-clipboard button
    • [Done] button closes modal and refreshes list

New panel: Settings > Access Control

Path: /settings/access-control, admin only.

UI structure:

  • PageHeader "Access control"
  • SectionCard "Role overrides"
    • Description: "These options expand the default read access of viewer and editor roles. They are disabled by default — only enable if your deployment needs them."
    • Three FormRow rows, each with ToggleSwitch:
      • "Viewers can read inventory (templates, devices)" — corresponds to viewer_can_read_inventory
      • "Viewers can read metrics configuration" — corresponds to viewer_can_read_metrics_config
      • "Editors can access logs" — corresponds to editor_can_read_logs
    • Persisted via PUT /api/auth/access-control (or wherever Issue C1 places it — to be aligned during implementation)

Header changes (AppTopBar.tsx)

  • Show username + role pill next to the avatar
  • "Sign out" item remains
  • Role pill colour code: viewer (blue), editor (amber), admin (red), consistent across all surfaces

Easter Egg Compatibility

The Konami code, 'toulouse'/'help'/'matrix' text triggers, Matrix rain palette, ASCII boot overlay, and EasterEggsModal in AboutPage MUST remain accessible to all three roles. Implementation: do not put any of these behind a useRoleGuard or RoleGate. The AboutPage itself is unrestricted (all roles). The text trigger listeners in AppSidebar.tsx are unconditional.

Add an explicit test case (see test plan) to prevent a future PR from accidentally gating them.

Test Plan

Unit tests (Vitest, frontend/src/**/__tests__/)

  • roleCapabilities.test.ts: viewer + no overrides → can't access templates / metrics / logs / settings
  • roleCapabilities.test.ts: viewer + viewer_can_read_inventory=true → can read templates
  • roleCapabilities.test.ts: editor + editor_can_read_logs=true → can access logs
  • roleCapabilities.test.ts: admin → can do everything regardless of overrides
  • useAuth.test.tsx: isAdmin, isEditor, isViewer helpers return correctly for each role

Component tests

  • RoleGate renders children when capability allowed
  • RoleGate renders nothing (or fallback) when capability denied
  • AppSidebar filters nav items based on role
  • AppTopBar shows the correct role pill for each role

E2E tests (Playwright, if infra exists — otherwise integration tests with MemoryRouter)

  • Login as viewer → URL /topology redirects to /not-authorized
  • Login as editor → URL /settings redirects to /not-authorized
  • Login as admin → all surfaces accessible
  • Login as admin → create user (bob, editor), log out, log in as bob, verify editor surfaces visible and admin surfaces hidden
  • Login as admin → enable viewer_can_read_inventory, log out, log in as a viewer → templates page now reachable
  • Login as any role → Konami code unlocks easter egg modal (regression test for "easter eggs survive RBAC")
  • Login as viewer → typing 'toulouse' on the sidebar still triggers the overlay

Visual / Storybook tests

  • Users panel — full table state
  • Users panel — empty state
  • Users panel — create user modal
  • Users panel — last-admin protection tooltip
  • API Tokens panel — full table state
  • API Tokens panel — empty state
  • API Tokens panel — create token modal (form state + "save now" state)
  • Access Control panel — overrides

Non-regression tests

  • Existing pages that did not have role checks pre-PR still render identically when auth.enabled=false (no role context = behave as admin for UI purposes)
  • Existing login flow → success → redirect to Dashboard works unchanged
  • useAutoRefresh hook on pages where role hides some sections still works on the visible sections

Impact and Severity

  • Audience affected: every deployment that will benefit from multi-user — same audience as Issue C1.
  • Severity: enhancement; required to fully realize the value of C1 (a viewer who can see admin menu items is a UX bug, not just an aesthetic issue — they'll click and get 403s).
  • Effort: ~1 week, including the test suite. Some work parallelizable with C1 (frontend can mock the new endpoints with MSW).

Breaking Changes

  • None at the user-facing level.
  • Frontend code in other PRs that imports nav items or page lists may need to consume the new declarative nav array — flag during review.

Dependencies

  • Blocked by Issue C1 (/api/auth/users, /api/auth/me with role, /api/auth/access-control must exist on the backend).
  • Blocked by Issue B if shipped after — if Issue B is shipped after C2, then C2 ships without the API Tokens panel and adds it in a follow-up PR. If shipped before, C2 includes the API Tokens panel. The decision depends on the actual merge order — describe both paths in the PR description.

Out of Scope

  • Bulk operations (delete multiple users at once) — Settings > Users handles one user at a time in v1.
  • User self-service password change UI from the topbar — already exists in the profile page, reuses the existing flow.
  • Audit log UI surface — separate issue if/when the backend log surfaces.
  • Migration of StadeToulousainOverlay or other easter eggs to a future Cosmos package — out of scope, easter eggs stay where they are.
  • Cosmetic redesign of Settings — this issue adapts existing patterns, the broader Cosmos migration (Issue refactor(frontend): audit & standardize component usage across all pages #21 / future) handles aesthetic uplift.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions