keys.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """
  2. 密钥管理接口
  3. """
  4. from fastapi import APIRouter, Depends, Request
  5. from sqlalchemy.orm import Session
  6. from fastapi import Body
  7. from app.database import get_db
  8. from app.api.deps import get_current_admin
  9. from app.models.api_key import APIKey
  10. from app.models.key_rotation_config import KeyRotationConfig
  11. from app.core.encrypt import encryptor
  12. from datetime import datetime, timedelta
  13. from app.utils.timezone import beijing_now
  14. from app.config import settings
  15. router = APIRouter()
  16. @router.get("/current")
  17. async def get_current_key(
  18. db: Session = Depends(get_db),
  19. current_admin = Depends(get_current_admin)
  20. ):
  21. """获取当前密钥"""
  22. key = db.query(APIKey).filter(APIKey.is_active == 1).order_by(APIKey.key_version.desc()).first()
  23. if not key:
  24. return {"code": 404, "msg": "未找到激活的密钥"}
  25. return {
  26. "code": 200,
  27. "msg": "成功",
  28. "data": {
  29. "public_key": key.public_key,
  30. "private_key": key.private_key,
  31. "key_version": key.key_version,
  32. "expire_at": key.expire_at.isoformat() if key.expire_at else None
  33. }
  34. }
  35. @router.get("/history")
  36. async def get_key_history(
  37. db: Session = Depends(get_db),
  38. current_admin = Depends(get_current_admin)
  39. ):
  40. """获取历史密钥"""
  41. keys = db.query(APIKey).order_by(APIKey.key_version.desc()).all()
  42. return {
  43. "code": 200,
  44. "msg": "成功",
  45. "data": [
  46. {
  47. "id": k.id,
  48. "key_version": k.key_version,
  49. "is_active": bool(k.is_active),
  50. "public_key": k.public_key,
  51. "private_key": k.private_key,
  52. "created_at": k.created_at.isoformat() if k.created_at else None,
  53. "expire_at": k.expire_at.isoformat() if k.expire_at else None
  54. }
  55. for k in keys
  56. ]
  57. }
  58. @router.post("/rotate")
  59. async def rotate_key(
  60. request: Request,
  61. db: Session = Depends(get_db),
  62. current_admin = Depends(get_current_admin)
  63. ):
  64. """立即更新密钥"""
  65. from app.models.system_config import SystemConfig
  66. # 获取当前激活的密钥
  67. current_key = db.query(APIKey).filter(APIKey.is_active == 1).order_by(APIKey.key_version.desc()).first()
  68. # 生成新密钥
  69. new_key_pair = encryptor.generate_key_pair()
  70. new_version = (current_key.key_version + 1) if current_key else 1
  71. # 获取配置,确定过期时间(使用system_config表中的key_expire_minutes,默认60分钟)
  72. expire_minutes = SystemConfig.get_config_value('key_expire_minutes', 60)
  73. expire_at = beijing_now() + timedelta(minutes=expire_minutes)
  74. # 创建新密钥
  75. new_key = APIKey(
  76. public_key=new_key_pair[1], # 公钥 (public_pem)
  77. private_key=new_key_pair[0], # 私钥 (private_pem)
  78. key_version=new_version,
  79. is_active=1,
  80. expire_at=expire_at,
  81. created_at=beijing_now(),
  82. updated_at=beijing_now()
  83. )
  84. db.add(new_key)
  85. # 刷新以获取ID
  86. db.flush()
  87. # 创建历史记录
  88. from app.utils.history import create_api_key_history, create_operation_log
  89. create_api_key_history(db, new_key, "INSERT")
  90. # 记录操作日志
  91. client_ip = request.client.host if request.client else None
  92. old_version = current_key.key_version if current_key else None
  93. create_operation_log(
  94. db=db,
  95. admin_id=current_admin.id,
  96. module="密钥管理",
  97. action="手动密钥轮换",
  98. description=f"执行手动密钥轮换:版本 {old_version} -> {new_version}",
  99. old_data={"old_version": old_version},
  100. new_data={"new_version": new_version, "expire_minutes": expire_minutes},
  101. ip_address=client_ip
  102. )
  103. # 一次性提交所有更改
  104. db.commit()
  105. return {
  106. "code": 200,
  107. "msg": "密钥更新成功",
  108. "data": {
  109. "public_key": new_key.public_key,
  110. "private_key": new_key.private_key,
  111. "key_version": new_key.key_version,
  112. "expire_at": new_key.expire_at.isoformat() if new_key.expire_at else None
  113. }
  114. }
  115. @router.put("/cycle")
  116. async def update_key_cycle(
  117. req: dict = Body(...),
  118. request: Request = None,
  119. db: Session = Depends(get_db),
  120. current_admin = Depends(get_current_admin)
  121. ):
  122. """更新密钥轮换周期"""
  123. rotation_days = req.get("rotation_days")
  124. if not rotation_days or rotation_days < 1:
  125. return {"code": 400, "msg": "轮换周期必须大于0"}
  126. # 获取或创建配置
  127. config = db.query(KeyRotationConfig).first()
  128. old_rotation_days = config.rotation_days if config else None
  129. if not config:
  130. config = KeyRotationConfig(
  131. rotation_days=rotation_days,
  132. is_auto_rotate=1,
  133. updated_at=beijing_now()
  134. )
  135. db.add(config)
  136. else:
  137. config.rotation_days = rotation_days
  138. config.updated_at = beijing_now()
  139. # 创建历史记录
  140. from app.utils.history import create_key_rotation_config_history, create_operation_log
  141. create_key_rotation_config_history(db, config, "INSERT" if not old_rotation_days else "UPDATE")
  142. # 记录操作日志
  143. client_ip = request.client.host if request and request.client else None
  144. create_operation_log(
  145. db=db,
  146. admin_id=current_admin.id,
  147. module="密钥管理",
  148. action="更新轮换周期",
  149. description=f"更新密钥轮换周期:{old_rotation_days}天 -> {rotation_days}天",
  150. old_data={"rotation_days": old_rotation_days},
  151. new_data={"rotation_days": rotation_days},
  152. ip_address=client_ip
  153. )
  154. # 一次性提交所有更改
  155. db.commit()
  156. return {"code": 200, "msg": "更新成功"}