56 lines
1.6 KiB
Python

import base64
from typing import Optional, Tuple
def _clean(value: Optional[str]) -> str:
"""
Normalize values coming from env files where quotes might be preserved.
"""
if not value:
return ""
return value.strip().strip('"').strip()
def resolve_api_key(api_id: Optional[str], api_key: Optional[str]) -> Tuple[Optional[str], Optional[str]]:
"""
Accept various API key formats and return (api_id, api_key).
Supported formats:
- Explicit ES_API_ID and ES_API_KEY values.
- ES_API_KEY that already contains \"id:key\".
- ES_API_KEY that is the base64 encoding of \"id:key\".
"""
cleaned_id = _clean(api_id)
cleaned_key = _clean(api_key)
if cleaned_id and cleaned_key:
return cleaned_id, cleaned_key
if not cleaned_key:
return None, None
# Raw "id:key" format
if ":" in cleaned_key:
potential_id, potential_key = cleaned_key.split(":", 1)
if potential_id and potential_key:
return potential_id, potential_key
# Base64 encoded "id:key" format
try:
decoded = base64.b64decode(cleaned_key, validate=True).decode()
if ":" in decoded:
potential_id, potential_key = decoded.split(":", 1)
if potential_id and potential_key:
return potential_id, potential_key
except Exception:
pass
return None, None
def build_api_key_header(api_id: str, api_key: str) -> str:
"""
Return the value for the Authorization header using ApiKey auth.
"""
token = base64.b64encode(f"{api_id}:{api_key}".encode()).decode()
return f"ApiKey {token}"