wop-python-sdk 0.1.1__tar.gz → 0.1.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. {wop_python_sdk-0.1.1/src/wop_python_sdk.egg-info → wop_python_sdk-0.1.7}/PKG-INFO +16 -5
  2. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/README.md +15 -4
  3. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/pyproject.toml +3 -3
  4. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7/src/wop_python_sdk.egg-info}/PKG-INFO +16 -5
  5. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_python_sdk.egg-info/SOURCES.txt +3 -0
  6. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/__init__.py +8 -1
  7. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/canonical.py +5 -4
  8. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/client.py +44 -22
  9. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/digest.py +2 -4
  10. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/encoding.py +1 -3
  11. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/envelope.py +60 -11
  12. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/keys.py +2 -2
  13. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/sm2crypto.py +2 -2
  14. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/suites.py +4 -8
  15. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/transports/httpx_transport.py +2 -2
  16. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/transports/requests_transport.py +2 -2
  17. wop_python_sdk-0.1.7/tests/test_bdd.py +510 -0
  18. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_client.py +7 -10
  19. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_coverage_gaps.py +5 -4
  20. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_envelope.py +27 -8
  21. wop_python_sdk-0.1.7/tests/test_interop.py +275 -0
  22. wop_python_sdk-0.1.7/tests/test_mutation_gaps.py +124 -0
  23. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/LICENSE +0 -0
  24. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/setup.cfg +0 -0
  25. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_python_sdk.egg-info/dependency_links.txt +0 -0
  26. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_python_sdk.egg-info/requires.txt +0 -0
  27. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_python_sdk.egg-info/top_level.txt +0 -0
  28. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/errors.py +0 -0
  29. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/signature.py +0 -0
  30. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/sm4gcm.py +0 -0
  31. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/transports/__init__.py +0 -0
  32. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/src/wop_sdk/transports/urllib_transport.py +0 -0
  33. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_canonical.py +0 -0
  34. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_digest.py +0 -0
  35. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_encoding.py +0 -0
  36. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_keys.py +0 -0
  37. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_signature.py +0 -0
  38. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_suites.py +0 -0
  39. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_transports.py +0 -0
  40. {wop_python_sdk-0.1.1 → wop_python_sdk-0.1.7}/tests/test_transports_real.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wop-python-sdk
3
- Version: 0.1.1
3
+ Version: 0.1.7
4
4
  Summary: WOP 商户侧官方 Python SDK:协议核心(签名/摘要/数字信封/验签解密)+ 可插拔 HTTP 适配层
5
5
  Author: wop-platform
6
6
  License: MIT
@@ -30,6 +30,10 @@ Dynamic: license-file
30
30
 
31
31
  # WOP Python SDK
32
32
 
33
+ [![PyPI](https://img.shields.io/pypi/v/wop-python-sdk)](https://pypi.org/project/wop-python-sdk/) [![Python 3.9+](https://img.shields.io/pypi/pyversions/wop-python-sdk)](https://pypi.org/project/wop-python-sdk/) [![Release](https://img.shields.io/github/v/release/wop-platform/wop-python-sdk)](https://github.com/wop-platform/wop-python-sdk/releases)
34
+ [![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://github.com/wop-platform/wop-python-sdk/actions/workflows/ci.yml) [![Gherkin](https://img.shields.io/badge/bdd-21%20scenarios-orange)](tests/features/wop_merchant.feature) ![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/wop-platform/wop-python-sdk?utm_source=oss&utm_medium=github&utm_campaign=wop-platform%2Fwop-python-sdk&labelColor=171717&color=FF570A&link=https%3A%2F%2Fcoderabbit.ai&label=CodeRabbit+Reviews)
35
+
36
+
33
37
  WOP 网关商户侧官方 Python 客户端库:封装协议核心(套件解析 / 结构化签名 / 内容摘要 /
34
38
  L2 数字信封 / 验签解密)与可插拔 HTTP 适配层,使商户无需理解 canonicalRequest、
35
39
  算法套件推导与线上字节格式即可安全对接网关。
@@ -129,11 +133,18 @@ python3 -m pytest --cov=wop_sdk --cov-branch --cov-fail-under=98
129
133
  覆盖:RSA3072/4096 与 SM2 签名字节级断言、OAEP 包装/解包、AES-256-GCM 与 SM4-GCM
130
134
  密文字节级断言、SM3/SHA-256 摘要、DEK 载荷组装、digest 头全部格式规则;负向量含
131
135
  tamper / 跨族 / 63B、65B 签名 / 带 `=` 的 base64url / C1C2C3 旧国标顺序 /
132
- MGF1-SHA1 陷阱密文,全部必须拒绝。CI(3.9–3.14 矩阵)执行同一命令。
136
+ MGF1-SHA1 陷阱密文,全部必须拒绝。CI(3.9–3.14 × linux/macOS 矩阵)执行同一命令。
137
+
138
+ 另消费 `wop-specs` 组织级 interop 样本集(`tests/fixtures/interop-cases.json` 字节
139
+ 副本,sha256 哨兵钉死):build 方向按冻结输入复现 draft(RSA byte-exact;SM2 按
140
+ opaque 剥离签名/包装段),verify 方向 23 条冻结样本逐条对账明文与错误分类
141
+ (canonical class 映射表见 `tests/test_interop.py`)。
133
142
 
134
143
  ## 错误处理与模糊化
135
144
 
136
- - **明确**(公开协议知识,帮助集成自查):套件格式/跨族、密钥材料、digest 头格式与
137
- 不匹配、DEK alg 与套件族不符;
145
+ - **明确**(公开协议知识,帮助集成自查):套件格式/跨族、密钥材料、digest 头格式、
146
+ 缺失与不匹配(D2/I1 结构前置校验)、信封 JSON 形态与各 base64url 段(F7)、
147
+ DEK alg 与套件族不符;
138
148
  - **模糊**(依赖密钥参与,防 oracle,I7):签名验证失败、解密失败——对外消息不区分
139
- tag 失败 / 密钥不符等原因细节。
149
+ tag 失败 / 密钥不符等原因细节;DEK 载荷(解包后明文)结构畸形除 alg 跨族外一律
150
+ 归入解密失败(interop 合同 n13 / 故障注入手册 P3)。
@@ -1,5 +1,9 @@
1
1
  # WOP Python SDK
2
2
 
3
+ [![PyPI](https://img.shields.io/pypi/v/wop-python-sdk)](https://pypi.org/project/wop-python-sdk/) [![Python 3.9+](https://img.shields.io/pypi/pyversions/wop-python-sdk)](https://pypi.org/project/wop-python-sdk/) [![Release](https://img.shields.io/github/v/release/wop-platform/wop-python-sdk)](https://github.com/wop-platform/wop-python-sdk/releases)
4
+ [![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://github.com/wop-platform/wop-python-sdk/actions/workflows/ci.yml) [![Gherkin](https://img.shields.io/badge/bdd-21%20scenarios-orange)](tests/features/wop_merchant.feature) ![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/wop-platform/wop-python-sdk?utm_source=oss&utm_medium=github&utm_campaign=wop-platform%2Fwop-python-sdk&labelColor=171717&color=FF570A&link=https%3A%2F%2Fcoderabbit.ai&label=CodeRabbit+Reviews)
5
+
6
+
3
7
  WOP 网关商户侧官方 Python 客户端库:封装协议核心(套件解析 / 结构化签名 / 内容摘要 /
4
8
  L2 数字信封 / 验签解密)与可插拔 HTTP 适配层,使商户无需理解 canonicalRequest、
5
9
  算法套件推导与线上字节格式即可安全对接网关。
@@ -99,11 +103,18 @@ python3 -m pytest --cov=wop_sdk --cov-branch --cov-fail-under=98
99
103
  覆盖:RSA3072/4096 与 SM2 签名字节级断言、OAEP 包装/解包、AES-256-GCM 与 SM4-GCM
100
104
  密文字节级断言、SM3/SHA-256 摘要、DEK 载荷组装、digest 头全部格式规则;负向量含
101
105
  tamper / 跨族 / 63B、65B 签名 / 带 `=` 的 base64url / C1C2C3 旧国标顺序 /
102
- MGF1-SHA1 陷阱密文,全部必须拒绝。CI(3.9–3.14 矩阵)执行同一命令。
106
+ MGF1-SHA1 陷阱密文,全部必须拒绝。CI(3.9–3.14 × linux/macOS 矩阵)执行同一命令。
107
+
108
+ 另消费 `wop-specs` 组织级 interop 样本集(`tests/fixtures/interop-cases.json` 字节
109
+ 副本,sha256 哨兵钉死):build 方向按冻结输入复现 draft(RSA byte-exact;SM2 按
110
+ opaque 剥离签名/包装段),verify 方向 23 条冻结样本逐条对账明文与错误分类
111
+ (canonical class 映射表见 `tests/test_interop.py`)。
103
112
 
104
113
  ## 错误处理与模糊化
105
114
 
106
- - **明确**(公开协议知识,帮助集成自查):套件格式/跨族、密钥材料、digest 头格式与
107
- 不匹配、DEK alg 与套件族不符;
115
+ - **明确**(公开协议知识,帮助集成自查):套件格式/跨族、密钥材料、digest 头格式、
116
+ 缺失与不匹配(D2/I1 结构前置校验)、信封 JSON 形态与各 base64url 段(F7)、
117
+ DEK alg 与套件族不符;
108
118
  - **模糊**(依赖密钥参与,防 oracle,I7):签名验证失败、解密失败——对外消息不区分
109
- tag 失败 / 密钥不符等原因细节。
119
+ tag 失败 / 密钥不符等原因细节;DEK 载荷(解包后明文)结构畸形除 alg 跨族外一律
120
+ 归入解密失败(interop 合同 n13 / 故障注入手册 P3)。
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "wop-python-sdk"
7
- version = "0.1.1"
7
+ version = "0.1.7"
8
8
  description = "WOP 商户侧官方 Python SDK:协议核心(签名/摘要/数字信封/验签解密)+ 可插拔 HTTP 适配层"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -36,9 +36,9 @@ httpx = ["httpx>=0.24"]
36
36
  requests = ["requests>=2.28"]
37
37
 
38
38
  [dependency-groups]
39
- # 发布构建前端(PEP 735,不进发布元数据):
39
+ # 发布构建前端 + BDD 测试工具链(PEP 735,不进发布元数据):
40
40
  # pip install --group dev && python -m build
41
- dev = ["build"]
41
+ dev = ["build", "pytest-bdd>=8.0,<9.0"]
42
42
 
43
43
  [project.urls]
44
44
  Homepage = "https://github.com/wop-platform/wop-python-sdk"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wop-python-sdk
3
- Version: 0.1.1
3
+ Version: 0.1.7
4
4
  Summary: WOP 商户侧官方 Python SDK:协议核心(签名/摘要/数字信封/验签解密)+ 可插拔 HTTP 适配层
5
5
  Author: wop-platform
6
6
  License: MIT
@@ -30,6 +30,10 @@ Dynamic: license-file
30
30
 
31
31
  # WOP Python SDK
32
32
 
33
+ [![PyPI](https://img.shields.io/pypi/v/wop-python-sdk)](https://pypi.org/project/wop-python-sdk/) [![Python 3.9+](https://img.shields.io/pypi/pyversions/wop-python-sdk)](https://pypi.org/project/wop-python-sdk/) [![Release](https://img.shields.io/github/v/release/wop-platform/wop-python-sdk)](https://github.com/wop-platform/wop-python-sdk/releases)
34
+ [![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://github.com/wop-platform/wop-python-sdk/actions/workflows/ci.yml) [![Gherkin](https://img.shields.io/badge/bdd-21%20scenarios-orange)](tests/features/wop_merchant.feature) ![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/wop-platform/wop-python-sdk?utm_source=oss&utm_medium=github&utm_campaign=wop-platform%2Fwop-python-sdk&labelColor=171717&color=FF570A&link=https%3A%2F%2Fcoderabbit.ai&label=CodeRabbit+Reviews)
35
+
36
+
33
37
  WOP 网关商户侧官方 Python 客户端库:封装协议核心(套件解析 / 结构化签名 / 内容摘要 /
34
38
  L2 数字信封 / 验签解密)与可插拔 HTTP 适配层,使商户无需理解 canonicalRequest、
35
39
  算法套件推导与线上字节格式即可安全对接网关。
@@ -129,11 +133,18 @@ python3 -m pytest --cov=wop_sdk --cov-branch --cov-fail-under=98
129
133
  覆盖:RSA3072/4096 与 SM2 签名字节级断言、OAEP 包装/解包、AES-256-GCM 与 SM4-GCM
130
134
  密文字节级断言、SM3/SHA-256 摘要、DEK 载荷组装、digest 头全部格式规则;负向量含
131
135
  tamper / 跨族 / 63B、65B 签名 / 带 `=` 的 base64url / C1C2C3 旧国标顺序 /
132
- MGF1-SHA1 陷阱密文,全部必须拒绝。CI(3.9–3.14 矩阵)执行同一命令。
136
+ MGF1-SHA1 陷阱密文,全部必须拒绝。CI(3.9–3.14 × linux/macOS 矩阵)执行同一命令。
137
+
138
+ 另消费 `wop-specs` 组织级 interop 样本集(`tests/fixtures/interop-cases.json` 字节
139
+ 副本,sha256 哨兵钉死):build 方向按冻结输入复现 draft(RSA byte-exact;SM2 按
140
+ opaque 剥离签名/包装段),verify 方向 23 条冻结样本逐条对账明文与错误分类
141
+ (canonical class 映射表见 `tests/test_interop.py`)。
133
142
 
134
143
  ## 错误处理与模糊化
135
144
 
136
- - **明确**(公开协议知识,帮助集成自查):套件格式/跨族、密钥材料、digest 头格式与
137
- 不匹配、DEK alg 与套件族不符;
145
+ - **明确**(公开协议知识,帮助集成自查):套件格式/跨族、密钥材料、digest 头格式、
146
+ 缺失与不匹配(D2/I1 结构前置校验)、信封 JSON 形态与各 base64url 段(F7)、
147
+ DEK alg 与套件族不符;
138
148
  - **模糊**(依赖密钥参与,防 oracle,I7):签名验证失败、解密失败——对外消息不区分
139
- tag 失败 / 密钥不符等原因细节。
149
+ tag 失败 / 密钥不符等原因细节;DEK 载荷(解包后明文)结构畸形除 alg 跨族外一律
150
+ 归入解密失败(interop 合同 n13 / 故障注入手册 P3)。
@@ -22,13 +22,16 @@ src/wop_sdk/transports/__init__.py
22
22
  src/wop_sdk/transports/httpx_transport.py
23
23
  src/wop_sdk/transports/requests_transport.py
24
24
  src/wop_sdk/transports/urllib_transport.py
25
+ tests/test_bdd.py
25
26
  tests/test_canonical.py
26
27
  tests/test_client.py
27
28
  tests/test_coverage_gaps.py
28
29
  tests/test_digest.py
29
30
  tests/test_encoding.py
30
31
  tests/test_envelope.py
32
+ tests/test_interop.py
31
33
  tests/test_keys.py
34
+ tests/test_mutation_gaps.py
32
35
  tests/test_signature.py
33
36
  tests/test_suites.py
34
37
  tests/test_transports.py
@@ -3,6 +3,8 @@
3
3
 
4
4
  协议核心(签名/摘要/数字信封/验签解密,纯函数、零网络 IO)+ 可插拔 HTTP 适配层。
5
5
  """
6
+ from importlib.metadata import PackageNotFoundError, version as _dist_version
7
+
6
8
  from .client import RequestDraft, VerifyResult, WopClient, WopConfig
7
9
  from .errors import (
8
10
  DecryptError,
@@ -17,7 +19,12 @@ from .errors import (
17
19
  )
18
20
  from .suites import Suite, parse_suite
19
21
 
20
- __version__ = "0.1.1"
22
+ # 版本单一源:pyproject [project].version(经分发元数据读取),
23
+ # 未安装场景(纯源码树 import)兜底 0.0.0
24
+ try:
25
+ __version__ = _dist_version("wop-python-sdk")
26
+ except PackageNotFoundError: # pragma: no cover —— 无分发元数据时的兜底分支
27
+ __version__ = "0.0.0"
21
28
 
22
29
  __all__ = [
23
30
  "WopClient",
@@ -18,11 +18,12 @@ def canonical_headers(headers: Optional[Dict[str, str]]) -> str:
18
18
  名称 ASCII 升序,行间 '\\n' 连接,尾行不加 '\\n'。"""
19
19
  if not headers:
20
20
  return ""
21
- normalized = {}
22
- for name, value in headers.items():
23
- normalized[trimall(name).lower()] = trimall(value)
21
+ normalized = {
22
+ trimall(name).lower(): trimall(value)
23
+ for name, value in headers.items()
24
+ }
24
25
  return "\n".join(
25
- "%s:%s" % (java_urlencode(k), java_urlencode(normalized[k]))
26
+ f"{java_urlencode(k)}:{java_urlencode(normalized[k])}"
26
27
  for k in sorted(normalized)
27
28
  )
28
29
 
@@ -2,8 +2,8 @@
2
2
  """WopClient:协议核心编排(spec §2 概念 API 的 Python 映射)。
3
3
 
4
4
  - build_request:组装协议头 + 签名 + 可选 L2 信封 → RequestDraft(零网络 IO);
5
- - verify_response / verify_callback:F6 固定顺序(验签 → digest 复核 → DEK 解包 →
6
- alg 族比对 → bulk 解密),失败统一 VerifyResult(ok=False, reason),
5
+ - verify_response / verify_callback:F6 固定顺序(结构前置校验 → 验签 → digest 复核 →
6
+ DEK 解包 → alg 族比对 → bulk 解密),失败统一 VerifyResult(ok=False, reason, error),
7
7
  验签/解密类 reason 模糊(I7),格式/完整性/一致性类 reason 明确(10.2)。
8
8
  """
9
9
  import json
@@ -71,11 +71,16 @@ class RequestDraft:
71
71
 
72
72
  @dataclass
73
73
  class VerifyResult:
74
- """响应/回调校验结果;reason 对验签/解密类模糊(I7)。"""
74
+ """响应/回调校验结果;reason 对验签/解密类模糊(I7)。
75
+
76
+ error 携带原始分类异常(WopSdkError 子类,仅失败时非 None),
77
+ 供消费方按 10.2 错误分类编程处理(对齐 Go VerifyResult.Code)。
78
+ """
75
79
 
76
80
  ok: bool
77
81
  plaintext: Optional[bytes] = None
78
82
  reason: Optional[str] = None
83
+ error: Optional[WopSdkError] = None
79
84
 
80
85
 
81
86
  class WopClient:
@@ -117,11 +122,21 @@ class WopClient:
117
122
  query_string: str = "",
118
123
  expired_seconds: int = 1800,
119
124
  extra_headers: Optional[Dict[str, str]] = None,
125
+ timestamp_ms: Optional[int] = None,
126
+ nonce: Optional[str] = None,
120
127
  ) -> RequestDraft:
121
- """构造请求(F9):协议头组装 → L2 可选封装 → canonicalRequest → 签名。"""
128
+ """构造请求(F9):协议头组装 → L2 可选封装 → canonicalRequest → 签名。
129
+
130
+ timestamp_ms / nonce 为确定性钩子(重放/联调用;镜像 Go WithTimestamp/
131
+ WithNonce)。随机流消费顺序合同(wop-specs/interop/v1):
132
+ [16B nonce 池][CEK][12B IV][k…]——nonce 注入时跳过 nonce 池段。
133
+ """
122
134
  if level not in _LEVELS:
123
135
  raise ValueError("level 必须为 L0 或 L2,实际 %r" % level)
124
136
  safe_method = method.strip().upper()
137
+ # spec:interop-v1 随机流消费顺序:nonce 池最前,先于 seal_l2 的 CEK/IV
138
+ if not nonce:
139
+ nonce = self._csprng(16).hex() # F9:CSPRNG nonce
125
140
  wire: Optional[bytes] = None
126
141
  encrypt_header: Optional[str] = None
127
142
  if level == "L2":
@@ -133,8 +148,8 @@ class WopClient:
133
148
 
134
149
  headers: Dict[str, str] = {
135
150
  "x-wop-appkey": self._config.app_key,
136
- "x-wop-timestamp": str(_now_ms()),
137
- "x-wop-nonce": self._csprng(16).hex(), # F9:CSPRNG nonce
151
+ "x-wop-timestamp": str(_now_ms() if timestamp_ms is None else int(timestamp_ms)),
152
+ "x-wop-nonce": nonce,
138
153
  }
139
154
  if wire is not None:
140
155
  # D2:有 body 必产 digest;I1:digest 必入 signedHeaders(下方签名集合即全部头)
@@ -150,21 +165,18 @@ class WopClient:
150
165
  else:
151
166
  app_headers[low] = str(value).strip()
152
167
 
153
- auth = "v1/%d" % int(expired_seconds)
168
+ auth = f"v1/{int(expired_seconds)}"
154
169
  canonical = build_canonical(
155
170
  auth, safe_method, path, query_string or "", canonical_headers(headers)
156
171
  )
157
172
  sig = sign(self._suite, self._signer, canonical.encode("utf-8"), csprng=self._csprng)
158
- headers["x-wop-sign"] = "%s %s/%s/%s" % (
159
- self._suite.security_req,
160
- auth,
161
- ";".join(sorted(k for k in headers)),
162
- b64url_encode(sig),
173
+ headers["x-wop-sign"] = (
174
+ f'{self._suite.security_req} {auth}/{";".join(sorted(iter(headers)))}/{b64url_encode(sig)}'
163
175
  )
164
176
  out: Dict[str, str] = dict(headers)
165
177
  if wire is not None:
166
178
  out.setdefault("content-type", "application/json")
167
- out.update(app_headers)
179
+ out |= app_headers
168
180
  return RequestDraft(safe_method, path, out, wire, level)
169
181
 
170
182
  @staticmethod
@@ -195,7 +207,7 @@ class WopClient:
195
207
  return self._verify_flow(lower, body, path, method.upper(), query_string or "")
196
208
  except (SignatureVerifyError, DecryptError, ProtocolFormatError, DigestMismatchError,
197
209
  DekConsistencyError, UnsupportedSuiteError, SuiteParseError) as exc:
198
- return VerifyResult(ok=False, reason=str(exc))
210
+ return VerifyResult(ok=False, reason=str(exc), error=exc)
199
211
 
200
212
  def verify_callback(
201
213
  self, headers: Dict[str, str], body: bytes, callback_path: str
@@ -223,27 +235,37 @@ class WopClient:
223
235
  req_suite = parse_suite(suite_part) # 解析类/支持类错误明确
224
236
  if req_suite.security_req != self._suite.security_req:
225
237
  raise UnsupportedSuiteError(
226
- "响应声明套件 %s 与商户配置 %s 不符" % (suite_part, self._suite.security_req)
238
+ f"响应声明套件 {suite_part} 与商户配置 {self._suite.security_req} 不符"
227
239
  )
240
+ # F6 ①前置结构校验(公开协议知识,明确拒绝,先于验签;spec:interop-v1 n09/n10/n15):
241
+ # D2 有 body 必传 digest;I1 digest 必入 signedHeaders;无 body 不得携带 digest。
242
+ digest_header = lower.get("x-wop-content-digest")
243
+ if body:
244
+ if digest_header is None:
245
+ raise DigestMismatchError("有响应体但缺少 x-wop-content-digest")
246
+ if "x-wop-content-digest" not in signed_names.split(";"):
247
+ raise ProtocolFormatError("x-wop-content-digest 未列入 signedHeaders(I1)")
248
+ elif digest_header is not None:
249
+ raise ProtocolFormatError("无响应体不应携带 x-wop-content-digest")
228
250
  sig = _strict_decode_signature(sig_b64u)
229
- auth = "%s/%s" % (version, _expired)
251
+ auth = f"{version}/{_expired}"
230
252
  signed: Dict[str, str] = {}
231
253
  for name in signed_names.split(";"):
232
254
  if name not in lower:
233
- raise ProtocolFormatError("签名声明的头在响应中缺席:%s" % name)
255
+ raise ProtocolFormatError(f"签名声明的头在响应中缺席:{name}")
234
256
  signed[name] = lower[name]
235
257
  canonical = build_canonical(auth, method, path, query_string, canonical_headers(signed))
236
- # F6 ①先验签(I2:先验签后解密)
258
+ # F6 ②先验签(I2:先验签后解密)
237
259
  verify(req_suite, self._wrap_pub, canonical.encode("utf-8"), sig)
238
- # F6 ②digest 复核(D2:有 body 必传;对象 = wire 原始字节)
260
+ # F6 ③digest 复核(D2:有 body 必传;对象 = wire 原始字节)
239
261
  if body:
240
262
  verify_digest_header(self._suite, lower.get("x-wop-content-digest"), body)
241
263
  enc = lower.get("x-wop-encrypt")
242
264
  if enc is None:
243
265
  return VerifyResult(ok=True, plaintext=body) # L0
244
- # F6 ③④⑤ DEK 解包 → alg 族比对 → bulk 解密(envelope.open_l2 内序)
266
+ # F6 ④⑤⑥ DEK 解包 → alg 族比对 → bulk 解密(envelope.open_l2 内序)
245
267
  if not enc.startswith(_DEK_PREFIX):
246
- raise ProtocolFormatError("x-wop-encrypt 头格式错误:应为 %s<base64url>" % _DEK_PREFIX)
268
+ raise ProtocolFormatError(f"x-wop-encrypt 头格式错误:应为 {_DEK_PREFIX}<base64url>")
247
269
  plaintext = open_l2(self._suite, self._signer, body, enc[len(_DEK_PREFIX):])
248
270
  return VerifyResult(ok=True, plaintext=plaintext)
249
271
 
@@ -255,4 +277,4 @@ def _strict_decode_signature(sig_b64u: str) -> bytes:
255
277
  try:
256
278
  return b64url_decode(sig_b64u)
257
279
  except ValueError as exc:
258
- raise ProtocolFormatError("签名编码非法:%s" % exc) from exc
280
+ raise ProtocolFormatError(f"签名编码非法:{exc}") from exc
@@ -27,7 +27,7 @@ def compute_digest(suite: Suite, data: bytes) -> bytes:
27
27
 
28
28
  def build_digest_header(suite: Suite, body: bytes) -> str:
29
29
  """组装 `<alg> <小写hex>`(恰一空格)。"""
30
- return "%s %s" % (suite.digest_tag, compute_digest(suite, body).hex())
30
+ return f"{suite.digest_tag} {compute_digest(suite, body).hex()}"
31
31
 
32
32
 
33
33
  def check_digest_header(suite: Suite, value: Optional[str]) -> str:
@@ -47,9 +47,7 @@ def check_digest_header(suite: Suite, value: Optional[str]) -> str:
47
47
  if tag != expected_tag:
48
48
  # I5:标签与套件族强耦合(sha-256 仅 RSA 族、sm3 仅 SM 族)
49
49
  if tag in ("sha-256", "sm3"):
50
- raise UnsupportedSuiteError(
51
- "digest 标签 %s 与套件族 %s 不符(跨族拒绝)" % (tag, suite.family)
52
- )
50
+ raise UnsupportedSuiteError(f"digest 标签 {tag} 与套件族 {suite.family} 不符(跨族拒绝)")
53
51
  raise ProtocolFormatError("digest 标签未知:%r" % tag)
54
52
  if not _HEX64.match(hex_value):
55
53
  raise ProtocolFormatError("digest 值必须为 64 字符小写 hex,实际 %r" % hex_value)
@@ -85,6 +85,4 @@ def java_urlencode(text: Optional[str]) -> str:
85
85
 
86
86
  def trimall(text: Optional[str]) -> str:
87
87
  """去首尾空白,连续空白折叠为单个空格(F2,对照 CanonicalRequestBuilder.trimall)。"""
88
- if text is None:
89
- return ""
90
- return re.sub(r"\s+", " ", text.strip())
88
+ return "" if text is None else re.sub(r"\s+", " ", text.strip())
@@ -7,6 +7,7 @@
7
7
  - DEK 载荷:alg$base64url(key)$base64url(iv);alg 族比对在解包后、bulk 解密前(D8/I3);
8
8
  - 解密失败(GCM tag、KDF、C3、OAEP)对外一律"解密失败"(I7 模糊化)。
9
9
  """
10
+ import hashlib
10
11
  import json
11
12
  import os
12
13
  from typing import Callable, Tuple, Union, cast
@@ -73,12 +74,48 @@ def _oaep_params() -> _rsa_padding.OAEP:
73
74
 
74
75
 
75
76
  def wrap_dek(suite: Suite, wrap_pub: KeyMaterial, payload: bytes, csprng: Csprng = os.urandom) -> bytes:
76
- """DEK 非对称包装(出向,平台公钥)。SM2 的 k 走 csprng(I4)。"""
77
+ """DEK 非对称包装(出向,平台公钥)。SM2 的 k 与 RSA-OAEP 的 seed 均走 csprng
78
+ (I4 + interop 合同:OAEP-from-stream 确定——确定性钩子须覆盖全部随机消费点)。"""
77
79
  if suite.family == "RSA":
78
- return cast(rsa.RSAPublicKey, wrap_pub).encrypt(payload, _oaep_params())
80
+ return _rsa_oaep_encrypt_from_stream(cast(rsa.RSAPublicKey, wrap_pub), payload, csprng)
79
81
  return sm2_encrypt(cast(Sm2Ops, wrap_pub), csprng, payload)
80
82
 
81
83
 
84
+ def _mgf1_sha256(seed: bytes, length: int) -> bytes:
85
+ """MGF1(SHA-256,RFC 8017 B.2.1)。"""
86
+ out = bytearray()
87
+ counter = 0
88
+ while len(out) < length:
89
+ out.extend(hashlib.sha256(seed + counter.to_bytes(4, "big")).digest())
90
+ counter += 1
91
+ return bytes(out[:length])
92
+
93
+
94
+ def _rsa_oaep_encrypt_from_stream(
95
+ pub: rsa.RSAPublicKey, message: bytes, csprng: Csprng
96
+ ) -> bytes:
97
+ """RSAES-OAEP-ENCRYPT(RFC 8017 7.1.1):摘要/MGF1 均钉死 SHA-256、空 label(F2/D10),
98
+ seed 显式取自 csprng——与 Go EncryptOAEP(hash, random, …) 的随机流消费位逐字节对齐
99
+ (interop/v1:RSA L2 build 样本 byte-exact 的前提)。
100
+ """
101
+ h_len = 32 # SHA-256 摘要长
102
+ nums = pub.public_numbers()
103
+ k = (nums.n.bit_length() + 7) // 8
104
+ if len(message) > k - 2 * h_len - 2:
105
+ raise ValueError("OAEP 载荷超长:%d > %d" % (len(message), k - 2 * h_len - 2))
106
+ l_hash = hashlib.sha256(b"").digest() # 空 label
107
+ seed = csprng(h_len)
108
+ ps = b"\x00" * (k - len(message) - 2 * h_len - 2)
109
+ db = l_hash + ps + b"\x01" + message
110
+ db_mask = _mgf1_sha256(seed, k - h_len - 1)
111
+ masked_db = bytes(a ^ b for a, b in zip(db, db_mask))
112
+ seed_mask = _mgf1_sha256(masked_db, h_len)
113
+ masked_seed = bytes(a ^ b for a, b in zip(seed, seed_mask))
114
+ em = b"\x00" + masked_seed + masked_db
115
+ m = int.from_bytes(em, "big")
116
+ return pow(m, nums.e, nums.n).to_bytes(k, "big")
117
+
118
+
82
119
  def unwrap_dek(suite: Suite, wrap_priv: KeyMaterial, wrapped: bytes) -> bytes:
83
120
  """DEK 解包(入向);失败对外模糊(I7)。"""
84
121
  if suite.family == "RSA":
@@ -96,7 +133,7 @@ def unwrap_dek(suite: Suite, wrap_priv: KeyMaterial, wrapped: bytes) -> bytes:
96
133
 
97
134
  def build_dek_payload(suite: Suite, key: bytes, iv: bytes) -> str:
98
135
  """DEK 载荷 alg$base64url(key)$base64url(iv)(§6.1)。"""
99
- return "%s$%s$%s" % (suite.message_alg, b64url_encode(key), b64url_encode(iv))
136
+ return f"{suite.message_alg}${b64url_encode(key)}${b64url_encode(iv)}"
100
137
 
101
138
 
102
139
  def parse_dek_payload(suite: Suite, payload: str) -> Tuple[bytes, bytes]:
@@ -113,13 +150,13 @@ def parse_dek_payload(suite: Suite, payload: str) -> Tuple[bytes, bytes]:
113
150
  raise ProtocolFormatError("DEK 载荷 alg 未知:%r" % alg)
114
151
  if alg != suite.message_alg: # I3/I5:族比对先于 bulk 解密
115
152
  raise DekConsistencyError(
116
- "DEK 算法 %s 与套件 %s 要求的 %s 不符" % (alg, suite.security_req, suite.message_alg)
153
+ f"DEK 算法 {alg} 与套件 {suite.security_req} 要求的 {suite.message_alg} 不符"
117
154
  )
118
155
  try:
119
156
  key = b64url_decode(key_b64u)
120
157
  iv = b64url_decode(iv_b64u)
121
158
  except ValueError as exc:
122
- raise ProtocolFormatError("DEK 载荷 key/iv 编码非法:%s" % exc) from exc
159
+ raise ProtocolFormatError(f"DEK 载荷 key/iv 编码非法:{exc}") from exc
123
160
  expected_key_len = _AES_KEY_LEN if suite.family == "RSA" else _SM4_KEY_LEN
124
161
  if len(key) != expected_key_len or len(iv) != _IV_LEN:
125
162
  raise ProtocolFormatError(
@@ -142,28 +179,40 @@ def seal_l2(
142
179
  wire_body = json.dumps({"encrypted": b64url_encode(cipher_tag)}, separators=(",", ":")).encode()
143
180
  payload = build_dek_payload(suite, key, iv).encode("utf-8")
144
181
  wrapped = wrap_dek(suite, platform_pub, payload, csprng)
145
- return wire_body, "L2;dek=" + b64url_encode(wrapped)
182
+ return wire_body, f"L2;dek={b64url_encode(wrapped)}"
146
183
 
147
184
 
148
185
  def open_l2(suite: Suite, wrap_priv: KeyMaterial, wire_body: bytes, dek_b64u: str) -> bytes:
149
- """L2 解密(F6 第 3–5 步):DEK 解包(模糊)→ alg 族比对(明确)→ bulk 解密(模糊)。"""
186
+ """L2 解密(F6 第 4–6 步):DEK 解包(模糊)→ alg 族比对(明确)→ bulk 解密(模糊)。
187
+
188
+ 错误分类(playbook §0 / interop 合同):
189
+ - 信封 JSON 形态与各 base64url 段 = 公开结构知识 → 解析类明确(P2/n12);
190
+ - DEK 载荷为解包后明文,除 alg 跨族(D8 明确)外一律解密类模糊(I7,P3/n13)。
191
+ """
150
192
  try:
151
193
  wrapped = b64url_decode(dek_b64u)
152
194
  except ValueError:
153
- raise DecryptError() from None
195
+ raise ProtocolFormatError("x-wop-encrypt 的 dek 值非合法 base64url(F7)") from None
154
196
  try:
155
197
  payload = unwrap_dek(suite, wrap_priv, wrapped).decode("utf-8", errors="strict")
156
198
  except UnicodeDecodeError:
157
199
  # 解包成功但载荷非 UTF-8 → 与解包失败同归模糊(I7),不得向商户层逃逸
158
200
  raise DecryptError() from None
159
- key, iv = parse_dek_payload(suite, payload)
201
+ try:
202
+ key, iv = parse_dek_payload(suite, payload)
203
+ except DekConsistencyError:
204
+ raise # alg 跨族:解包后明文内的公开映射知识,明确(D8/I3)
205
+ except ProtocolFormatError:
206
+ # 载荷结构在解包后才可见,属密钥参与层;除 alg 跨族外一律归入解密类
207
+ # 模糊(I7 保守默认,interop 合同 n13 / playbook P3)
208
+ raise DecryptError() from None
160
209
  try:
161
210
  obj = json.loads(wire_body)
162
211
  encrypted = obj["encrypted"]
163
212
  except Exception:
164
- raise DecryptError() from None
213
+ raise ProtocolFormatError("L2 请求体须为含 encrypted 字段的 JSON 信封") from None
165
214
  try:
166
215
  cipher_tag = b64url_decode(encrypted)
167
216
  except (ValueError, TypeError):
168
- raise DecryptError() from None
217
+ raise ProtocolFormatError("L2 请求体 encrypted 字段非合法 base64url(F7)") from None
169
218
  return message_decrypt(suite, key, iv, cipher_tag)
@@ -56,7 +56,7 @@ def load_rsa_public_key(material: str, expected_bits: Optional[int] = None) -> r
56
56
  try:
57
57
  key = load_der_public_key(der)
58
58
  except (InvalidKey, ValueError, TypeError) as exc:
59
- raise KeyMaterialError("RSA 公钥解析失败(应为 SPKI DER Base64/PEM): %s" % exc) from exc
59
+ raise KeyMaterialError(f"RSA 公钥解析失败(应为 SPKI DER Base64/PEM): {exc}") from exc
60
60
  if not isinstance(key, rsa.RSAPublicKey):
61
61
  raise KeyMaterialError("非 RSA 公钥材料")
62
62
  if expected_bits is not None and key.key_size != expected_bits:
@@ -71,7 +71,7 @@ def load_rsa_private_key(material: str, expected_bits: Optional[int] = None) ->
71
71
  try:
72
72
  key = load_der_private_key(der, password=None)
73
73
  except (InvalidKey, ValueError, TypeError) as exc:
74
- raise KeyMaterialError("RSA 私钥解析失败(应为 PKCS#8 DER Base64/PEM): %s" % exc) from exc
74
+ raise KeyMaterialError(f"RSA 私钥解析失败(应为 PKCS#8 DER Base64/PEM): {exc}") from exc
75
75
  if not isinstance(key, rsa.RSAPrivateKey):
76
76
  raise KeyMaterialError("非 RSA 私钥材料")
77
77
  if expected_bits is not None and key.key_size != expected_bits:
@@ -41,7 +41,7 @@ class Sm2Ops(CryptSM2):
41
41
  def _point_on_curve(xy_hex: str) -> bool:
42
42
  x = int(xy_hex[:64], 16)
43
43
  y = int(xy_hex[64:], 16)
44
- return (y * y - (x * x * x + _A * x + _B)) % _P == 0
44
+ return (y**2 - (x**2 * x + _A * x + _B)) % _P == 0
45
45
 
46
46
 
47
47
  def sm2_sign_with_sm3(ops: Sm2Ops, data: bytes, k_hex: str) -> bytes:
@@ -72,7 +72,7 @@ def sm2_encrypt(ops: Sm2Ops, csprng, plaintext: bytes) -> bytes:
72
72
  x2, y2 = x2y2[:64], x2y2[64:]
73
73
  c2 = _xor_kdf(plaintext, x2y2)
74
74
  c3 = _sm3.sm3_hash(list(bytes.fromhex(x2 + plaintext.hex() + y2)))
75
- return bytes.fromhex("04" + c1_xy + c3) + c2
75
+ return bytes.fromhex(f"04{c1_xy}{c3}") + c2
76
76
 
77
77
 
78
78
  def sm2_decrypt(ops: Sm2Ops, cipher: bytes) -> bytes:
@@ -52,21 +52,17 @@ def parse_suite(security_req: Optional[str]) -> Suite:
52
52
  )
53
53
  _, key_alg, digest_alg = parts
54
54
  if key_alg not in _KEY_ALGORITHMS:
55
- raise UnsupportedSuiteError("不支持的密钥算法:%s" % key_alg)
55
+ raise UnsupportedSuiteError(f"不支持的密钥算法:{key_alg}")
56
56
  if digest_alg not in _DIGEST_ALGORITHMS:
57
- raise UnsupportedSuiteError("不支持的摘要算法:%s" % digest_alg)
57
+ raise UnsupportedSuiteError(f"不支持的摘要算法:{digest_alg}")
58
58
  family, key_bits = _KEY_ALGORITHMS[key_alg]
59
59
  digest_family, digest_tag = _DIGEST_ALGORITHMS[digest_alg]
60
60
  # I5:国际/国密跨族组合禁止(§2.3)
61
61
  if family != digest_family:
62
62
  raise UnsupportedSuiteError(
63
- "跨族算法组合被拒绝:%s(密钥族 %s 与摘要族 %s 不一致)"
64
- % (security_req, family, digest_family)
63
+ f"跨族算法组合被拒绝:{security_req}(密钥族 {family} 与摘要族 {digest_family} 不一致)"
65
64
  )
66
- if family == "RSA":
67
- key_wrap_alg = _FAMILY_KEY_WRAP[key_bits]
68
- else:
69
- key_wrap_alg = "SM2"
65
+ key_wrap_alg = _FAMILY_KEY_WRAP[key_bits] if family == "RSA" else "SM2"
70
66
  return Suite(
71
67
  security_req=security_req,
72
68
  family=family,
@@ -1,5 +1,5 @@
1
1
  # -*- coding: utf-8 -*-
2
- """httpx peer 适配器(extras:``pip install 'wop-sdk[httpx]'``)。"""
2
+ """httpx peer 适配器(extras:``pip install 'wop-python-sdk[httpx]'``)。"""
3
3
  from typing import Dict, Optional
4
4
 
5
5
  from . import HttpResponse, _READ_CHUNK, read_capped
@@ -17,7 +17,7 @@ class HttpxTransport:
17
17
  import httpx
18
18
  except ImportError as exc: # pragma: no cover —— 视环境而定
19
19
  raise ImportError(
20
- "httpx 未安装;peer 适配器请执行 pip install 'wop-sdk[httpx]'"
20
+ "httpx 未安装;peer 适配器请执行 pip install 'wop-python-sdk[httpx]'"
21
21
  ) from exc
22
22
  self._client = client if client is not None else httpx.Client()
23
23
 
@@ -1,5 +1,5 @@
1
1
  # -*- coding: utf-8 -*-
2
- """requests peer 适配器(extras:``pip install 'wop-sdk[requests]'``)。"""
2
+ """requests peer 适配器(extras:``pip install 'wop-python-sdk[requests]'``)。"""
3
3
  from typing import Dict, Optional
4
4
 
5
5
  from . import HttpResponse, _READ_CHUNK, read_capped
@@ -17,7 +17,7 @@ class RequestsTransport:
17
17
  import requests
18
18
  except ImportError as exc: # pragma: no cover —— 视环境而定
19
19
  raise ImportError(
20
- "requests 未安装;peer 适配器请执行 pip install 'wop-sdk[requests]'"
20
+ "requests 未安装;peer 适配器请执行 pip install 'wop-python-sdk[requests]'"
21
21
  ) from exc
22
22
  self._session = session if session is not None else requests.Session()
23
23