auth.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. """
  2. api.middleware.auth — API Key authentication middleware.
  3. Security: Only SHA-256 hash stored. Key shown once at creation.
  4. Format: ap_xxxxxxxxxxxxxxxx (32 char random, prefix ap_)
  5. """
  6. from __future__ import annotations
  7. import hashlib
  8. import time
  9. from typing import Optional
  10. from agentpaas.db.session import get_db
  11. from agentpaas.db.models import now_utc
  12. class AuthError(Exception):
  13. def __init__(self, message: str, code: int = 401):
  14. self.message = message
  15. self.code = code
  16. super().__init__(message)
  17. class TenantContext:
  18. """Injected into request state after authentication."""
  19. def __init__(self, tenant_id: str, tenant_name: str, plan: str,
  20. user_id: str = "", role: str = "developer",
  21. scopes: list = None, rate_limit: int = 60):
  22. self.tenant_id = tenant_id
  23. self.tenant_name = tenant_name
  24. self.plan = plan
  25. self.user_id = user_id
  26. self.role = role
  27. self.scopes = scopes or []
  28. self.rate_limit = rate_limit
  29. def _legacy_hash_key(key: str) -> str:
  30. """Legacy SHA-256 hash (for migration)."""
  31. return hashlib.sha256(key.encode()).hexdigest()
  32. def hash_key(key: str) -> str:
  33. """FIX-08: PBKDF2 hash with random salt for API keys.
  34. New format: "pbkdf2:<hex_salt>:<hex_hash>" — random salt per key.
  35. Legacy format: "<hex_hash>" (64 chars) — fixed salt, kept for backward compat.
  36. Old fixed-salt approach was insecure: salt derived from key prefix is
  37. predictable, enabling precomputation attacks.
  38. """
  39. import secrets as _secrets
  40. salt = _secrets.token_bytes(16) # 128-bit random salt
  41. dk = hashlib.pbkdf2_hmac('sha256', key.encode(), salt, 100000)
  42. return f"pbkdf2:{salt.hex()}:{dk.hex()}"
  43. def _hash_key_legacy(key: str) -> str:
  44. """Legacy PBKDF2 with fixed salt (for verifying old keys during migration)."""
  45. salt = hashlib.sha256(key[:8].encode()).digest()[:16]
  46. dk = hashlib.pbkdf2_hmac('sha256', key.encode(), salt, 100000)
  47. return dk.hex()
  48. def verify_key_hash(key: str, stored_hash: str) -> bool:
  49. """Verify a key against a stored hash. Supports both new and legacy formats."""
  50. if stored_hash.startswith("pbkdf2:"):
  51. # New format: "pbkdf2:<salt_hex>:<hash_hex>"
  52. parts = stored_hash.split(":")
  53. if len(parts) != 3:
  54. return False
  55. salt = bytes.fromhex(parts[1])
  56. expected = parts[2]
  57. dk = hashlib.pbkdf2_hmac('sha256', key.encode(), salt, 100000)
  58. return dk.hex() == expected
  59. else:
  60. # Legacy format: fixed-salt hash (64 hex chars)
  61. return _hash_key_legacy(key) == stored_hash
  62. async def authenticate(api_key: str) -> TenantContext:
  63. """
  64. Authenticate via API Key.
  65. Returns TenantContext with tenant info and permissions.
  66. """
  67. if not api_key:
  68. raise AuthError("Missing API key", 401)
  69. # Strip "Bearer " prefix if present
  70. if api_key.startswith("Bearer "):
  71. api_key = api_key[7:]
  72. db = get_db()
  73. # Look up candidate keys by prefix, then verify hash
  74. key_prefix = api_key[:8]
  75. candidates = db.fetchall(
  76. "SELECT k.*, t.name as tenant_name, t.plan, t.status as tenant_status "
  77. "FROM api_keys k JOIN tenants t ON k.tenant_id = t.id "
  78. "WHERE k.key_prefix = ? AND k.status = 'active'",
  79. (key_prefix,)
  80. )
  81. record = None
  82. for candidate in candidates:
  83. if verify_key_hash(api_key, candidate["key_hash"]):
  84. record = candidate
  85. break
  86. if not record:
  87. # Try legacy SHA-256 hash (no prefix match needed)
  88. legacy_hash = _legacy_hash_key(api_key)
  89. record = db.fetchone(
  90. "SELECT k.*, t.name as tenant_name, t.plan, t.status as tenant_status "
  91. "FROM api_keys k JOIN tenants t ON k.tenant_id = t.id "
  92. "WHERE k.key_hash = ? AND k.status = 'active'",
  93. (legacy_hash,)
  94. )
  95. if record:
  96. # Auto-migrate to PBKDF2
  97. new_hash = hash_key(api_key)
  98. db.execute("UPDATE api_keys SET key_hash = ? WHERE id = ?",
  99. (new_hash, record["id"]))
  100. db.commit()
  101. if not record:
  102. raise AuthError("Invalid API key", 401)
  103. if record["tenant_status"] != "active":
  104. raise AuthError("Tenant suspended", 403)
  105. if record.get("expires_at") and record["expires_at"] < now_utc():
  106. raise AuthError("API key expired", 401)
  107. # Update last_used_at
  108. db.execute("UPDATE api_keys SET last_used_at = ? WHERE id = ?",
  109. (now_utc(), record["id"]))
  110. db.commit()
  111. import json
  112. scopes = json.loads(record.get("scopes", "[]"))
  113. return TenantContext(
  114. tenant_id=record["tenant_id"],
  115. tenant_name=record["tenant_name"],
  116. plan=record["plan"],
  117. user_id=record.get("user_id", ""),
  118. scopes=scopes,
  119. rate_limit=record.get("rate_limit", 60),
  120. )