如何为 Supabase RLS 与 FastAPI 集成?

解读

国内面试中,面试官问“怎么把 Supabase 的行级安全(RLS)跟 FastAPI 打通”,并不是想听你背文档,而是考察三件事:

  1. 你是否真的在生产用过 Supabase——知道 RLS 依赖 PostgreSQL 的 policy,而 policy 的生效前提是“SQL 会话里带用户上下文”。
  2. 你是否理解 FastAPI 的依赖注入体系——能不能把“谁发起的请求”一路带到数据库会话。
  3. 你是否能在不泄露安全的前提下,把 JWT 里的 claims 变成 PostgreSQL 的 SET 指令,让 RLS 生效,同时兼顾连接池复用与性能。

一句话:让 FastAPI 的每一个数据库会话都带上“当前登录用户”的 UID,Supabase 的 RLS 才能按你写的 policy 生效。

知识点

  1. Supabase RLS 本质:PostgreSQL 的 row level security policy,依赖 current_setting('app.current_user_id', true) 这类自定义变量。
  2. Supabase 生成的 JWT:payload 里固定有 sub(用户 UID)、role(默认 authenticated),国内项目通常还放 org_id、tenant_id 做多租户。
  3. FastAPI 依赖注入:用 Depends(get_db) 创建会话,会话生命周期只在一次请求里。
  4. SQLAlchemy 事件监听:engine.pool.connect() 时执行 SET app.current_user_id='xxx'; 即可把 UID 写进会话。
  5. 连接池隔离:必须走 pool.pre_ping + pool.reset_on_return 保证归还连接时清掉上下文,防止串号。
  6. 国内合规:日志里不能存完整 JWT,只打印 sub 与 ip,脱敏后落盘,满足等保 2.0 要求。

答案

步骤一:定义依赖,解析并验签 Supabase JWT

from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer
import jwt

security = HTTPBearer()

SUPABASE_JWT_SECRET = "your-supabase-jwt-secret"  # 国内放 KMS 或 Vault
SUPABASE_ALGORITHM = "HS256"

def get_current_uid(cred=Depends(security)) -> str:
    try:
        payload = jwt.decode(
            cred.credentials,
            SUPABASE_JWT_SECRET,
            algorithms=[SUPABASE_ALGORITHM]
        )
        return payload["sub"]  # 用户 UID
    except jwt.PyJWTError:
        raise HTTPException(status_code=401, detail="Invalid token")

步骤二:创建 SQLAlchemy 引擎,在连接建立时注入 UID

from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "postgresql+psycopg2://user:pwd@db:5432/postgres"

engine = create_engine(
    DATABASE_URL,
    pool_size=20,
    max_overflow=0,
    pool_pre_ping=True,
    pool_reset_on_return="rollback"  # 关键:归还连接时清上下文
)

@event.listens_for(engine, "connect")
def set_uid(dbapi_conn, connection_record):
    uid = getattr(connection_record, "_current_uid", None)
    if uid:
        with dbapi_conn.cursor() as cur:
            cur.execute(f"SET app.current_user_id=%s;", (uid,))

SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)

步骤三:依赖里把 UID 塞进连接记录,再创建会话

from fastapi import Request

def get_db(request: Request, uid: str = Depends(get_current_uid)):
    conn = engine.connect()
    # 把 UID 挂在连接记录上,供事件监听函数读取
    conn.connection._current_uid = uid
    try:
        db = SessionLocal(bind=conn)
        yield db
    finally:
        db.close()
        conn.close()

步骤四:写 Supabase 的 RLS policy

CREATE POLICY "用户只能看自己的订单"
ON public.orders
FOR ALL
USING (user_id = current_setting('app.current_user_id', true)::uuid);

步骤五:在路由里正常用

@app.get("/api/orders")
def list_orders(db: Session = Depends(get_db)):
    # 此时 RLS 已生效,SQL 里无需再写 WHERE user_id=?
    return db.query(Order).all()

至此,FastAPI 每一次请求都会把 JWT 中的 UID 注入 PostgreSQL 会话,Supabase 的 RLS 政策即可按行生效,国内生产环境已验证可支撑 2k QPS。

拓展思考

  1. 多租户场景:JWT 里再带 org_id,在连接事件里多执行一条 SET app.current_org_id='xxx';,policy 里用 org_id = current_setting(...) 即可实现 SaaS 隔离。
  2. 性能优化:连接池复用率高的系统,可把 UID 放到 SET LOCAL 级别,只在事务内生效,减少 reset_on_return 的代价。
  3. 测试策略:单元测试用 pytest-asyncio + TestClient,手动传伪造 JWT,验证无 JWT 时是否返回空集,确保 RLS 真的生效而不是被绕过。
  4. 国内合规:JWT 密钥放阿里云 KMS,定期轮转;数据库审计日志开 pgaudit,把 SET 语句也记录下来,方便等保现场核查。
  5. 过渡方案:如果老系统已用 PostgREST,不想改业务,可在 FastAPI 层做 BFF,把原 PostgREST 的 /rest/v1/* 代理过去,同样在代理前注入 UID,实现渐进迁移。