fix(shipping-notice): 修复抽取续抽与 STP 入队并发死锁并幂等草稿校验

- 抽取 Job 续抽交接时 defer_stp_enqueue,STP 入队推迟到 run 收口统一触发,消除与续抽 Job 互抢行锁的死锁(2026-09-22 生产事故)
- 草稿显式 validate 在内容未变时幂等短路:不递增版本、不写事件、不重复触发下游,防连点「保存并校验」产生版本/Job 风暴(事故根因)
- STP 自动建单入队前 supersede 同文档过期排队 Job,防止旧版本 Job 抢跑
- 抽取 Job 异常收口识别 PostgreSQL 瞬时锁冲突(40P01/55P03)标记可重试,不再终态失败要求人工重新识别
- 订单凭据加密抽离为 app/core/credential_crypto 通用模块,shipping_notice 委托调用并保留原错误码
- 同步复核视图与测试:新增草稿校验幂等契约测试,更新 STP 入队与 Worker 重试用例
This commit is contained in:
hugo committed 2026-09-23 00:41:32 +08:00
1 parent 13c33d063c
commit 5df204fdea
12 files changed
+865 -87

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
"""app/core/credential_crypto.py
用途:通用 Fernet 凭据加解密(主密钥只来自 Flask config 的环境注入键,绝不落库明文)。
依赖:cryptography.fernet、Flask current_app、app.core.errors。
逻辑:调用方通过 CredentialCryptoErrorCodes 提供各自的业务错误码;主密钥缺失/无效时
fail-closed 拒绝加密,避免产生不可恢复密文。shipping_notice(RPA Profile)与
integration_connector(凭据引用)共用本模块,仅密钥键名与错误码不同。
"""
from __future__ import annotations
from dataclasses import dataclass
from cryptography.fernet import Fernet, InvalidToken
from flask import current_app
from app.core.errors import ServiceUnavailableError, ValidationError
@dataclass(frozen=True)
class CredentialCryptoErrorCodes:
"""加解密失败的错误码集合(按调用方业务域自定义)。"""
key_missing: str
key_invalid: str
secret_empty: str
secret_missing: str
secret_invalid: str
def _fernet(key_config_name: str, codes: CredentialCryptoErrorCodes) -> Fernet:
"""从 Flask config 读取主密钥并构造加密器;缺失/无效即 fail-closed。"""
key = str(current_app.config.get(key_config_name) or '').strip()
if not key:
raise ServiceUnavailableError(
f'{key_config_name} is not configured',
code=codes.key_missing,
)
try:
return Fernet(key.encode('ascii'))
except (ValueError, UnicodeEncodeError) as exc:
raise ServiceUnavailableError(
f'{key_config_name} is invalid',
code=codes.key_invalid,
) from exc
def encrypt_secret(value: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
"""加密单个凭据字段以便持久化;调用方不得记录明文。"""
plaintext = str(value or '')
if not plaintext:
raise ValidationError('credential must not be empty', code=codes.secret_empty)
return _fernet(key_config_name, codes).encrypt(plaintext.encode('utf-8')).decode('ascii')
def decrypt_secret(ciphertext: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
"""在受控运行时解密密文;仅供当次调用内存使用,禁止落日志/响应。"""
value = str(ciphertext or '').strip()
if not value:
raise ValidationError('credential ciphertext is missing', code=codes.secret_missing)
try:
return _fernet(key_config_name, codes).decrypt(value.encode('ascii')).decode('utf-8')
except (InvalidToken, UnicodeDecodeError) as exc:
raise ValidationError('credential ciphertext is invalid', code=codes.secret_invalid) from exc