From ec5d9398b5f872aa9711852ad848e62061358598 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Fri, 16 Oct 2026 10:14:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AF=BC=E5=85=A5=E6=B8=85=E5=8D=95=E3=80=81?= =?UTF-8?q?=E7=B4=AF=E7=A7=AF=E5=BF=AB=E7=85=A7=E6=B8=85=E5=8D=95=E3=80=81?= =?UTF-8?q?=E4=BD=9C=E5=BA=9F=E8=AE=B0=E5=BD=95=E3=80=81=E6=B8=85=E9=99=A4?= =?UTF-8?q?=E5=8E=9F=E4=BB=B6=E8=AE=B0=E5=BD=95=E5=A6=82=E5=AE=9E=E5=86=99?= =?UTF-8?q?=E3=80=8C=E6=98=AF=E5=90=A6=E8=AE=A4=E8=AF=81=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为什么:这四处的 signed_by.verified / signed_by_verified 写死 False。开了登录时署名就是登录的人,封存证据里却记着 「未认证」,和审计表、待办派单、run.origin 的 verified 口径对不上——留痕记错了事实(05-已知遗留 (c))。 做了什么:api/deps 新增 signer_verified()(开了登录、这次请求的身份认证过时为真;关登录、不在请求里为假),和 signer_of 配对。表格导入提交、按期移除 / 作废接受、清除原件三个写接口在请求那一刻算好,和 signed_by 一起往下传到 recipe_imports._manifest、source_versions.manifest_doc / _revoked_record、table_versions.purge_import_raw;没有署名的 (退回暂存区上记的那个)照实记未认证。新参数都带默认值 False:运行里按配方导入一期(files/imports.py,署名取动作确认人 或发起人)没有请求身份,照旧记未认证。已封存的旧清单不改写,读取复验照旧。 测试:test_signer_verified(signer_verified 跟请求身份走;作废记录照给的写;开登录首次导入的清单 verified=True、清除原件 记录 signed_by 是登录的人且 verified=True,请求体里填的名字不看)。关登录的老断言(False)照旧通过。 --- backend/app/api/datasources.py | 5 ++- backend/app/api/deps.py | 9 ++++ backend/app/api/source_versions.py | 7 +-- backend/app/api/table_imports.py | 5 ++- backend/app/data/recipe_imports.py | 15 ++++--- backend/app/data/source_versions.py | 30 ++++++++----- backend/app/data/table_versions.py | 6 ++- backend/tests/test_signer_verified.py | 63 +++++++++++++++++++++++++++ 8 files changed, 114 insertions(+), 26 deletions(-) create mode 100644 backend/tests/test_signer_verified.py diff --git a/backend/app/api/datasources.py b/backend/app/api/datasources.py index 38bebb9b..3f8a972f 100644 --- a/backend/app/api/datasources.py +++ b/backend/app/api/datasources.py @@ -18,7 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.api import health from app.api.coded import PROFILE_SETTINGS_INVALID, CodedHTTPException -from app.api.deps import signer_of +from app.api.deps import signer_of, signer_verified from app.core.errors import AUTH, NETWORK, TIMEOUT, classify, explain, raw from app.core.config import settings from app.core.crypto import encrypt, mask @@ -1104,7 +1104,8 @@ async def purge_raw( if imp.raw_state == "purged": raise CodedHTTPException(409, "这次导入的原件已经清除", "raw_already_purged") try: - purged = await table_versions.purge_import_raw(session, imp, reason=reason, signed_by=signed_by) + purged = await table_versions.purge_import_raw(session, imp, reason=reason, signed_by=signed_by, + signer_verified=signer_verified()) except table_versions.StoreUnavailable as e: raise CodedHTTPException(503, str(e), "store_unavailable") from e deleted, others = purged.deleted, purged.others diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py index 6fa03e2d..eebbc76e 100644 --- a/backend/app/api/deps.py +++ b/backend/app/api/deps.py @@ -105,6 +105,15 @@ def signer_of(given: Any, header: str | None, limit: int = 100) -> str | None: return decode_actor(header) +def signer_verified() -> bool: + """signer_of 记下的署名是不是认证过的身份:开了登录、这次请求的身份认证过时为真;关登录时署名是自报的,为假。 + + 导入清单、累积快照清单、作废记录、清除原件记录的「是否认证」记这个(docs/design/next-round/05-已知遗留.md (c)), + 和审计表、待办派单、run.origin 的 verified 同一个口径。证据要在生成那一刻定下:调用方和 signed_by 一起往下传。""" + principal = _principal.get() + return principal is not None and principal.mode != "off" and bool(principal.verified) + + def current_principal() -> Principal: """这次请求的完整身份。关登录时:等同 admin、未认证,username 是中间件按 X-Actor 解出的自报署名;中间件没写 (不在请求里,比如测试直接调函数、启动时的整理、调度循环)时同样等同 admin、未认证,username 为空。""" diff --git a/backend/app/api/source_versions.py b/backend/app/api/source_versions.py index 7d8a07ba..bd77947f 100644 --- a/backend/app/api/source_versions.py +++ b/backend/app/api/source_versions.py @@ -21,7 +21,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.api.coded import CodedHTTPException from app.api.datasources import _out -from app.api.deps import signer_of +from app.api.deps import signer_of, signer_verified from app.data import source_versions, table_versions from app.data.recipe_imports import ImportRefused from app.db.base import get_session @@ -170,7 +170,8 @@ async def remove_period(source_id: str, import_id: str, request: Request, x_acto source = await _source(session, source_id) try: out = await source_versions.remove_period(session, source, import_id, expected_current=expected, - reason=reason or "", signed_by=_signed(body, x_actor)) + reason=reason or "", signed_by=_signed(body, x_actor), + signer_verified=signer_verified()) except _REFUSALS as e: raise _refused(e) from e return {"source": await _source_out(session, source_id), **out} @@ -193,7 +194,7 @@ async def revoke_acceptance(source_id: str, import_id: str, request: Request, try: out = await source_versions.revoke_acceptance( session, source, import_id, expected_current=expected, expected_target=target, ack_mask_lost=ack, - reason=reason or "", signed_by=_signed(body, x_actor)) + reason=reason or "", signed_by=_signed(body, x_actor), signer_verified=signer_verified()) except _REFUSALS as e: raise _refused(e) from e return {"source": await _source_out(session, source_id), **out} diff --git a/backend/app/api/table_imports.py b/backend/app/api/table_imports.py index 24e13370..1fdf408e 100644 --- a/backend/app/api/table_imports.py +++ b/backend/app/api/table_imports.py @@ -28,7 +28,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.api.coded import CodedHTTPException from app.api.datasources import _NAME_PATTERN, _out, read_upload -from app.api.deps import current_principal, signer_of +from app.api.deps import current_principal, signer_of, signer_verified from app.data import recipe_imports, table_versions from app.data.recipe_imports import EditRequest, ImportRefused from app.data.recipe_types import Acceptance, AiAvailability, PeriodInput, Recipe, Selection @@ -422,7 +422,8 @@ async def commit(staging_id: str, request: Request, x_actor: str | None = Header try: result = await recipe_imports.commit_staging( session, staging, trial_id=trial_id if isinstance(trial_id, str) else "", - confirmations=confirmations, acceptances=_acceptances(body.get("acceptances"), who), signed_by=who) + confirmations=confirmations, acceptances=_acceptances(body.get("acceptances"), who), signed_by=who, + signer_verified=signer_verified()) except _REFUSALS as e: raise _refused(e) from e source = await session.get(DataSource, result.source_id, populate_existing=True) diff --git a/backend/app/data/recipe_imports.py b/backend/app/data/recipe_imports.py index 40dba2b1..34acb9f0 100644 --- a/backend/app/data/recipe_imports.py +++ b/backend/app/data/recipe_imports.py @@ -2361,7 +2361,7 @@ def _manifest(*, staging_id: str, kind: str, source_id: str, info: table_version ex_dict: dict[str, Any], file: dict[str, Any], recipe_meta: dict[str, Any], checks: list[dict[str, Any]], overrides: list[dict[str, Any]], waivers: list[dict[str, Any]], confirmed: list[dict[str, Any]], notes: SchemaNotes, ai: dict[str, Any], signed_by: str | None, - edits: list[dict[str, Any]] | None = None) -> dict[str, Any]: + edits: list[dict[str, Any]] | None = None, signer_verified: bool = False) -> dict[str, Any]: receipt = copy.deepcopy(ex_dict) receipt.pop("problems", None) return { @@ -2383,7 +2383,8 @@ def _manifest(*, staging_id: str, kind: str, source_id: str, info: table_version "ai": ai, # 期 3:修复、框选的修改记录(含已被整份替换覆盖的,作为历史;不带撤销用的修改前起点) "edits": copy.deepcopy(list(edits or [])), - "signed_by": {"name": signed_by, "verified": False}, + # 是否认证照实记(05-已知遗留 (c)):开了登录、署名是登录的人时为真。以前写死 False,封存的证据记错了事实 + "signed_by": {"name": signed_by, "verified": bool(signer_verified and signed_by)}, "staging_id": staging_id, "kind": kind, "created_at": _now_iso(), } @@ -2411,7 +2412,8 @@ def _file_sha(path: Path) -> str | None: async def commit_staging(session: AsyncSession, staging: ImportStaging, *, trial_id: str, confirmations: list[str], - acceptances: list[Acceptance], signed_by: str | None) -> CommitResult: + acceptances: list[Acceptance], signed_by: str | None, + signer_verified: bool = False) -> CommitResult: """POST imports/{id}/commit(7.8):预检 → (与现行导入相同时)不新建记录 → 发布构建、写配方、导入记录、 快照、清单,切指针。失败时指针不动,暂存区退回 drafting(试运行库已被发布流程消耗)。 @@ -2532,6 +2534,8 @@ async def commit_staging(session: AsyncSession, staging: ImportStaging, *, trial ex = extraction_from_dict(ex_dict) who = signed_by or staging.signed_by + # 署名是这次请求的(signed_by)才谈得上认证;退回暂存区上记的那个,是否认证这里不知道,照实记未认证 + who_verified = bool(signer_verified and signed_by) acc = [Acceptance(check_id=a.check_id, reason=a.reason.strip(), signed_by=who) for a in given.values()] # 这一期自己的说明(带实际的接受)进它的导入清单:版本页逐期显示「改写后的那一句」从这里取(第 5 节)。 # 快照冻结的说明在多期时另按各期最弱的结论合并(2.8),只剩本期时就是它 @@ -2603,7 +2607,8 @@ async def commit_staging(session: AsyncSession, staging: ImportStaging, *, trial file={"name": file_name, "size": file_size, "raw_sha256": raw_sha}, recipe_meta={"id": recipe_id, "sha256": recipe_sha, "origin": origin, "canonical": canonical}, checks=checks_full, overrides=overrides, waivers=waivers, confirmed=confirmed, - notes=notes if union_info is None else period_notes, ai=ai, signed_by=who, edits=edits) + notes=notes if union_info is None else period_notes, ai=ai, signed_by=who, edits=edits, + signer_verified=who_verified) async def schema_cache_for(view: table_versions.SourceView, info: table_versions.PublishInfo) -> dict[str, Any]: from app.core import artifact_store @@ -2663,7 +2668,7 @@ async def commit_staging(session: AsyncSession, staging: ImportStaging, *, trial "table_hashes": dict(union_report.get("table_hashes") or {}), "union_ver": recipe_types.UNION_VER}, parts=ordered, report=union_report, label_sets=list((plan or {}).get("label_sets") or []), gaps=list((plan or {}).get("gaps") or []), replaced=(plan or {}).get("replaces"), removed=None, - notes=notes, signed_by=who) + notes=notes, signed_by=who, signer_verified=who_verified) smid = await artifact_store.put_json(doc, kind="snapshot_manifest", meta={"source_id": source_id, "snapshot_id": info.snapshot_id}) cache["import_manifests"] = [mid if iid is None else by_imp[iid].info.manifest_artifact diff --git a/backend/app/data/source_versions.py b/backend/app/data/source_versions.py index a3dcb73f..4e389fb0 100644 --- a/backend/app/data/source_versions.py +++ b/backend/app/data/source_versions.py @@ -394,7 +394,7 @@ def columns_doc(report: dict[str, Any], periods: list[str]) -> dict[str, dict[st def manifest_doc(*, source_id: str, snapshot_id: str, action: str, recipe: dict[str, Any], union: dict[str, Any], parts: list[Part | dict[str, Any]], report: dict[str, Any], label_sets: list[Any], gaps: list[dict[str, str]], replaced: Any, removed: Any, - notes: SchemaNotes, signed_by: str | None) -> dict[str, Any]: + notes: SchemaNotes, signed_by: str | None, signer_verified: bool = False) -> dict[str, Any]: """快照清单(2.9)。parts 按统计期排序,与 report.part_rows 同序;本期写成 dict(导入记录还没落库)。""" part_rows = report.get("part_rows") or [] keys = [] @@ -422,7 +422,8 @@ def manifest_doc(*, source_id: str, snapshot_id: str, action: str, recipe: dict[ "checks": copy.deepcopy(report.get("checks") or []), "notes": {"templates": dict(notes.templates), "rendered": {t: {"comment": n.comment, "columns": dict(n.columns)} for t, n in notes.tables.items()}}, - "signed_by": {"name": signed_by, "verified": False}, + # 是否认证照实记(05-已知遗留 (c),同导入清单) + "signed_by": {"name": signed_by, "verified": bool(signer_verified and signed_by)}, "created_at": utcnow().isoformat(), } @@ -684,8 +685,10 @@ async def _current(session: AsyncSession, source: DataSource) -> _Current: mode=snap.mode or "replace", recipe=recipe) -def _revoked_record(reason: str, signed_by: str | None) -> dict[str, Any]: - return {"at": utcnow().isoformat(), "reason": reason, "signed_by": signed_by or None, "signed_by_verified": False} +def _revoked_record(reason: str, signed_by: str | None, signer_verified: bool = False) -> dict[str, Any]: + """作废接受的记录。是否认证照实记(05-已知遗留 (c)):开了登录、署名是登录的人时为真。""" + return {"at": utcnow().isoformat(), "reason": reason, "signed_by": signed_by or None, + "signed_by_verified": bool(signer_verified and signed_by)} async def rollback_target(session: AsyncSession, source: DataSource, import_id: str) -> SourceSnapshot | None: @@ -739,7 +742,8 @@ async def revoke_plan(session: AsyncSession, source: DataSource, imp: TableImpor async def _rebuild_without(session: AsyncSession, cur: _Current, imp: TableImport, *, expected_current: str | None, - kind: str, reason: str, signed_by: str | None, revoke: bool) -> tuple[str, bool]: + kind: str, reason: str, signed_by: str | None, revoke: bool, + signer_verified: bool = False) -> tuple[str, bool]: """从当前版本去掉一期、生成(或复用、复活)新快照(7.4)。配方和导入模式不变。返回 (快照 id, 是否复用)。 revoke=True 时同一个事务里写 table_imports.revoked(7.5):复用路径在调 activate_snapshot 之前改好(随它的提交 @@ -758,7 +762,7 @@ async def _rebuild_without(session: AsyncSession, cur: _Current, imp: TableImpor sid = table_versions.snapshot_id(source_id, keep, recipe_types.RECIPE_ENGINE_VER, mode="accumulate", recipe_sha=target_sha) imp_id = imp.id - revoked = _revoked_record(reason, signed_by) if revoke else None + revoked = _revoked_record(reason, signed_by, signer_verified) if revoke else None activation = {"kind": kind, "import_id": imp_id, "reason": reason, "signed_by": signed_by} existing = await session.get(SourceSnapshot, sid) @@ -871,7 +875,7 @@ async def _rebuild_without(session: AsyncSession, cur: _Current, imp: TableImpor "table_hashes": dict((info.union_report or report_json or {}).get("table_hashes") or {}), "union_ver": recipe_types.UNION_VER}, parts=parts, report=info.union_report or report_json or {}, label_sets=label_sets, gaps=gaps, - replaced=None, removed=removed, notes=notes, signed_by=signed_by) + replaced=None, removed=removed, notes=notes, signed_by=signed_by, signer_verified=signer_verified) cache["snapshot_manifest"] = await artifact_store.put_json( doc, kind="snapshot_manifest", meta={"source_id": source_id, "snapshot_id": info.snapshot_id}) return cache @@ -931,7 +935,7 @@ def _check_base(cur: _Current, expected_current: str | None) -> None: async def remove_period(session: AsyncSession, source: DataSource, import_id: str, *, expected_current: str | None, - reason: str, signed_by: str | None) -> dict[str, Any]: + reason: str, signed_by: str | None, signer_verified: bool = False) -> dict[str, Any]: """POST …/imports/{id}/remove(7.4)。""" imp = await session.get(TableImport, import_id) if imp is None or imp.source_id != source.id: @@ -947,13 +951,15 @@ async def remove_period(session: AsyncSession, source: DataSource, import_id: st if len(cur.imports) < 2: raise ImportRefused(409, "last_period", _LAST_PERIOD) sid, reused = await _rebuild_without(session, cur, imp, expected_current=expected_current, kind="remove_period", - reason=reason, signed_by=signed_by, revoke=False) + reason=reason, signed_by=signed_by, revoke=False, + signer_verified=signer_verified) return {"snapshot_id": sid, "removed_import_id": import_id, "reused": reused} async def revoke_acceptance(session: AsyncSession, source: DataSource, import_id: str, *, expected_current: str | None, expected_target: str | None, - ack_mask_lost: list[str] | None, reason: str, signed_by: str | None) -> dict[str, Any]: + ack_mask_lost: list[str] | None, reason: str, signed_by: str | None, + signer_verified: bool = False) -> dict[str, Any]: """POST …/imports/{id}/revoke-acceptance(7.5)。累积模式(至少两期)= 移除这一期;否则回滚到第 5 节定义的目标。""" imp = await session.get(TableImport, import_id) if imp is None or imp.source_id != source.id: @@ -968,7 +974,7 @@ async def revoke_acceptance(session: AsyncSession, source: DataSource, import_id if _accumulating(cur): sid, _reused = await _rebuild_without(session, cur, imp, expected_current=expected_current, kind="revoke_acceptance", reason=reason, signed_by=signed_by, - revoke=True) + revoke=True, signer_verified=signer_verified) return {"snapshot_id": sid, "action": "remove_period"} target = await rollback_target(session, source, imp.id) if target is None: @@ -976,7 +982,7 @@ async def revoke_acceptance(session: AsyncSession, source: DataSource, import_id if target.id != expected_target: raise ImportRefused(409, "revoke_target_changed", _TARGET_CHANGED) target_id = target.id - imp.revoked = _revoked_record(reason, signed_by) + imp.revoked = _revoked_record(reason, signed_by, signer_verified) try: await table_versions.activate_snapshot( session, source, target_id, expected_current=expected_current, kind="revoke_acceptance", reason=reason, diff --git a/backend/app/data/table_versions.py b/backend/app/data/table_versions.py index 2407d0e3..3302344b 100644 --- a/backend/app/data/table_versions.py +++ b/backend/app/data/table_versions.py @@ -2130,7 +2130,7 @@ class RawPurge: async def purge_import_raw( - session: AsyncSession, imp: TableImport, *, reason: str, signed_by: str | None + session: AsyncSession, imp: TableImport, *, reason: str, signed_by: str | None, signer_verified: bool = False ) -> RawPurge: """清除一次导入的原件(提交)。按两元组解包得到 (是否删了文件, 一并标成已清除的其他导入记录), discarded_stagings 是一并放弃的暂存区。 @@ -2160,7 +2160,9 @@ async def purge_import_raw( now = utcnow() record = { "at": now.isoformat(), "reason": reason, - "signed_by": (signed_by or "").strip() or None, "signed_by_verified": False, + # 是否认证照实记(05-已知遗留 (c)):开了登录、署名是登录的人时为真 + "signed_by": (signed_by or "").strip() or None, + "signed_by_verified": bool(signer_verified and (signed_by or "").strip()), } imp.raw_state, imp.purged = "purged", record for other in others: diff --git a/backend/tests/test_signer_verified.py b/backend/tests/test_signer_verified.py new file mode 100644 index 00000000..6d4df7f7 --- /dev/null +++ b/backend/tests/test_signer_verified.py @@ -0,0 +1,63 @@ +"""导入清单、累积快照清单、作废记录、清除原件记录如实写「是否认证」(docs/design/next-round/05-已知遗留.md (c))。 + +以前四处都写死 False:开了登录、署名就是登录的人,封存的证据里却记着「未认证」,和审计表、待办派单、run.origin 的 +verified 对不上。现在由 api/deps.signer_verified 在请求那一刻定下、和署名一起往下传:开登录为真,关登录(自报的署名) +为假。已封存的旧清单不改写(关登录时的形状见 test_table_imports_api、test_source_versions_api、test_datasources_upload)。 +""" +from __future__ import annotations + +import pytest + +from app.api import deps +from app.core import artifact_store +from app.db.models import TableImport +from tests.fakes import auth_env +from tests.test_table_imports_api import first_import, get, store, unique # noqa: F401 - store 是 autouse 夹具 + + +@pytest.fixture +async def admin(): + await auth_env.reset() + c = await auth_env.turn_on_local("root") + try: + yield c + finally: + await c.aclose() + await auth_env.reset() + + +def test_signer_verified_follows_the_request_identity(): + token = deps._principal.set(deps.Principal(username="root", role="admin", verified=True, mode="local")) + try: + assert deps.signer_verified() is True + finally: + deps._principal.reset(token) + token = deps._principal.set(deps.Principal(username="张三", role="admin", verified=False, mode="off")) + try: + assert deps.signer_verified() is False, "关登录时署名是自报的" + finally: + deps._principal.reset(token) + assert deps.signer_verified() is False, "不在请求里(启动整理、调度循环)不算认证" + + +def test_the_records_write_what_they_are_given(): + from app.data import source_versions + + assert source_versions._revoked_record("理由", "root", True)["signed_by_verified"] is True + assert source_versions._revoked_record("理由", "root")["signed_by_verified"] is False + assert source_versions._revoked_record("理由", None, True)["signed_by_verified"] is False, "没有署名谈不上认证" + + +async def test_login_on_import_manifest_and_purge_record_say_verified(admin): + out = (await first_import(admin, unique("signer")))["commit"] + imp = await get(TableImport, out["import_id"]) + manifest = artifact_store.load(imp.manifest_artifact) + assert manifest["signed_by"] == {"name": "root", "verified": True} + assert imp.signed_by == "root" + + source_id = out["source"]["id"] + resp = await admin.post(f"/api/datasources/{source_id}/imports/{imp.id}/purge-raw", + json={"reason": "含有不应保留的内容", "signed_by": "随手填的名字"}) + assert resp.status_code == 200, resp.text + purged = resp.json()["import"]["purged"] + assert (purged["signed_by"], purged["signed_by_verified"]) == ("root", True)