Spaces:
Running

MeloonTop / backend /common /database.py
isold's picture
update
1babfaa
Raw History Blame Contribute Delete
5.38 kB
import base64
import json
import os
from pathlib import Path
from typing import Optional
from dotenv import load_dotenv
from supabase import Client, create_client
from common.logging_config import get_logger
logger = get_logger(__name__)
_BACKEND_DIR = Path(__file__).resolve().parents[1]
_PROJECT_DIR = _BACKEND_DIR.parent
# Load local development configuration without overriding environment variables
# supplied by Hugging Face Spaces or another deployment platform.
load_dotenv(_BACKEND_DIR / ".env")
load_dotenv(_PROJECT_DIR / ".env")
SUPABASE_URL: Optional[str] = None
SUPABASE_KEY: Optional[str] = None
supabase: Optional[Client] = None
def _key_role(key: Optional[str]) -> Optional[str]:
"""Return the Supabase role a key carries, without verifying its signature.
Supabase keys are JWTs whose payload carries ``"role"``. We only *read*
that claim to tell an ``anon`` key apart from a ``service_role`` key --
nothing security-critical depends on this value, it is a diagnostic.
Also understands the newer ``sb_publishable_…`` / ``sb_secret_…`` formats.
"""
if not key:
return None
if key.startswith("sb_publishable_"):
return "anon"
if key.startswith("sb_secret_"):
return "service_role"
parts = key.split(".")
if len(parts) != 3:
return None
payload = parts[1]
try:
padded = payload + "=" * (-len(payload) % 4)
claims = json.loads(base64.urlsafe_b64decode(padded).decode("utf-8"))
except Exception: # noqa: BLE001 - a malformed key is just "unknown"
return None
role = claims.get("role") if isinstance(claims, dict) else None
return str(role) if role else None
def _audit_key_role() -> None:
"""Warn loudly when the backend runs on an anon key.
背景:后端自己用 JWT 鉴权,PostgREST 层看到的角色完全取决于所用 key。
用 anon key 时,为了让写操作不被 42501 拒绝,RLS 必须对 ``anon`` 全表放行
(见 migrations/20261002b_rls_policies.sql)——于是 **anon key 就等于整库
读写凭据**,而 anon key 在 Supabase 的设计里是「可公开」的。
改用 service_role key(仅存于服务端,带 BYPASSRLS)后,anon key 即使泄漏
也读不到任何数据。这里把这个隐性前提变成启动时可见的告警。
默认只告警不阻断:正在运行的线上实例改用 anon key 也能工作,直接
fail-fast 会把站点打挂。需要强制时设 ``MELOON_REQUIRE_SERVICE_ROLE=1``。
"""
role = _key_role(SUPABASE_KEY)
if role != "anon":
if role:
logger.debug("Supabase key 角色: %s", role)
return
message = (
"当前 SUPABASE_KEY 是 anon key。anon key 在 Supabase 的设计中是可公开"
"凭据,而本项目的 RLS 策略必须对 anon 全表放行(否则写入 42501),"
"两者叠加等于把整个数据库的读写权限交了出去。"
"请改用 service_role key(仅配置在服务端),并执行 "
"backend/migrations/20261008_rls_hardening.sql 撤销 anon 的权限。"
)
if os.getenv("MELOON_REQUIRE_SERVICE_ROLE", "").strip().lower() in {
"1",
"true",
"yes",
"on",
}:
raise RuntimeError(message)
logger.warning(message)
def _load_supabase_settings() -> None:
"""Load Supabase settings from the runtime environment."""
global SUPABASE_KEY, SUPABASE_URL
SUPABASE_URL = (
os.getenv("SUPABASE_URL")
or os.getenv("NEXT_PUBLIC_SUPABASE_URL")
or os.getenv("VITE_SUPABASE_URL")
)
SUPABASE_KEY = (
os.getenv("SUPABASE_KEY")
or os.getenv("SUPABASE_ANON_KEY")
or os.getenv("SUPABASE_SERVICE_ROLE_KEY")
)
# Never log the key itself -- only whether one was found.
logger.debug(
"Supabase 配置已加载 (url=%s, key=%s)",
SUPABASE_URL or "<missing>",
"已设置" if SUPABASE_KEY else "<missing>",
)
_audit_key_role()
def _create_supabase_client() -> Optional[Client]:
"""Create the Supabase client when deployment settings are available."""
if not SUPABASE_URL or not SUPABASE_KEY:
logger.warning(
"缺少 SUPABASE_URL/SUPABASE_KEY,Supabase 客户端未创建,"
"所有依赖数据库的接口将不可用"
)
return None
try:
client = create_client(SUPABASE_URL, SUPABASE_KEY)
logger.debug("Supabase 客户端创建成功 (url=%s)", SUPABASE_URL)
return client
except Exception as error:
logger.error("初始化 Supabase 客户端失败: %s", error, exc_info=True)
return None
_load_supabase_settings()
supabase = _create_supabase_client()
def init_supabase() -> Optional[Client]:
"""Initialize or re-initialize the Supabase client."""
global supabase
_load_supabase_settings()
if not supabase:
supabase = _create_supabase_client()
if supabase:
logger.info("Supabase 客户端初始化成功")
else:
logger.debug("Supabase 客户端已存在,复用现有实例")
return supabase
def get_db() -> Optional[Client]:
"""Dependency / helper to get Supabase client instance."""
global supabase
if not supabase:
return init_supabase()
return supabase