api_keys.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import logging
  2. from fastapi import APIRouter, Depends, HTTPException
  3. from sqlalchemy import select
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from backend.app.core.auth import RequirePermissionIfAuthEnabled, generate_api_key
  6. from backend.app.core.database import get_db
  7. from backend.app.core.permissions import Permission
  8. from backend.app.core.websocket import ws_manager
  9. from backend.app.models.api_key import APIKey
  10. from backend.app.models.user import User
  11. from backend.app.schemas.api_key import (
  12. APIKeyCreate,
  13. APIKeyCreateResponse,
  14. APIKeyResponse,
  15. APIKeyUpdate,
  16. )
  17. logger = logging.getLogger(__name__)
  18. router = APIRouter(prefix="/api-keys", tags=["api-keys"])
  19. @router.get("/", response_model=list[APIKeyResponse])
  20. async def list_api_keys(
  21. db: AsyncSession = Depends(get_db),
  22. _: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_READ),
  23. ):
  24. """List all API keys (without full key values)."""
  25. result = await db.execute(select(APIKey).order_by(APIKey.created_at.desc()))
  26. return list(result.scalars().all())
  27. @router.post("/", response_model=APIKeyCreateResponse)
  28. async def create_api_key(
  29. data: APIKeyCreate,
  30. db: AsyncSession = Depends(get_db),
  31. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_CREATE),
  32. ):
  33. """Create a new API key.
  34. IMPORTANT: The full API key is only returned in this response.
  35. Store it securely - it cannot be retrieved again.
  36. """
  37. # Reject can_access_cloud on auth-disabled deployments — there's no per-user
  38. # cloud_token to read against, so the flag would just silently do nothing.
  39. # Surfacing the rejection at create time prevents the user from thinking
  40. # they've configured cloud access when they actually haven't.
  41. if data.can_access_cloud and current_user is None:
  42. raise HTTPException(
  43. status_code=400,
  44. detail="can_access_cloud requires authentication to be enabled (per-user cloud tokens)",
  45. )
  46. # Generate the key
  47. full_key, key_hash, key_prefix = generate_api_key()
  48. api_key = APIKey(
  49. name=data.name,
  50. key_hash=key_hash,
  51. key_prefix=key_prefix,
  52. user_id=current_user.id if current_user else None,
  53. can_queue=data.can_queue,
  54. can_control_printer=data.can_control_printer,
  55. can_read_status=data.can_read_status,
  56. can_manage_library=data.can_manage_library,
  57. can_manage_inventory=data.can_manage_inventory,
  58. can_manage_maintenance=data.can_manage_maintenance,
  59. can_manage_archives=data.can_manage_archives,
  60. can_manage_projects=data.can_manage_projects,
  61. can_access_cloud=data.can_access_cloud,
  62. can_update_energy_cost=data.can_update_energy_cost,
  63. can_send_notifications=data.can_send_notifications,
  64. printer_ids=data.printer_ids,
  65. expires_at=data.expires_at,
  66. )
  67. db.add(api_key)
  68. await db.flush()
  69. await db.refresh(api_key)
  70. # Return with full key (only time it's shown)
  71. return APIKeyCreateResponse(
  72. id=api_key.id,
  73. name=api_key.name,
  74. key_prefix=api_key.key_prefix,
  75. key=full_key, # Only returned on creation
  76. user_id=api_key.user_id,
  77. can_queue=api_key.can_queue,
  78. can_control_printer=api_key.can_control_printer,
  79. can_read_status=api_key.can_read_status,
  80. can_manage_library=api_key.can_manage_library,
  81. can_manage_inventory=api_key.can_manage_inventory,
  82. can_manage_maintenance=api_key.can_manage_maintenance,
  83. can_manage_archives=api_key.can_manage_archives,
  84. can_manage_projects=api_key.can_manage_projects,
  85. can_access_cloud=api_key.can_access_cloud,
  86. can_update_energy_cost=api_key.can_update_energy_cost,
  87. can_send_notifications=api_key.can_send_notifications,
  88. printer_ids=api_key.printer_ids,
  89. enabled=api_key.enabled,
  90. last_used=api_key.last_used,
  91. created_at=api_key.created_at,
  92. expires_at=api_key.expires_at,
  93. )
  94. @router.get("/{key_id}", response_model=APIKeyResponse)
  95. async def get_api_key(
  96. key_id: int,
  97. db: AsyncSession = Depends(get_db),
  98. _: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_READ),
  99. ):
  100. """Get an API key by ID."""
  101. result = await db.execute(select(APIKey).where(APIKey.id == key_id))
  102. api_key = result.scalar_one_or_none()
  103. if not api_key:
  104. raise HTTPException(status_code=404, detail="API key not found")
  105. return api_key
  106. @router.patch("/{key_id}", response_model=APIKeyResponse)
  107. async def update_api_key(
  108. key_id: int,
  109. data: APIKeyUpdate,
  110. db: AsyncSession = Depends(get_db),
  111. _: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_UPDATE),
  112. ):
  113. """Update an API key."""
  114. result = await db.execute(select(APIKey).where(APIKey.id == key_id))
  115. api_key = result.scalar_one_or_none()
  116. if not api_key:
  117. raise HTTPException(status_code=404, detail="API key not found")
  118. # Update fields if provided
  119. if data.name is not None:
  120. api_key.name = data.name
  121. if data.can_queue is not None:
  122. api_key.can_queue = data.can_queue
  123. if data.can_control_printer is not None:
  124. api_key.can_control_printer = data.can_control_printer
  125. if data.can_read_status is not None:
  126. api_key.can_read_status = data.can_read_status
  127. if data.can_manage_library is not None:
  128. api_key.can_manage_library = data.can_manage_library
  129. if data.can_manage_inventory is not None:
  130. api_key.can_manage_inventory = data.can_manage_inventory
  131. if data.can_manage_maintenance is not None:
  132. api_key.can_manage_maintenance = data.can_manage_maintenance
  133. if data.can_manage_archives is not None:
  134. api_key.can_manage_archives = data.can_manage_archives
  135. if data.can_manage_projects is not None:
  136. api_key.can_manage_projects = data.can_manage_projects
  137. if data.can_access_cloud is not None:
  138. # Same constraint as create — flipping cloud access on a legacy key
  139. # without an owner would be silently broken; reject at the route layer.
  140. if data.can_access_cloud and api_key.user_id is None:
  141. raise HTTPException(
  142. status_code=400,
  143. detail="can_access_cloud requires the API key to have an owner; recreate the key after upgrading",
  144. )
  145. api_key.can_access_cloud = data.can_access_cloud
  146. if data.can_update_energy_cost is not None:
  147. api_key.can_update_energy_cost = data.can_update_energy_cost
  148. if data.can_send_notifications is not None:
  149. api_key.can_send_notifications = data.can_send_notifications
  150. if data.printer_ids is not None:
  151. api_key.printer_ids = data.printer_ids
  152. if data.enabled is not None:
  153. api_key.enabled = data.enabled
  154. if data.expires_at is not None:
  155. api_key.expires_at = data.expires_at
  156. await db.flush()
  157. await db.refresh(api_key)
  158. if data.printer_ids is not None or data.enabled is not None or data.expires_at is not None:
  159. # Sockets opened with this key may now see fewer printers, or none
  160. # (#1727). Committed first so the refresh reads the new row.
  161. await db.commit()
  162. await ws_manager.refresh_printer_scopes()
  163. return api_key
  164. @router.delete("/{key_id}")
  165. async def delete_api_key(
  166. key_id: int,
  167. db: AsyncSession = Depends(get_db),
  168. _: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_DELETE),
  169. ):
  170. """Delete (revoke) an API key."""
  171. result = await db.execute(select(APIKey).where(APIKey.id == key_id))
  172. api_key = result.scalar_one_or_none()
  173. if not api_key:
  174. raise HTTPException(status_code=404, detail="API key not found")
  175. await db.delete(api_key)
  176. # Sockets opened with this key lose their printers (#1727)
  177. await db.commit()
  178. await ws_manager.refresh_printer_scopes()
  179. return {"message": "API key deleted"}