Repository navigation
Description
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 everythingauth.enabled=true→ a singleadminuser 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
- Non-regression first: existing
auth.enabled=truesingle-admin deployments must keep working without configuration changes. The fix migrates them automatically. - Separate file for user state: new
config/users.yaml, not stored inapp.yaml(cf. audit LIM-03). - One authorization concept: a single role enum (
viewer | editor | admin), used by both human users (Issue C1) and API tokens (Issue B). - 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: falseschema_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.roleLogin flow update
POST /api/auth/login (auth.py:187) now:
- Looks up the user in
users_store(no longer readsauth.usernamefromapp.yaml) - On migrated deployments, the admin user is the migrated entry
- JWT payload unchanged shape (
{sub, exp}) — non-breaking for existing JWTs in flight - Updates
last_login_aton 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— usesusers_storeinstead ofapp.yaml(transparent after migration)GET /api/auth/me— addsroleto the response payloadPOST /api/auth/change-password— operates on the calling user's entry inusers_storePOST /api/auth/change-username— operates on the calling user's entry inusers_store
Configuration changes (AppConfig)
In src/rackscope/model/config.py:
auth.usernameandauth.password_hashbecome deprecated fields (kept for migration trigger, emit deprecation warning at startup if non-empty after migration completed)- No new keys required —
users.yamlis 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 fromapp.yaml-with-admin tousers.yaml-with-1-admin works, idempotent, no-op whenusers.yamlalready exists
Functional tests (tests/integration/auth/)
- Login flow:
POST /api/auth/loginon a freshly migrated deployment returns a JWT,GET /api/auth/mereturns{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/adminreturns 409 with"Cannot delete the last admin user" - Editor cannot list users:
GET /api/auth/userswith editor JWT → 403 - Viewer cannot access editor endpoints:
POST /api/siteswith viewer JWT → 403 - Editor can access editor endpoints:
POST /api/siteswith editor JWT → 201 - Override
viewer_can_read_inventory=true: viewer canGET /api/catalog/templates - Override
editor_can_read_logs=true: editor canGET /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.yamlvalue, not the stale claim - Username validation rejects
../,<script>, null bytes - Password policy enforced on
POST /api/auth/users(length, charset per existingPasswordPolicyConfig) - 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=truewith single admin inapp.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/loginnow reads fromusers.yamlafter migration. The first start of a migrated instance createsconfig/users.yamlautomatically. The user's credentials are unchanged.GET /api/auth/meadds arolefield. Existing frontend code that ignores extra fields keeps working.auth.usernameandauth.password_hashinapp.yamlbecome deprecated. They are read once at migration, then ignored. A startup warning is emitted if they remain inapp.yamlafter 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 withviewer,editor, oradminroles via Settings > Users." - "After upgrading, you may safely remove
auth.usernameandauth.password_hashfromapp.yaml— they are no longer used."
Dependencies
- Blocked by Issue A (
require_adminmust exist on mutation endpoints before role distinctions are meaningful). - Unblocks Issue B (API tokens reuse the role enum and
require_roledependency). - Unblocks Issue C2 (frontend RBAC needs
/api/auth/usersand/api/auth/mewith 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.
Activity