Files
bambuddy/backend/app/schemas/api_key.py
T
maziggy 133ec72527 feat(api-keys): per-user ownership + opt-in cloud access scope (#1182)
Tim (@turulix) is building a fully automated headless slicing pipeline
  against Bambuddy's API and hit the wall flagged in #665: /cloud/* routes
  resolve cloud_token per-user from User.cloud_token, but the auth gate
  returned None for API-keyed requests, so the route fell back to the
  global Settings-table token, which only carries a value in auth-disabled
  deployments. Net effect on auth-enabled deployments: API keys reached
  the gate just fine, then /cloud/filaments always saw user=None and
  returned 401 / empty results — no path to read slicer presets or the
  filament catalogue that a CLI workflow needs.

  Make API keys carry an owner and route /cloud/* lookups through that
  owner; gate the new capability behind an explicit opt-in scope so
  existing automation doesn't gain cloud-read access on upgrade.

  - APIKey gains user_id (FK to users.id, ON DELETE CASCADE) and
    can_access_cloud (BOOLEAN DEFAULT 0). User-delete route also runs an
    explicit DELETE FROM api_keys WHERE user_id = ? since SQLite ships
    FK enforcement off — same pattern as the existing created_by_id
    cleanup blocks.

  - New cloud_caller dep on /cloud/* routes resolves to the JWT user OR
    the API-key owner stashed by a router-level gate. The auth gate itself
    continues to return None for API keys so #1182's surface stays bounded
    to /cloud/* — without that bound, any route that fences API keys via
    `if current_user is None: raise 403` (e.g. long-lived-token
    management) would silently start accepting them.

  - The /cloud/* router-level dep enforces three independent fences for
    API-keyed callers: user_id IS NOT NULL (legacy keys → 401 with
    recreate copy), can_access_cloud=True (otherwise 403), and owner has
    cloud_token (existing fence, unchanged). Two extra one-shot fence
    errors at create/update time refuse can_access_cloud=True when auth
    is disabled or the key is ownerless.

  - Frontend: APIKey list shows "Cloud" badge on cloud-enabled keys and
    "Legacy" badge on ownerless rows; create form gains an "Allow cloud
    access" toggle, default off. New i18n keys in all 8 locales (en + de
    fully translated, others seeded with English fallbacks pending native
    translation — matches the project's flow for newly-added features).

  Migration: two idempotent ALTER TABLE statements + an index on user_id
  for the auth gate's owner→keys lookup. Postgres-safe.

  Tests: 9 backend integration tests in test_api_key_cloud_access.py
  covering creation flags, the three /cloud/* fences, JWT no-op, and
  deletion CASCADE; 2 frontend SettingsPage tests pinning the badge
  matrix and the create-form contract; 5 daemon unit tests for the
  related SpoolBuddy ssh-key sync work that landed in the same branch.
  Full backend suite: 3578 passed; full frontend suite: 1597 passed; no
  regressions.

  Permission semantics for existing keys: keys created before this
  release become "legacy" and are rejected at /cloud/* with the recreate
  message. Every other endpoint they were used against — queue, status,
  control — is untouched.
2026-05-01 11:43:55 +02:00

56 lines
1.5 KiB
Python

from datetime import datetime
from pydantic import BaseModel
class APIKeyCreate(BaseModel):
"""Schema for creating a new API key."""
name: str
can_queue: bool = True
can_control_printer: bool = False
can_read_status: bool = True
can_access_cloud: bool = False # Read /cloud/* on the creator's behalf — default off (#1182)
printer_ids: list[int] | None = None # null = all printers
expires_at: datetime | None = None
class APIKeyUpdate(BaseModel):
"""Schema for updating an API key."""
name: str | None = None
can_queue: bool | None = None
can_control_printer: bool | None = None
can_read_status: bool | None = None
can_access_cloud: bool | None = None
printer_ids: list[int] | None = None
enabled: bool | None = None
expires_at: datetime | None = None
class APIKeyResponse(BaseModel):
"""Schema for API key response (without full key)."""
id: int
name: str
key_prefix: str # First 8 chars for identification
user_id: int | None # Owner — NULL on legacy keys created before per-user ownership (#1182)
can_queue: bool
can_control_printer: bool
can_read_status: bool
can_access_cloud: bool
printer_ids: list[int] | None
enabled: bool
last_used: datetime | None
created_at: datetime
expires_at: datetime | None
class Config:
from_attributes = True
class APIKeyCreateResponse(APIKeyResponse):
"""Response when creating a key - includes full key (shown only once)."""
key: str # Full API key, only shown on creation