Skip to content

feat(auth): local RBAC backend — multi-user accounts with viewer/editor/admin roles #27

Open

Description

@SckyzO

feat(auth): local RBAC backend — multi-user accounts with viewer/editor/admin roles

Context and Motivation

Today Rackscope has a binary authorization model (cf. audit LIM-01):

  • auth.enabled=false → anonymous access to everything
  • auth.enabled=true → a single admin user with full access

There is no middle ground. Every realistic deployment needs at least these three personas:

Persona Typical use Today
NOC viewer Watches dashboards from a shared screen / lobby display Must share admin password OR run with auth.enabled=false (everything exposed)
Infrastructure operator Modifies topology, racks, devices when hardware changes Must share admin password
Deployment owner Modifies app config, plugins, users, etc. Today's only persona

This issue implements local-only RBAC as Phase 1 of the RFC RBAC (cf. rackscope_documentation/docs/development/RFC_RBAC.md). External identity providers (LDAP, OIDC) are explicitly out of scope and ship in Phase 2 once the local model is stable.

Design Principles

  1. Non-regression first: existing auth.enabled=true single-admin deployments must keep working without configuration changes. The fix migrates them automatically.
  2. Separate file for user state: new config/users.yaml, not stored in app.yaml (cf. audit LIM-03).
  3. One authorization concept: a single role enum (viewer | editor | admin), used by both human users (Issue C1) and API tokens (Issue B).
  4. Anticipate Phase 2: the user lookup is structured so an external provider can plug in later without API breakage. See "Forward compatibility" below.

Role Model

Role Can access Cannot access
viewer Dashboards (DashboardPage, MaintenancesPage), worldmap, /about Editors (topology, catalog, checks, metrics, templates), Settings, Logs, Users, API Tokens
editor Everything viewer can + all editors (topology, catalog, checks, metrics, templates, rack templates) + read-only API access to system status Settings, Logs, Users, API Tokens
admin Everything (nothing)

Role Overrides (auth_settings in users.yaml)

Three opt-in flags to relax viewer/editor restrictions when the deployment requires it. Defaults are restrictive (least privilege).

auth_settings:
  viewer_can_read_inventory: false        # default: viewer cannot see templates/devices in read mode
  viewer_can_read_metrics_config: false   # default: viewer cannot see metrics configuration
  editor_can_read_logs: false             # default: editor cannot access /api/logs (often contains sensitive data)

No "permission builder" UI in v1 — these three flags cover the documented user pain points and stay simple.

Storage Format

New file: config/users.yaml

schema_version: 1
users:
  - username: admin
    password_hash: "$2b$13$..."
    role: admin
    created_at: 2026-05-13T10:00:00Z
    created_by: "migration"        # or username of creator post-migration
    last_login_at: null
  - username: bob
    password_hash: "$2b$13$..."
    role: editor
    created_at: 2026-05-13T10:30:00Z
    created_by: "admin"
    last_login_at: 2026-05-13T11:00:00Z
  - username: alice
    password_hash: "$2b$13$..."
    role: viewer
    created_at: 2026-05-13T10:35:00Z
    created_by: "admin"
    last_login_at: null
auth_settings:
  viewer_can_read_inventory: false
  viewer_can_read_metrics_config: false
  editor_can_read_logs: false

schema_version allows future migrations without breaking the loader. Bump it whenever the file shape changes incompatibly.

Migration from Single-Admin (Non-Breaking)

On startup, the auth loader follows this decision tree:

1. Does config/users.yaml exist?
   ├── YES → load it, done.
   └── NO  →
       2. Does app.yaml contain auth.username + auth.password_hash?
          ├── YES →
          │   - Create config/users.yaml with one user:
          │     { username: <app.yaml auth.username>, password_hash: <same>, role: admin,
          │       created_at: now(), created_by: "migration", last_login_at: null }
          │   - Log INFO "Migrated single-admin auth → config/users.yaml (1 user, role=admin)"
          │   - Optionally (post-migration): emit deprecation warning telling the operator
          │     to remove auth.username / auth.password_hash from app.yaml.
          │     DO NOT auto-delete from app.yaml — that's destructive on a config the user owns.
          └── NO →
              - Create empty config/users.yaml with schema_version + empty users list.
              - Behaviour unchanged from today (auth.enabled=false means anonymous access).

This ensures zero manual action for existing auth.enabled=true deployments — they boot, get migrated, and keep working.

Backend Changes

New module: src/rackscope/api/auth/

src/rackscope/api/auth/
├── __init__.py
├── roles.py            # Role enum, role hierarchy logic
├── users_store.py      # YAML-backed user store with locking
├── overrides.py        # AuthSettings, override evaluation
└── identity.py         # UserIdentity / ApiTokenIdentity (forward-compat with Issue B)

roles.py

from enum import Enum

class Role(str, Enum):
    VIEWER = "viewer"
    EDITOR = "editor"
    ADMIN = "admin"

# Strict hierarchy: admin > editor > viewer
_ORDER = {Role.VIEWER: 0, Role.EDITOR: 1, Role.ADMIN: 2}

def role_satisfies(actual: Role, required: Role) -> bool:
    return _ORDER[actual] >= _ORDER[required]

dependencies.py — new require_role, keep require_admin for compat

def require_role(required: Role):
    def _dep(request: Request) -> None:
        from rackscope.api.app import APP_CONFIG
        # auth.enabled=false → same trusted_networks behaviour as today
        if not (APP_CONFIG and APP_CONFIG.auth.enabled):
            networks = APP_CONFIG.auth.trusted_networks if APP_CONFIG else []
            if not networks:
                return
            if not _is_trusted_ip(request, networks):
                raise HTTPException(403, "Not from a trusted network")
            return
        # auth.enabled=true → role check
        actual_role = getattr(request.state, "role", None)
        if actual_role is None:
            raise HTTPException(401, "Not authenticated")
        if not role_satisfies(actual_role, required):
            raise HTTPException(403, f"Requires role: {required.value}")
    return _dep

# Backwards-compatible alias used during transition
def require_admin(request: Request) -> None:
    return require_role(Role.ADMIN)(request)

require_admin stays available as an alias for require_role(Role.ADMIN) — every existing call site keeps working. Future routers should prefer the explicit require_role() form.

AuthMiddleware extension

Decode JWT → look up the user → set both request.state.user (username string, kept for backward-compat) and request.state.role (Role enum):

payload = _jwt.decode(token, secret, algorithms=["HS256"])
username = payload.get("sub", "")
request.state.user = username
user = users_store.get(username)
if user is None:
    raise HTTPException(401, "User no longer exists")
request.state.role = user.role

Login flow update

POST /api/auth/login (auth.py:187) now:

  1. Looks up the user in users_store (no longer reads auth.username from app.yaml)
  2. On migrated deployments, the admin user is the migrated entry
  3. JWT payload unchanged shape ({sub, exp}) — non-breaking for existing JWTs in flight
  4. Updates last_login_at on success (debounced as in Issue B)

New CRUD endpoints — /api/auth/users

All under require_role(Role.ADMIN):

Method Path Body Notes
POST /api/auth/users {username, password, role} Validates username regex, password policy, returns user (sans hash)
GET /api/auth/users — List all users (sans hash)
GET /api/auth/users/{username} — Single user (sans hash)
PUT /api/auth/users/{username} {role?, password?} Change role and/or reset password
DELETE /api/auth/users/{username} — Cannot delete the last admin (server enforces)

Existing auth endpoints behaviour

  • POST /api/auth/login — uses users_store instead of app.yaml (transparent after migration)
  • GET /api/auth/me — adds role to the response payload
  • POST /api/auth/change-password — operates on the calling user's entry in users_store
  • POST /api/auth/change-username — operates on the calling user's entry in users_store

Configuration changes (AppConfig)

In src/rackscope/model/config.py:

  • auth.username and auth.password_hash become deprecated fields (kept for migration trigger, emit deprecation warning at startup if non-empty after migration completed)
  • No new keys required — users.yaml is a separate file managed by the new module

Forward Compatibility with Phase 2 (LDAP / OIDC)

The user store is structured to allow an external provider later:

# users_store.py — current v1 abstraction
class LocalUserStore:
    def get(self, username: str) -> Optional[User]: ...
    def list(self) -> list[User]: ...
    def authenticate(self, username: str, password: str) -> Optional[User]: ...

# Phase 2 will introduce
class AuthProvider(Protocol):
    name: str
    def authenticate(self, ...) -> Optional[Identity]: ...

class LocalProvider(LocalUserStore): name = "local"
class LdapProvider: name = "ldap"
class OidcProvider: name = "oidc"

The v1 implementation does not need to use this abstraction yet — over-abstracting now would be premature. But the function shapes (authenticate, get_user) are chosen so the Phase 2 RFC can introduce the Protocol without rewriting v1 callers.

Test Plan

Unit tests (tests/unit/auth/)

  • test_roles.py: role_satisfies(admin, viewer) == True, role_satisfies(viewer, admin) == False, all 9 combinations
  • test_users_store.py: load/save round-trip, file locking under concurrent writes, schema version mismatch raises
  • test_overrides.py: each of the three flags toggles the right effective permission
  • test_migration.py: migration from app.yaml-with-admin to users.yaml-with-1-admin works, idempotent, no-op when users.yaml already exists

Functional tests (tests/integration/auth/)

  • Login flow: POST /api/auth/login on a freshly migrated deployment returns a JWT, GET /api/auth/me returns {username, role: "admin"}
  • CRUD users: admin can create bob (editor), alice (viewer); list shows them; PUT changes alice's role; DELETE removes bob
  • Last-admin protection: DELETE /api/auth/users/admin returns 409 with "Cannot delete the last admin user"
  • Editor cannot list users: GET /api/auth/users with editor JWT → 403
  • Viewer cannot access editor endpoints: POST /api/sites with viewer JWT → 403
  • Editor can access editor endpoints: POST /api/sites with editor JWT → 201
  • Override viewer_can_read_inventory=true: viewer can GET /api/catalog/templates
  • Override editor_can_read_logs=true: editor can GET /api/logs/recent

Security tests (tests/security/)

  • Privilege escalation: viewer cannot self-promote via PUT /api/auth/users/viewer-name {role: admin} (only admin can change roles)
  • JWT forgery: token signed with wrong key → 401
  • JWT replay after user deletion: deleted user's JWT → 401 with "User no longer exists"
  • JWT replay after role downgrade: in-flight JWT after a role demotion → role check uses fresh users.yaml value, not the stale claim
  • Username validation rejects ../, <script>, null bytes
  • Password policy enforced on POST /api/auth/users (length, charset per existing PasswordPolicyConfig)
  • Bcrypt hash never appears in any API response (golden test on all /api/auth/users* shapes)

Non-regression tests (tests/regression/)

  • auth.enabled=false + trusted_networks=[] behaviour identical to pre-PR (anonymous, all endpoints accessible)
  • auth.enabled=false + trusted_networks=["10.0.0.0/8"] behaviour identical to pre-PR
  • auth.enabled=true with single admin in app.yaml: starts up, migrates, login still works with the same credentials, all existing endpoints respond identically
  • Existing JWTs in flight at the moment of the migration are still accepted (no forced re-login)

Impact and Severity

  • Audience affected: every deployment with more than one user. Today, multi-user deployments are forced to share an admin password — a known security anti-pattern.
  • Severity: enhancement, but it unblocks a category of legitimate use cases (NOC viewer screens, ops technicians).
  • Effort: ~1 week for backend, including the test suite.

Breaking Changes

None at the API contract level. Behavioural changes:

  • POST /api/auth/login now reads from users.yaml after migration. The first start of a migrated instance creates config/users.yaml automatically. The user's credentials are unchanged.
  • GET /api/auth/me adds a role field. Existing frontend code that ignores extra fields keeps working.
  • auth.username and auth.password_hash in app.yaml become deprecated. They are read once at migration, then ignored. A startup warning is emitted if they remain in app.yaml after migration.

A v1.x release note must call out:

  • "Authentication is now multi-user." (single line, prominent)
  • "Your existing admin account has been migrated to config/users.yaml. You can now create additional users with viewer, editor, or admin roles via Settings > Users."
  • "After upgrading, you may safely remove auth.username and auth.password_hash from app.yaml — they are no longer used."

Dependencies

  • Blocked by Issue A (require_admin must exist on mutation endpoints before role distinctions are meaningful).
  • Unblocks Issue B (API tokens reuse the role enum and require_role dependency).
  • Unblocks Issue C2 (frontend RBAC needs /api/auth/users and /api/auth/me with role).

Out of Scope

  • LDAP, OIDC, SAML — Phase 2 RFC, future issues.
  • Audit log (logs/audit.jsonl) — mentioned in audit LIM-04, may ship in a follow-up alongside this work or after, but not blocking.
  • Permission builder UI — three fixed overrides are enough for v1.
  • Per-resource permissions (e.g., "user X can edit only site Y") — out of scope.
  • Password reset by email — file-based, no SMTP, admin resets passwords via Settings > Users.
  • 2FA / TOTP — separate future issue.
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