Skip to content

feat(auth): file-based API tokens for external integrations (NetBox, BlueBanquise) #28

Open

Description

@SckyzO

feat(auth): file-based API tokens for external integrations (NetBox, BlueBanquise, ...)

Context and Motivation

Rackscope today offers only one way to authenticate against the API programmatically: scripting a POST /api/auth/login with a human user's username + password, retrieving the resulting JWT, and reusing it until expiration.

This works for ad-hoc curl and manual scripts, but it is the wrong primitive for machine-to-machine integrations, which are real and documented use cases for Rackscope:

Integration Direction Need
NetBox → Rackscope NetBox as DCIM source of truth, pushes topology updates to Rackscope for physical visualisation Stable credential, write access to topology, no human password rotation
BlueBanquise → Rackscope HPC cluster deployment tool (Ansible-based) maintains the cluster inventory, pushes nodes/racks to Rackscope Stable credential, write access to topology, runs on schedule
Generic DCIM sync tools Third-party inventory tools pushing to Rackscope's /api/topology Same

Problems with the current flow for these scenarios:

  • Storing a human admin's password in a CI secret or cron environment file is risky (audit, leakage, rotation hell).
  • Rotating the human password breaks every integration silently.
  • No granular revocation: rotating auth.secret_key invalidates all human sessions at the same time.
  • No last_used_at to detect decommissioned integrations whose credentials still exist.

Design Goals

  1. File-based — fits the Rackscope philosophy ("no mandatory database, GitOps-friendly").
  2. No new dependency — reuse bcrypt (already in deps) for token hashing.
  3. Role-attached — tokens reference the same role enum as users (Issue C1 introduces viewer | editor | admin). One authorization model in the whole app.
  4. Revocable individually — deleting an entry from api_tokens.yaml immediately invalidates that one token, leaves all others intact.
  5. Audit-friendly — last_used_at updated on each successful authentication, surfaced in Settings UI.
  6. Non-breaking — JWT login flow for human users unchanged.

Storage Format

New file: config/api_tokens.yaml, separate from app.yaml (avoids polluting GitOps-friendly static config with runtime state — cf. audit LIM-03).

schema_version: 1
api_tokens:
  - id: tok_01HF9YQK4Z8M3X
    name: "netbox-sync"
    token_hash: "$2b$13$..."        # bcrypt, plain token never stored
    role: editor                     # viewer | editor | admin
    created_at: 2026-05-13T10:00:00Z
    created_by: "admin"              # username of the user who created it
    last_used_at: null
    expires_at: null                 # nullable
  - id: tok_01HF9YR2P5N7Q1
    name: "bluebanquise-inventory"
    token_hash: "$2b$13$..."
    role: editor
    created_at: 2026-05-13T10:05:00Z
    created_by: "admin"
    last_used_at: 2026-05-13T11:30:00Z
    expires_at: 2027-05-13T00:00:00Z

The file MUST be excluded from GET /api/config output (see audit SEC-04 pattern).

Token Format

  • Prefix: rsk_ (rackscope key)
    • Identifiable by grep in case of accidental commit
    • Pattern added to .gitleaks.toml (^rsk_[A-Za-z0-9_-]{40,}$)
  • Body: 32 bytes random base64url → ~43 chars
  • Full format: rsk_<43 chars>

The plain token is shown to the user exactly once, at creation time, in a modal with explicit "save now, you won't see this again" warning. Only the bcrypt hash is persisted.

API Surface

All three endpoints require require_role("admin") (admin users only — tokens themselves cannot create other tokens, prevents propagation if a token leaks).

Method Path Body Response
POST /api/auth/api-tokens {name, role, expires_at?} {id, name, role, token: "rsk_..."} (plain token, one-shot)
GET /api/auth/api-tokens — [{id, name, role, created_at, created_by, last_used_at, expires_at}] (never the secret)
DELETE /api/auth/api-tokens/{id} — 204

Middleware Changes

AuthMiddleware (src/rackscope/api/middleware.py:81) accepts two formats in Authorization: Bearer:

if token.startswith("rsk_"):
    # API token path
    matched = _verify_api_token(token, api_tokens_store)
    if matched is None:
        raise HTTPException(401, "Invalid API token")
    request.state.identity = ApiTokenIdentity(name=matched.name, token_id=matched.id)
    request.state.role = matched.role
    _update_last_used_at(matched.id)  # fire-and-forget, debounced
else:
    # Existing JWT path (unchanged)
    payload = _jwt.decode(token, secret, algorithms=["HS256"])
    request.state.identity = UserIdentity(username=payload["sub"])
    request.state.role = _lookup_role(payload["sub"])

_update_last_used_at MUST be debounced (e.g., update at most once per minute per token) to avoid hammering the YAML file on high-frequency integrations.

Role Coverage for the Documented Use Cases

Token use case Recommended role
NetBox sync (write topology, no Settings) editor
BlueBanquise inventory (write topology, no Settings) editor
Read-only Grafana scrape (if ever needed later) viewer
CI/CD that needs Settings (rare) admin

The editor role is the right default for DCIM sync use cases — it grants write access to topology/catalog/checks without exposing Settings, Logs, Users, or token management.

UI Changes

New section: Settings > API Tokens. Two views:

List view

  • Table columns: name, role, created, last used, expires, actions
  • Action: [Revoke] button per row → confirmation modal → DELETE /api/auth/api-tokens/{id}
  • "Create token" CTA in the header

Creation modal

  • Input: name (required, free label like "netbox-sync", validated against [a-zA-Z0-9-_]{3,64})
  • Select: role (viewer | editor | admin)
  • Optional: expires_at date picker
  • On submit: backend returns the plain token, modal switches to "Save this token now" state showing the rsk_xxx value with a copy button and warning that it cannot be recovered.

Test Plan

Unit tests (tests/unit/auth/test_api_tokens.py)

  • Token generation: prefix rsk_, length, base64url charset, entropy
  • Bcrypt hash matches plain token
  • Bcrypt hash does not match a different token
  • _update_last_used_at debouncing logic
  • Token file serialization round-trip (no precision loss on timestamps)

Functional tests (tests/integration/test_api_tokens_endpoints.py)

  • POST /api/auth/api-tokens with admin JWT: 201 + plain token in response
  • GET /api/auth/api-tokens with admin JWT: list without secrets
  • DELETE /api/auth/api-tokens/{id} with admin JWT: 204 + token unusable after
  • POST /api/auth/api-tokens with editor JWT: 403 (tokens are admin-only)
  • POST /api/auth/api-tokens with viewer JWT: 403
  • Created token can authenticate a subsequent GET /api/topology (when role allows)
  • Created editor token can POST /api/sites (NetBox use case)
  • Created viewer token cannot POST /api/sites → 403
  • Expired token returns 401 with explicit detail "API token expired"

Security tests (tests/security/test_api_tokens_security.py)

  • Token forgery: random rsk_<42 chars> not in the store → 401
  • Hash-only storage: the plain token never appears in config/api_tokens.yaml
  • GET /api/config excludes api_tokens entirely (no token_hash leak)
  • GET /api/auth/api-tokens never returns token_hash in any response shape
  • Rate-limit on POST /api/auth/api-tokens (anti-flood, same primitive as login)
  • Token cannot create other tokens (admin token used → 403 on POST /api/auth/api-tokens if identity is a token, not a user)
  • Token with malformed rsk_ prefix is rejected fast (before bcrypt verification, to avoid timing oracle)

Non-regression tests (tests/regression/test_jwt_login_unchanged.py)

  • Existing POST /api/auth/login flow returns JWT identical to pre-PR behaviour (golden response)
  • Existing JWT can authenticate all endpoints exactly as before
  • Adding/revoking API tokens has no effect on JWT validity

Impact and Severity

  • Audience affected: operators of Rackscope deployments who want to integrate with NetBox, BlueBanquise, or any external DCIM tool that writes to the Rackscope API.
  • Severity: enhancement. Not a blocker for v1.0.0 itself, but a blocker for any non-trivial automation use case.
  • Bundle impact: minimal — one new YAML loader, one new router, one new Settings panel, one middleware branch.

Breaking Changes

None.

  • Existing JWT login flow unchanged.
  • New file config/api_tokens.yaml is created on first token creation (does not need to exist upfront).
  • No config migration required.

Dependencies

  • Blocked by Issue C1 (RBAC backend): introduces the role enum (viewer | editor | admin) and require_role() dependency. This issue's middleware reuses that infrastructure.
  • Frontend UI shipped in Issue C2, alongside the Users panel: both panels live under Settings, ship together for UX coherence.

Out of Scope

  • OAuth/OIDC tokens issued by external IdPs — covered by the future RBAC Phase 2 RFC.
  • Per-resource scoping (e.g., a token that can only write to one specific site). Use the role enum coarse granularity — if a real use case for finer scoping emerges, open a follow-up issue.
  • Token rotation / expiry warnings via email or webhook. Manual rotation via Settings UI is the v1 model.
  • IP allowlisting per token. Possible follow-up if a real need emerges.
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