Files
bambuddy/backend/app/models/api_key.py
T
maziggy ec51394196 fix(security): GHSA-r2qv-8222-hqg3 — allowlist API-key permissions (CVSS 9.9)
API-key permission gates went from a 17-entry admin denylist with the three
  documented scope flags (can_read_status / can_queue / can_control_printer)
  enforced only inside /api/v1/webhook/* to an explicit per-Permission
  allowlist consulted by every dependency:

    - core/auth.py: _APIKEY_SCOPE_BY_PERMISSION maps every non-admin
      Permission to one scope flag on APIKey; unmapped = 403.
      _check_apikey_permissions now takes the api_key and checks the flag.
    - require_any_permission_if_auth_enabled + require_ownership_permission
      were returning None for any valid key with zero scope check; both now
      invoke _check_apikey_permissions and fail closed.
    - Two new scope flags on api_keys: can_manage_library (LIBRARY_UPLOAD /
      UPDATE_OWN / DELETE_OWN / MAKERWORLD_IMPORT) and can_manage_inventory
      (INVENTORY_CREATE / UPDATE / DELETE / FORECAST_WRITE — required by
      SpoolBuddy kiosks). Default TRUE, backfilled from can_queue so existing
      "queue-only" keys keep working and hardened "read-only" keys do not
      silently gain writes.
    - CLOUD_AUTH now routed through can_access_cloud for defence-in-depth
      alongside the existing _cloud_api_key_gate.
    - Migration column-existence check (_api_keys_column_exists) gates the
      backfill so user-edited values are never overwritten on restart.

  Structural drift backstop: test_every_permission_has_a_classification fails
  CI on any new Permission added without an explicit scope mapping —
  prevents the denylist-shape regression that grew the prior surface.

  Backend 5469 tests green; ruff clean. Frontend build green; i18n parity
  green across 9 locales (5005 leaves each, +6 new keys). Wiki permissions
  table + allowlist callout + upgrade notes updated.
2026-06-02 08:28:24 +02:00

53 lines
2.5 KiB
Python

from datetime import datetime
from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, String, func
from sqlalchemy.orm import Mapped, mapped_column
from backend.app.core.database import Base
class APIKey(Base):
"""API key for external webhook access."""
__tablename__ = "api_keys"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100)) # User-friendly name
key_hash: Mapped[str] = mapped_column(String(255)) # bcrypt hash of the key
key_prefix: Mapped[str] = mapped_column(String(20)) # First 8 chars + "..." for display
# Owner — required for new keys, NULL only on legacy rows that predate per-user
# ownership. Cloud routes reject calls from keys without an owner so callers are
# forced to recreate them. CASCADE so deleting a user removes their keys.
user_id: Mapped[int | None] = mapped_column(
Integer,
ForeignKey("users.id", ondelete="CASCADE"),
nullable=True,
index=True,
)
# Permissions
can_queue: Mapped[bool] = mapped_column(Boolean, default=True) # Add to queue
can_control_printer: Mapped[bool] = mapped_column(Boolean, default=False) # Start/stop/cancel
can_read_status: Mapped[bool] = mapped_column(Boolean, default=True) # Query status
can_manage_library: Mapped[bool] = mapped_column(
Boolean, default=True
) # Upload/rename/delete own library files + MakerWorld import
can_manage_inventory: Mapped[bool] = mapped_column(
Boolean, default=True
) # Inventory write ops (incl. SpoolBuddy kiosk NFC/scale/system)
can_access_cloud: Mapped[bool] = mapped_column(Boolean, default=False) # Read /cloud/* on the owner's behalf
# Narrowly-scoped settings write: only POST /settings/electricity-price.
# Lets HA/Tibber-style automations push dynamic tariff updates without
# granting full SETTINGS_UPDATE (which is denied for API keys because it
# could rewrite SMTP/LDAP/MQTT credentials).
can_update_energy_cost: Mapped[bool] = mapped_column(Boolean, default=False)
# Optional scope limits
printer_ids: Mapped[list | None] = mapped_column(JSON, nullable=True) # null = all printers
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
last_used: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True) # Optional expiry