update
Browse filesFiles changed (9)
- backend/app/unittest/test_auth.py+105
- backend/app/unittest/test_contract_guards.py+46
- backend/app/unittest/test_postgrest_error_handler.py+18
- backend/common/auth/service.py+40
- backend/common/postgrest_errors.py+17-2
- backend/migrations/20261002b_rls_policies.sqlAdded+120
- backend/tools/auth_flow_smoke.pyAdded+271
- backend/tools/cleanup_probe_accounts.pyAdded+106
- backend/tools/rls_probe.pyAdded+227
8 unmodified lines91011121314432 unmodified lines4474484494504518 unmodified linesfrom unittest.mock import MagicMock, patchfrom fastapi.testclient import TestClientsys.path.insert(0,432 unmodified linesself.assertEqual(resp.status_code, 401)if __name__ == "__main__":unittest.main()8 unmodified lines9101112131415432 unmodified lines4484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555568 unmodified linesfrom unittest.mock import MagicMock, patchfrom fastapi.testclient import TestClientfrom postgrest.exceptions import APIErrorsys.path.insert(0,432 unmodified linesself.assertEqual(resp.status_code, 401)# ─────────────────────────────────────────────# Registration must be atomic# ─────────────────────────────────────────────class TestRegistrationIsAtomic(unittest.TestCase):"""A signup that fails after the ``users`` insert must leave no debris.Registration writes ``users`` and then the product profile. When thesecond write failed -- which is what happened while the profile tables hadRLS enabled with no policy -- the account row stayed behind, so the callergot a 500 and the email/username were nevertheless taken. Retrying thenanswered "已被注册" and the account could never be completed."""class _FailingProfileDb:"""``users`` works, the product profile upsert raises ``42501``."""def __init__(self, user_id):self.user_id = user_idself.deleted = []def table(self, name):return self._Query(self, name)class _Query:def __init__(self, outer, name):self._outer = outerself._name = nameself._op = "select"def select(self, *args, **kwargs):self._op = "select"return selfdef insert(self, *args, **kwargs):self._op = "insert"return selfdef upsert(self, *args, **kwargs):self._op = "upsert"return selfdef update(self, *args, **kwargs):self._op = "update"return selfdef delete(self, *args, **kwargs):self._op = "delete"return selfdef eq(self, *args, **kwargs):return selfdef limit(self, *args, **kwargs):return selfdef execute(self):if self._name == "users" and self._op == "insert":return _Result([{"id": self._outer.user_id, "username": "atomic"}])if self._name == "users" and self._op == "delete":self._outer.deleted.append(self._name)return _Result([])if self._op == "upsert":raise APIError({"code": "42501","message": ("new row violates row-level security policy "'for table "exam_profile"'),"details": None,"hint": None,})return _Result([])def test_failed_profile_write_removes_the_users_row(self):user_id = str(uuid.uuid4())email = f"atomic_{uuid.uuid4().hex[:6]}@example.com"db = self._FailingProfileDb(user_id)with patch("common.auth.service.get_db", return_value=db):resp = client.post(AUTH_REGISTER, json={"email": email, "password": "Password123"})self.assertEqual(resp.status_code, 500)self.assertIn("exam_profile", resp.json()["detail"])self.assertIn("users",db.deleted,"注册失败后必须删除已写入的 users 行,否则邮箱/用户名被永久占用",)class _Result:"""Minimal stand-in for a PostgREST response object."""def __init__(self, data):self.data = dataself.count = len(data)if __name__ == "__main__":unittest.main()
299 unmodified lines300301302303304299 unmodified lines)if __name__ == "__main__":unittest.main()299 unmodified lines300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350299 unmodified lines)# ════════════════════════════════════════════════════════════════════════════# Guard: the RLS remediation must exist and cover the registration tables# ════════════════════════════════════════════════════════════════════════════# Creating the tables is not enough. Supabase enables RLS on new tables in the# ``public`` schema but creates no policies, and the backend talks to PostgREST# with the **anon** key, so every write to such a table fails with ``42501``.# Registration was broken exactly this way: it writes the product profile with# ``upsert(..., on_conflict="user_id")``, which needs *both* an INSERT and an# UPDATE policy. See ``tools/rls_probe.py`` for the live check.RLS_SCRIPT = BACKEND_DIR / "migrations" / "20261002b_rls_policies.sql"class TestRlsRemediationCoversProfileTables(unittest.TestCase):"""``20261002b_rls_policies.sql`` must grant policies for the profile tables."""def test_rls_script_exists(self):self.assertTrue(RLS_SCRIPT.is_file(),f"missing RLS remediation script: {RLS_SCRIPT}",)def test_every_product_profile_table_is_covered(self):from common.auth.service import PRODUCT_PROFILE_TABLESsql = RLS_SCRIPT.read_text(encoding="utf-8")missing = sorted(tablefor table in set(PRODUCT_PROFILE_TABLES.values())if table not in sql)self.assertEqual(missing,[],"these product profile tables are written at registration but the ""RLS script does not mention them:\n"+ "\n".join(f" - {table}" for table in missing),)def test_rls_script_is_parseable_sql(self):try:from pglast import parse_sqlexcept ImportError: # pragma: no cover - optional dev dependencyself.skipTest("pglast 未安装,跳过 SQL 语法校验")parse_sql(RLS_SCRIPT.read_text(encoding="utf-8"))if __name__ == "__main__":unittest.main()
26 unmodified lines27282930313255 unmodified lines88899091929326 unmodified linesMISSING_COLUMN,MISSING_TABLE,NO_ROWS,describe,register_postgrest_error_handler,)55 unmodified linesself.assertEqual(status, 404)self.assertIn("标识符格式不合法", detail)def test_unknown_code_keeps_the_raw_message(self):status, detail = describe(_api_error("XX999", "something exploded", hint="try again")26 unmodified lines2728293031323355 unmodified lines899091929394959697989910010110210310410510610710810911011126 unmodified linesMISSING_COLUMN,MISSING_TABLE,NO_ROWS,RLS_DENIED,describe,register_postgrest_error_handler,)55 unmodified linesself.assertEqual(status, 404)self.assertIn("标识符格式不合法", detail)def test_rls_denial_points_at_the_rls_script(self):"""``42501`` means Supabase created the table with RLS but no policy.The backend uses the anon key, so this is a provisioning gap ratherthan a bad request -- the message must name the remediation."""status, detail = describe(_api_error(RLS_DENIED,'new row violates row-level security policy for table ''"exam_profile"',))self.assertEqual(status, 500)self.assertIn("exam_profile", detail)self.assertIn("20261002b_rls_policies.sql", detail)def test_unknown_code_keeps_the_raw_message(self):status, detail = describe(_api_error("XX999", "something exploded", hint="try again")
234 unmodified lines23523623723823924052 unmodified lines29329429529629729844 unmodified lines343344345346347348349350234 unmodified linesreturn get_product_profile(user_id, product, db=database_client) or rowdef register_user(credentials: UnifiedAuthRequest,db=None,52 unmodified linesif existing_username.data:raise HTTPException(status_code=400, detail="该用户名或邮箱已被注册,请直接登录")try:# 1. Insert into the shared users tableres = (44 unmodified lines"success": True,}except HTTPException:raiseexcept Exception as e:raise http_error_from(e, 400) from e234 unmodified lines23523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627752 unmodified lines33033133233333433533644 unmodified lines381382383384385386387388389390234 unmodified linesreturn get_product_profile(user_id, product, db=database_client) or rowdef _rollback_registration(database_client, user_id: Optional[str]) -> None:"""Undo step 1 when step 2 of registration fails.Registration is two writes against two tables. Without this, a failure inthe profile upsert (for example ``42501`` when the profile table has RLSenabled but no policy) left the ``users`` row behind: the caller saw a 500,yet the email and username were now taken, so retrying answered"该用户名或邮箱已被注册" and the account could never be completed.Deliberately best-effort -- the original error is more useful than arollback failure, so the latter is only reported, never raised.The affected-row count is checked on purpose: a DELETE that RLS hides fromthe caller returns ``200`` with an empty body instead of an error, so"the call succeeded" is not the same as "the row is gone"."""if not user_id:returntry:result = (database_client.table("users").delete().eq("id", user_id).execute())if not result.data:print(f"Warning: rollback of user {user_id} removed 0 rows -- the ""account row is still present (check DELETE permission / RLS ""policy on users).")except Exception as error: # noqa: BLE001print(f"Warning: could not roll back partially created user {user_id}: "f"{error}")def register_user(credentials: UnifiedAuthRequest,db=None,52 unmodified linesif existing_username.data:raise HTTPException(status_code=400, detail="该用户名或邮箱已被注册,请直接登录")user_id: Optional[str] = Nonetry:# 1. Insert into the shared users tableres = (44 unmodified lines"success": True,}except HTTPException:_rollback_registration(database_client, user_id)raiseexcept Exception as e:_rollback_registration(database_client, user_id)raise http_error_from(e, 400) from e
43 unmodified lines444546474849505152535438 unmodified lines93949596979843 unmodified linesMISSING_COLUMN = "PGRST204"NO_ROWS = "PGRST116"INVALID_CAST = "22P02"MIGRATION_SCRIPT = "backend/migrations/20261002_deploy_all.sql"# ``Could not find the table 'public.exam_user_downloads' in the schema cache``_QUOTED_OBJECT = re.compile(r"'([^']+)'")def _quoted_object(message: Optional[str]) -> Optional[str]:38 unmodified lines# identifier simply cannot match any row, so "not found" is accurate.return 404, "资源不存在:标识符格式不合法"return 500, f"数据库查询失败({code or 'unknown'}):{message}"43 unmodified lines444546474849505152535455565758596038 unmodified lines9910010110210310410510610710810911011111211343 unmodified linesMISSING_COLUMN = "PGRST204"NO_ROWS = "PGRST116"INVALID_CAST = "22P02"RLS_DENIED = "42501"MIGRATION_SCRIPT = "backend/migrations/20261002_deploy_all.sql"RLS_SCRIPT = "backend/migrations/20261002b_rls_policies.sql"# PostgREST quotes the object it is complaining about, but the quote style# varies by error: PGRST205 uses single quotes# (``Could not find the table 'public.exam_user_downloads' ...``) while 42501# uses double quotes# (``new row violates row-level security policy for table "exam_profile"``)._QUOTED_OBJECT = re.compile(r"['\"]([^'\"]+)['\"]")def _quoted_object(message: Optional[str]) -> Optional[str]:38 unmodified lines# identifier simply cannot match any row, so "not found" is accurate.return 404, "资源不存在:标识符格式不合法"if code == RLS_DENIED:# Row Level Security refused the write. The backend uses the anon key,# so a table that Supabase created with RLS on and no policy answers# 42501 for every write -- a provisioning gap, not a bad request.detail = f"数据库拒绝写入数据表 {obj}(RLS 无策略)。" if obj else ("数据库拒绝写入(RLS 无策略)。")return 500, f"{detail}请执行 {RLS_SCRIPT} 后重试。"return 500, f"数据库查询失败({code or 'unknown'}):{message}"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120-- ============================================================================-- 20261002b_rls_policies.sql---- 修复:注册 / 新建数据被 RLS 拒绝(PostgREST 错误码 42501)-- ------------------------------------------------------------------------------ 现象-- POST /api/v1/auth/register 等注册接口返回 500:-- {"code": "42501", "message": "new row violates row-level security policy-- for table \"exam_profile\""}---- 根因-- 后端用 **anon key** 直连 PostgREST,自己用 JWT 做鉴权(前端不直连-- Supabase,也拿不到 anon key)。因此 PostgREST 层面看到的角色始终是-- anon,RLS 策略必须显式放行 anon,否则任何写入都会 42501。---- 这些表由 20261002_deploy_all.sql 通过 SQL Editor 创建,Supabase 对-- public schema 的新表默认开启 RLS 但不自动建策略,于是写入被拦。---- 证据(执行前用 backend/tools/rls_probe.py 实测)-- 10 张表缺 INSERT 策略,写入直接报 42501:-- chatbi_profile, exam_profile, exam_score_history, exam_user_mistakes,-- top_dynamics, top_games, top_profile, top_prompts, top_ratings, top_tools---- 其中三张产品档案表注册时用的是 upsert(INSERT ... ON CONFLICT DO-- UPDATE)。PostgreSQL 无论是否真的发生冲突都会规划 UPDATE 分支,所以-- INSERT 与 UPDATE 策略缺一不可 —— 只补 INSERT 仍然会失败。---- 另外 public.users 的 DELETE 被策略静默拦截:删除返回 200 但影响 0 行,-- 行仍然存在。这会让注册失败后的回滚(见 common/auth/service.py::-- _rollback_registration)形同虚设,于是"注册失败但邮箱被占用"的问题-- 依旧存在。users 因此也纳入本文件。---- 为什么授予 FOR ALL 而不是只补 INSERT-- 同样的 42501 会因为缺少任何一类策略而重现,而代码对这些表确实会做-- INSERT / UPDATE / DELETE。这里按"每张表整体放行"处理,与 users、-- exam_paper、top_comments 等既有表的实际行为保持一致。---- 安全性说明-- anon key 只在后端进程中使用,不随前端产物下发(MeloonExam 的-- supabaseClient 是用户运行时自填 URL/Key,默认走本地存储)。-- 即本文件的策略不会把数据面暴露给浏览器。若日后改为前端直连-- Supabase,必须重做这套策略(改为基于 auth.uid() 的细粒度策略)。---- 幂等:可重复执行。-- ============================================================================
BEGIN;
DO $$DECLARE target TEXT; policy_name TEXT; tables TEXT[] := ARRAY[ 'users', 'chatbi_profile', 'exam_profile', 'exam_score_history', 'exam_user_mistakes', 'top_dynamics', 'top_games', 'top_profile', 'top_prompts', 'top_ratings', 'top_tools' ];BEGIN FOREACH target IN ARRAY tables LOOP -- 表不存在则跳过,方便在部分部署上安全执行。 IF NOT EXISTS ( SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relname = target AND c.relkind = 'r' ) THEN RAISE NOTICE '[skip] public.% 不存在,跳过', target; CONTINUE; END IF;
-- 确保 RLS 处于开启状态:关闭 RLS 的表不需要策略, -- 但显式开启可让"策略已就位"这一事实与状态一致。 EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', target);
policy_name := target || '_backend_all';
-- 幂等:先删后建,避免重复执行时报 42710 策略已存在。 EXECUTE format('DROP POLICY IF EXISTS %I ON public.%I', policy_name, target); EXECUTE format( 'CREATE POLICY %I ON public.%I ' 'FOR ALL TO anon, authenticated ' 'USING (true) WITH CHECK (true)', policy_name, target );
RAISE NOTICE '[ok] public.% 已放行 anon/authenticated(FOR ALL)', target; END LOOP;END $$;
COMMIT;
-- ============================================================================-- 自检:确认每张表都有一条放行 anon 的策略-- 期望:11 行,且 anon_policies >= 1-- ============================================================================-- SELECT c.relname AS table_name,-- count(p.policyname) FILTER (WHERE p.roles::text LIKE '%anon%') AS anon_policies-- FROM pg_class c-- JOIN pg_namespace n ON n.oid = c.relnamespace-- LEFT JOIN pg_policies p ON p.schemaname = n.nspname AND p.tablename = c.relname-- WHERE n.nspname = 'public'-- AND c.relname IN ('users','chatbi_profile','exam_profile','exam_score_history',-- 'exam_user_mistakes','top_dynamics','top_games',-- 'top_profile','top_prompts','top_ratings','top_tools')-- GROUP BY c.relname-- ORDER BY c.relname;
-- 执行后请运行以下命令复查(期望"后端需要的所有写操作均被允许"):-- python backend/tools/rls_probe.py-- python backend/tools/auth_flow_smoke.py --base-url http://127.0.0.1:8000123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271#!/usr/bin/env python3"""End-to-end smoke for the authentication + user-center flow.
``live_smoke.py`` sweeps *read-only* routes; this covers the write path thatmatters most: register -> login -> read profile -> update profile -> sync. Thatchain is the heart of the unified user model (``users`` + one ``*_profile`` rowper product) and it was exactly what 500ed while the deployed database wasbehind the code, so it deserves its own check.
Every account it creates is a throwaway: the identifier carries a random suffixand the script deletes what it created on the way out (``users`` cascades to theproduct profile tables; the retired ``exam_profiles`` table has no foreign key,so it is cleaned explicitly).
Usage::
python backend/tools/auth_flow_smoke.py python backend/tools/auth_flow_smoke.py --base-url http://127.0.0.1:8000 python backend/tools/auth_flow_smoke.py --keep # leave rows for inspection
Exit code 0 only when every step of every surface succeeds."""from __future__ import annotations
import argparseimport jsonimport sysimport urllib.errorimport urllib.requestimport uuidfrom pathlib import Path
BACKEND_DIR = Path(__file__).resolve().parents[1]sys.path.insert(0, str(BACKEND_DIR))
DEFAULT_BASE = "https://isold23-meloontop.hf.space"TIMEOUT = 30
#: (label, register path, login path) -- one per auth surface, all of which must#: converge on the same ``users`` account store.SURFACES = [ ("MeloonChatBI", "/api/v1/auth/register", "/api/v1/auth/login"), ("MeloonExam(legacy /api/auth)", "/api/auth/register", "/api/auth/login"), ("MeloonExam", "/api/exam/auth/register", "/api/exam/auth/login"), ("MeloonTop", "/api/top/auth/register", "/api/top/auth/login"),]
class Failure(Exception): """A step did not behave as the contract requires."""
def call( base_url: str, method: str, path: str, payload: dict | None = None, token: str | None = None,) -> tuple[int, object]: """Issue one request and return ``(status, decoded_body)``.""" url = base_url.rstrip("/") + path headers = {"Accept": "application/json"} if token: headers["Authorization"] = f"Bearer {token}" data = None if payload is not None: headers["Content-Type"] = "application/json" data = json.dumps(payload).encode()
request = urllib.request.Request(url, data=data, headers=headers, method=method) host = url.split("//", 1)[-1].split("/", 1)[0].split(":")[0] if host in ("127.0.0.1", "localhost", "::1", "0.0.0.0"): opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) else: opener = urllib.request.build_opener()
try: with opener.open(request, timeout=TIMEOUT) as response: body = response.read().decode("utf-8", "replace") status = response.status except urllib.error.HTTPError as error: body = error.read().decode("utf-8", "replace") status = error.code
try: return status, json.loads(body) if body else None except json.JSONDecodeError: return status, body
def expect(condition: bool, message: str) -> None: if not condition: raise Failure(message)
def token_of(body: object) -> str | None: """Pull the access token out of whichever envelope the surface returns.""" if not isinstance(body, dict): return None for key in ("access_token", "accessToken", "token"): value = body.get(key) if isinstance(value, str) and value: return value nested = body.get("data") if isinstance(nested, dict): for key in ("access_token", "accessToken", "token"): value = nested.get(key) if isinstance(value, str) and value: return value return None
def run_surface(base_url: str, label: str, register: str, login: str) -> dict: """Drive one auth surface end to end; return the created identifiers.""" suffix = uuid.uuid4().hex[:10] identifier = f"smoke_{suffix}" password = f"Smoke!{suffix}" # ``.invalid`` / ``.test`` / ``example.com`` are special-use names that # email-validator rejects outright, so use a syntactically ordinary domain. email = f"{identifier}@meloon-smoke.edu.cn"
credentials = { "identifier": identifier, "username": identifier, "email": email, "password": password, "nickname": f"联调探针 {suffix}", "role": "student", }
status, body = call(base_url, "POST", register, credentials) expect( status in (200, 201), f"注册失败:HTTP {status} {json.dumps(body, ensure_ascii=False)[:200]}", ) print(f" 注册 200 {identifier}")
status, body = call( base_url, "POST", login, {"identifier": identifier, "password": password} ) expect( status == 200, f"登录失败:HTTP {status} {json.dumps(body, ensure_ascii=False)[:200]}", ) token = token_of(body) expect(bool(token), "登录响应里没有 token") print(" 登录 200 已签发 token")
# The unified user center must see the account every surface just created. status, profile = call(base_url, "GET", "/api/users/me", token=token) expect( status == 200, "统一用户中心读不到刚注册的账号:" f"HTTP {status} {json.dumps(profile, ensure_ascii=False)[:200]}", ) expect( isinstance(profile, dict) and profile.get("id"), f"/api/users/me 返回结构异常:{profile!r}", ) print(f" 读取档案 200 id={profile['id']}")
# Profile update must persist across both tables (users + exam_profile). update = { "nickname": f"已更新 {suffix}", "bio": "联调写入的简介", "school": "联调中学", "grade": "高三年级", "avatar": "https://example.invalid/avatar.png", } status, updated = call(base_url, "PUT", "/api/users/me", update, token=token) expect( status == 200, f"更新档案失败:HTTP {status} {json.dumps(updated, ensure_ascii=False)[:200]}", ) print(" 更新档案 200")
status, reread = call(base_url, "GET", "/api/users/me", token=token) expect(status == 200, f"更新后重读失败:HTTP {status}") expect( isinstance(reread, dict) and reread.get("nickname") == update["nickname"], f"昵称未持久化:期望 {update['nickname']!r},实际 {reread!r}", ) expect( reread.get("school") == update["school"], f"exam_profile 字段未持久化:school={reread.get('school')!r}", ) print(" 重读校验 200 昵称/学校均已持久化")
status, sync = call(base_url, "GET", "/api/users/me/sync", token=token) expect( status == 200, f"同步接口失败:HTTP {status} {json.dumps(sync, ensure_ascii=False)[:200]}", ) print(" 数据同步 200")
return { "identifier": identifier, "email": email, "user_id": profile["id"], }
def cleanup(base_url: str, created: list[dict]) -> None: """Delete every row this run created.
``users`` cascades to ``exam_profile`` / ``top_profile`` / ``chatbi_profile`` (``ON DELETE CASCADE``), but the retired ``exam_profiles`` table has no foreign key, so it is cleaned by ``id`` as well. """ from common.database import get_db
client = get_db() if client is None: print(" ! 无法初始化 Supabase 客户端,跳过清理") return
for row in created: user_id = row["user_id"] for table, column, value in ( ("exam_profiles", "id", user_id), ("users", "id", user_id), ): try: client.table(table).delete().eq(column, value).execute() except Exception as error: # noqa: BLE001 code = getattr(error, "code", None) print(f" ! 清理 {table} 失败({code}):{error}")
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base-url", default=DEFAULT_BASE) parser.add_argument( "--keep", action="store_true", help="保留测试账号,便于人工排查", ) args = parser.parse_args()
print(f"target : {args.base_url}") print()
created: list[dict] = [] failures: list[str] = []
for label, register, login in SURFACES: print(f"── {label}") try: created.append(run_surface(args.base_url, label, register, login)) print(" 结果 通过") except Failure as error: failures.append(f"{label}: {error}") print(f" 结果 失败 -> {error}") print()
if created and not args.keep: print("── 清理") cleanup(args.base_url, created) print(f" 已删除 {len(created)} 个测试账号") print()
print("── 汇总 ────────────────────────────────────────────") print(f" 通过 {len(created)}/{len(SURFACES)}") for failure in failures: print(f" 失败:{failure}")
return 1 if failures else 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106#!/usr/bin/env python3"""Remove the throwaway accounts the smoke tools create.
``auth_flow_smoke.py`` and ``rls_probe.py`` create accounts named``smoke_*`` / ``rls_*``. They clean up after themselves, but a run that failshalf-way (or a run made while the database still refused DELETEs) can leaverows behind. This script finds them and removes them, then **reads back** toconfirm -- a DELETE that RLS hides from the caller answers ``200`` whileremoving nothing, so "no error" is not proof.
Usage::
python backend/tools/cleanup_probe_accounts.py # dry run python backend/tools/cleanup_probe_accounts.py --apply"""from __future__ import annotations
import argparseimport sysfrom pathlib import Path
BACKEND_DIR = Path(__file__).resolve().parents[1]sys.path.insert(0, str(BACKEND_DIR))
PREFIXES = ("smoke_", "rls_")
#: Tables keyed by ``user_id`` that must go before the account row.CHILD_TABLES = ("exam_profile", "top_profile", "chatbi_profile")
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--apply", action="store_true", help="actually delete; without it this is a dry run", ) args = parser.parse_args()
from common.database import get_db
client = get_db() if client is None: print("无法初始化 Supabase 客户端") return 2
rows = client.table("users").select("id,username,email").execute().data or [] targets = [ row for row in rows if str(row.get("username") or "").startswith(PREFIXES) ]
print(f"users 总行数 : {len(rows)}") print(f"探针账号 : {len(targets)}") for row in targets: print(f" - {row['username']} ({row['id']})")
if not targets: print("\n无需清理。") return 0
if not args.apply: print("\n这是预演。加 --apply 才会真正删除。") return 0
print("\n── 清理") removed = 0 for row in targets: user_id = row["id"] for table in CHILD_TABLES: try: client.table(table).delete().eq("user_id", user_id).execute() except Exception: # noqa: BLE001 pass try: client.table("exam_profiles").delete().eq("id", user_id).execute() except Exception: # noqa: BLE001 pass try: client.table("users").delete().eq("id", user_id).execute() except Exception as error: # noqa: BLE001 print(f" ! {row['username']} 删除报错:{error}") continue
# Verify instead of trusting the 200. left = ( client.table("users").select("id").eq("id", user_id).execute().data or [] ) if left: print(f" ! {row['username']} 仍然存在(DELETE 被 RLS 静默拦截)") else: removed += 1 print(f" - {row['username']} 已删除")
print(f"\n实际删除 {removed}/{len(targets)}") if removed < len(targets): print("提示:users 的 DELETE 需要策略放行,请先执行") print(" backend/migrations/20261002b_rls_policies.sql") return 1 return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227#!/usr/bin/env python3"""Report the live Supabase write permissions the backend actually needs.
The backend talks to PostgREST with the **anon** key and does its own JWThandling, so PostgREST-level RLS evaluates the role ``anon`` for every request.A table with RLS enabled and no permissive policy for that role rejects thewrite with ``42501`` even when the request is perfectly well-formed.
Why INSERT alone is not enough: registration writes the product profile with``upsert(..., on_conflict="user_id")``, i.e. ``INSERT ... ON CONFLICT DOUPDATE``. PostgreSQL plans the UPDATE arm of that statement regardless ofwhether a conflict occurs, so the table needs an **UPDATE** policy as well --``insert({})`` passing tells you nothing about ``upsert``.
Probing is non-destructive:
* ``insert({})`` -> RLS blocks first (``42501``) or the schema rejects it (``23502``/``23514``), which proves the policy let it through. No row is written. This is the only verdict the probe can settle on its own.
**UPDATE / DELETE are reported as ``未验证`` on purpose.** A policy of``USING (false)`` hides every row from the statement, so the request comes back``200`` with an empty body -- indistinguishable from success unless a real rowis created, mutated and read back. The earlier version of this probe filteredon an id that could not exist and therefore called such tables "allowed"; thelive ``users`` table is exactly this case (DELETE returns 200, removes nothing).The probe deliberately does not create scratch rows just to answer thequestion, so it says so instead of guessing. The definitive check lives in``tools/auth_flow_smoke.py``, which exercises real writes and reads them back.
Usage::
python backend/tools/rls_probe.py python backend/tools/rls_probe.py --quiet # only the remediation list"""from __future__ import annotations
import argparseimport reimport sysimport uuidfrom pathlib import Path
BACKEND_DIR = Path(__file__).resolve().parents[1]sys.path.insert(0, str(BACKEND_DIR))
TABLE_REF_RE = re.compile(r'\.table\(\s*["\']([^"\']+)["\']\s*\)')
#: Tables the code only probes for backwards compatibility.LEGACY_PROBE_TABLES = {"exam_profiles"}
ALLOWED = "允许"BLOCKED = "拒绝"MISSING = "表不存在"UNVERIFIED = "未验证"
OPERATIONS = ("INSERT", "UPDATE", "DELETE")
def referenced_tables() -> list[str]: """Every table the backend touches.
A literal ``.table(...)`` scan misses tables reached through a mapping -- ``top_profile`` and ``chatbi_profile`` are only named in ``common.auth.service.PRODUCT_PROFILE_TABLES``, and skipping them would have hidden two of the tables that actually break registration. """ tables: set[str] = set() for path in BACKEND_DIR.rglob("*.py"): if "unittest" in path.parts or "__pycache__" in path.parts: continue tables |= set(TABLE_REF_RE.findall(path.read_text(encoding="utf-8")))
try: from common.auth.service import PRODUCT_PROFILE_TABLES
tables |= set(PRODUCT_PROFILE_TABLES.values()) except Exception: # noqa: BLE001 - probe must still work standalone pass
return sorted(tables)
def _code(error: Exception) -> str | None: return getattr(error, "code", None)
def probe_insert(client, table: str) -> tuple[str, str]: try: client.table(table).insert({}).execute() return ALLOWED, "空行插入成功" except Exception as error: # noqa: BLE001 code = _code(error) if code == "42501": return BLOCKED, "42501" if code == "PGRST205": return MISSING, "PGRST205" return ALLOWED, f"schema 拒绝({code}),说明策略已放行"
def probe_upsert(client, table: str, user_id: str) -> tuple[str, str]: """Attempt the exact statement registration issues.
``upsert`` compiles to ``INSERT ... ON CONFLICT DO UPDATE``; PostgreSQL plans the UPDATE arm whether or not a conflict occurs, so this can fail with ``42501`` even on a table where a plain ``insert`` succeeds. That is precisely the gap a bare INSERT probe misses. """ try: client.table(table).upsert({"user_id": user_id}, on_conflict="user_id").execute() return ALLOWED, "upsert 成功" except Exception as error: # noqa: BLE001 code = _code(error) if code == "42501": return BLOCKED, "42501(缺 INSERT 或 UPDATE 策略)" if code == "PGRST205": return MISSING, "PGRST205" return f"错误 {code}", (getattr(error, "message", None) or "")[:60]
def run_upsert_phase(client) -> dict[str, str]: """Create a throwaway account, exercise every profile upsert, clean up.""" user_id = str(uuid.uuid4()) identifier = f"rls_upsert_{uuid.uuid4().hex[:8]}" try: client.table("users").insert( { "id": user_id, "username": identifier, "email": f"{identifier}@meloon-smoke.edu.cn", "password_hash": "probe-not-a-real-hash", "role": "student", } ).execute() except Exception as error: # noqa: BLE001 print(f" 无法创建探测账号({_code(error)}),跳过 upsert 阶段") return {}
results: dict[str, str] = {} try: for table in ("exam_profile", "top_profile", "chatbi_profile"): verdict, detail = probe_upsert(client, table, user_id) results[table] = verdict print(f" {table:<24} upsert {verdict:<10}{detail}") finally: for table in ("exam_profile", "top_profile", "chatbi_profile"): try: client.table(table).delete().eq("user_id", user_id).execute() except Exception: # noqa: BLE001 pass try: client.table("users").delete().eq("id", user_id).execute() except Exception: # noqa: BLE001 pass
return results
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--quiet", action="store_true", help="只输出结论") args = parser.parse_args()
from common.database import get_db
client = get_db() if client is None: print("无法初始化 Supabase 客户端") return 2
matrix: dict[str, dict[str, str]] = {}
if not args.quiet: print(f"{'表':<24}" + "".join(f"{op:<12}" for op in OPERATIONS)) print("─" * 60)
for table in referenced_tables(): if table in LEGACY_PROBE_TABLES: continue row: dict[str, str] = {} row["INSERT"] = probe_insert(client, table)[0] # A 200 with an empty body means "no rows matched", which is what both # "policy denies everything" and "the filter matched nothing" look # like. Without creating a scratch row there is no way to tell them # apart, so do not pretend otherwise. for operation in ("UPDATE", "DELETE"): row[operation] = UNVERIFIED matrix[table] = row
if not args.quiet: print(f"{table:<24}" + "".join(f"{row[op]:<12}" for op in OPERATIONS))
if not args.quiet: print() print("── 产品档案 upsert(注册流程实际使用的语句)") upsert_results = run_upsert_phase(client)
blocked = { table: [op for op in OPERATIONS if row.get(op) == BLOCKED] for table, row in matrix.items() if any(row.get(op) == BLOCKED for op in OPERATIONS) } blocked_upserts = [t for t, v in upsert_results.items() if v == BLOCKED]
print() print("── 结论 ────────────────────────────────────────────") if not blocked and not blocked_upserts: print(" 后端需要的所有写操作均被允许。") return 0
if blocked: print(f" {len(blocked)} 张表禁止 anon 的部分写操作:") for table, operations in sorted(blocked.items()): print(f" - {table:<24} 缺:{', '.join(operations)}") if blocked_upserts: print(f" {len(blocked_upserts)} 张产品档案表 upsert 被拒:") for table in sorted(blocked_upserts): print(f" - {table}") print() print(" 后端用 anon key 直连 PostgREST,这些操作会 42501。") print(" 注册流程写产品档案用的是 upsert,因此 INSERT 和 UPDATE 都必须放行。") print(" 修复:执行 backend/migrations/20261002b_rls_policies.sql") return 1
if __name__ == "__main__": raise SystemExit(main())backend/app/unittest/test_auth.py+105
backend/app/unittest/test_contract_guards.py+46
backend/app/unittest/test_postgrest_error_handler.py+18
backend/common/auth/service.py+40
backend/common/postgrest_errors.py+17-2
backend/migrations/20261002b_rls_policies.sqlAdded+120
backend/tools/auth_flow_smoke.pyAdded+271
backend/tools/cleanup_probe_accounts.pyAdded+106
backend/tools/rls_probe.pyAdded+227