api_keys.py 7.0 KB

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