wop-python-sdk 0.1.7__py3-none-any.whl → 0.2.0__py3-none-any.whl
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.
- {wop_python_sdk-0.1.7.dist-info → wop_python_sdk-0.2.0.dist-info}/METADATA +39 -6
- wop_python_sdk-0.2.0.dist-info/RECORD +28 -0
- {wop_python_sdk-0.1.7.dist-info → wop_python_sdk-0.2.0.dist-info}/WHEEL +1 -1
- wop_sdk/__init__.py +21 -11
- wop_sdk/client.py +244 -9
- wop_sdk/config/__init__.py +12 -0
- wop_sdk/config/_loader.py +130 -0
- wop_sdk/config/_models.py +122 -0
- wop_sdk/config/_parser.py +186 -0
- wop_sdk/config/_validator.py +114 -0
- wop_sdk/config/wopSdkConfig.json +14 -0
- wop_sdk/errors.py +56 -1
- wop_sdk/sm2crypto.py +53 -4
- wop_sdk/suites.py +3 -2
- wop_sdk/transport_discovery.py +50 -0
- wop_sdk/transports/urllib_transport.py +10 -4
- wop_python_sdk-0.1.7.dist-info/RECORD +0 -21
- {wop_python_sdk-0.1.7.dist-info → wop_python_sdk-0.2.0.dist-info}/licenses/LICENSE +0 -0
- {wop_python_sdk-0.1.7.dist-info → wop_python_sdk-0.2.0.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: wop-python-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: WOP 商户侧官方 Python SDK:协议核心(签名/摘要/数字信封/验签解密)+ 可插拔 HTTP 适配层
|
|
5
5
|
Author: wop-platform
|
|
6
6
|
License: MIT
|
|
@@ -34,14 +34,16 @@ Dynamic: license-file
|
|
|
34
34
|
[](https://github.com/wop-platform/wop-python-sdk/actions/workflows/ci.yml) [](tests/features/wop_merchant.feature) 
|
|
35
35
|
|
|
36
36
|
|
|
37
|
+
> **WOP · 万联易达开放平台** 官方 Python SDK —— 协议与黄金向量真源:[wop-specs](https://github.com/wop-platform/wop-specs)
|
|
38
|
+
|
|
37
39
|
WOP 网关商户侧官方 Python 客户端库:封装协议核心(套件解析 / 结构化签名 / 内容摘要 /
|
|
38
40
|
L2 数字信封 / 验签解密)与可插拔 HTTP 适配层,使商户无需理解 canonicalRequest、
|
|
39
41
|
算法套件推导与线上字节格式即可安全对接网关。
|
|
40
42
|
|
|
41
|
-
- 协议真源:[crypto-strategy-spec.md](https://github.com/wop-platform/wop-specs/blob/main/crypto/crypto-strategy-spec.md)(v0.3-reviewed)+ [wop-sdk-spec.md](https://github.com/wop-platform/wop-specs/blob/main/
|
|
43
|
+
- 协议真源:[crypto-strategy-spec.md](https://github.com/wop-platform/wop-specs/blob/main/crypto/crypto-strategy-spec.md)(v0.3-reviewed)+ [wop-sdk-spec.md](https://github.com/wop-platform/wop-specs/blob/main/docs/specs/wop-sdk-spec.md)(v1.0-ratified)
|
|
42
44
|
- 向量真源:[crypto-vectors.json](https://github.com/wop-platform/wop-specs/blob/main/crypto/crypto-vectors.json)(本仓 fixture 为字节级副本,禁手改)
|
|
43
45
|
- Python ≥ 3.9
|
|
44
|
-
-
|
|
46
|
+
- 四套件全支持:`WOP-RSA2048-SHA256` / `WOP-RSA3072-SHA256` / `WOP-RSA4096-SHA256` / `WOP-SM2-SM3`
|
|
45
47
|
- 密码依赖(唯一指定路径):`cryptography`(RSA/AES)+ `gmssl ≥ 3.2.2`(SM2/SM3/SM4)
|
|
46
48
|
- 主包零额外依赖;HTTP 适配器以 peer 依赖交付(`wop-python-sdk[httpx]` / `wop-python-sdk[requests]`)
|
|
47
49
|
|
|
@@ -58,7 +60,7 @@ from wop_sdk.transports import UrllibTransport, send_draft
|
|
|
58
60
|
|
|
59
61
|
client = WopClient(WopConfig(
|
|
60
62
|
app_key="app_10012481831",
|
|
61
|
-
suite="WOP-
|
|
63
|
+
suite="WOP-RSA2048-SHA256", # 或 WOP-RSA4096-SHA256 / WOP-SM2-SM3
|
|
62
64
|
merchant_private_key=MERCHANT_PRIV_PEM, # 商户私钥(PEM 或 Base64 单行)
|
|
63
65
|
platform_public_key=PLATFORM_PUB_PEM, # 平台公钥(PEM 或 Base64 单行)
|
|
64
66
|
gateway_base_url="https://wop.example.com",
|
|
@@ -78,12 +80,31 @@ else:
|
|
|
78
80
|
print(result.reason) # 验签/解密失败对外模糊(I7),格式/完整性/一致性类明确
|
|
79
81
|
```
|
|
80
82
|
|
|
83
|
+
## ISV 子商户身份(ISV D-13)
|
|
84
|
+
|
|
85
|
+
代子商户调用业务 API 时,按请求传 `sub_mch_id`(值 = 子商户 `plf_co_id`):
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
draft = client.build_request("POST", "/gateway/order/create", body, level="L0",
|
|
89
|
+
sub_mch_id="PLF-SUB-001")
|
|
90
|
+
# 一站式调用:
|
|
91
|
+
result = client.execute("POST", "/gateway/order/create", body, level="L0",
|
|
92
|
+
sub_mch_id="PLF-SUB-001")
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
SDK 在签名前写入 `x-wop-sub-mch-id`,并自动纳入 `x-wop-sign` 的 signedHeaders。
|
|
96
|
+
首尾空白 trim 后发送;仅接受可打印 ASCII(0x20–0x7E)、无内部空白、≤128 字符,
|
|
97
|
+
违规抛 `ConfigurationError`。不传或纯空白 = 应用自身身份,头缺席,请求头集合与签名
|
|
98
|
+
与旧版逐字节一致(AC-20)。`extra_headers` 携带该头等价于参数;双来源同传构造即拒。
|
|
99
|
+
该头仅在网关子商户灰度放行且应用为 ISV 应用(`app_type=20`)时生效。
|
|
100
|
+
|
|
81
101
|
## 密钥准备
|
|
82
102
|
|
|
83
103
|
密钥入参为字符串(PEM 或 Base64 单行),SDK 内部解析(D12 分发契约):
|
|
84
104
|
|
|
85
105
|
| 套件 | 商户私钥 | 平台公钥 | 约束 |
|
|
86
106
|
|------|----------|----------|------|
|
|
107
|
+
| `WOP-RSA2048-SHA256` | PKCS#8 DER,Base64/PEM | X.509 SPKI DER,Base64/PEM | 密钥必须 2048 位 |
|
|
87
108
|
| `WOP-RSA3072-SHA256` | PKCS#8 DER,Base64/PEM | X.509 SPKI DER,Base64/PEM | 密钥必须 3072 位 |
|
|
88
109
|
| `WOP-RSA4096-SHA256` | 同上 | 同上 | 密钥必须 4096 位 |
|
|
89
110
|
| `WOP-SM2-SM3` | `d` 标量 32 字节,Base64 | 未压缩点 `04‖X‖Y` 65 字节,Base64 | 点必须在 sm2p256v1 曲线上(I5) |
|
|
@@ -130,14 +151,14 @@ pip install -e '.[httpx]' coverage
|
|
|
130
151
|
python3 -m pytest --cov=wop_sdk --cov-branch --cov-fail-under=98
|
|
131
152
|
```
|
|
132
153
|
|
|
133
|
-
覆盖:
|
|
154
|
+
覆盖:RSA2048/3072/4096 与 SM2 签名字节级断言、OAEP 包装/解包、AES-256-GCM 与 SM4-GCM
|
|
134
155
|
密文字节级断言、SM3/SHA-256 摘要、DEK 载荷组装、digest 头全部格式规则;负向量含
|
|
135
156
|
tamper / 跨族 / 63B、65B 签名 / 带 `=` 的 base64url / C1C2C3 旧国标顺序 /
|
|
136
157
|
MGF1-SHA1 陷阱密文,全部必须拒绝。CI(3.9–3.14 × linux/macOS 矩阵)执行同一命令。
|
|
137
158
|
|
|
138
159
|
另消费 `wop-specs` 组织级 interop 样本集(`tests/fixtures/interop-cases.json` 字节
|
|
139
160
|
副本,sha256 哨兵钉死):build 方向按冻结输入复现 draft(RSA byte-exact;SM2 按
|
|
140
|
-
opaque 剥离签名/包装段),verify 方向
|
|
161
|
+
opaque 剥离签名/包装段),verify 方向 24 条冻结样本逐条对账明文与错误分类
|
|
141
162
|
(canonical class 映射表见 `tests/test_interop.py`)。
|
|
142
163
|
|
|
143
164
|
## 错误处理与模糊化
|
|
@@ -148,3 +169,15 @@ opaque 剥离签名/包装段),verify 方向 23 条冻结样本逐条对账
|
|
|
148
169
|
- **模糊**(依赖密钥参与,防 oracle,I7):签名验证失败、解密失败——对外消息不区分
|
|
149
170
|
tag 失败 / 密钥不符等原因细节;DEK 载荷(解包后明文)结构畸形除 alg 跨族外一律
|
|
150
171
|
归入解密失败(interop 合同 n13 / 故障注入手册 P3)。
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## 🧩 WOP 生态导航 | Ecosystem
|
|
176
|
+
|
|
177
|
+
| 类别 | 组件 |
|
|
178
|
+
|------|------|
|
|
179
|
+
| 协议与向量真源 | [wop-specs](https://github.com/wop-platform/wop-specs) —— crypto-strategy-spec · wop-sdk-spec · 黄金测试向量 |
|
|
180
|
+
| 官方 SDK(六语言) | [Java](https://github.com/wop-platform/wop-java-sdk) · [Go](https://github.com/wop-platform/wop-go-sdk) · [Python](https://github.com/wop-platform/wop-python-sdk) · [PHP](https://github.com/wop-platform/wop-php-sdk) · [.NET](https://github.com/wop-platform/wop-dotnet-sdk) · [TypeScript](https://github.com/wop-platform/wop-typescript-sdk) |
|
|
181
|
+
| 浏览器工作台 | [wop-web-tools](https://github.com/wop-platform/wop-web-tools) —— 密钥生成 · 报文联调 · 国密 · 六语言代码片段 |
|
|
182
|
+
| Agent 技能包 | [wop-skills](https://github.com/wop-platform/wop-skills) —— 零代码调用 · 联调对拍 · 62 错误码排错 |
|
|
183
|
+
| 平台服务(企业内部) | 统一接入网关 · 核心逻辑服务 · 回调服务 · 开发者门户 · 文档中心 |
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
wop_python_sdk-0.2.0.dist-info/licenses/LICENSE,sha256=9HPK_oKzyRh2oK3x0YiYrE1envRgKMfD1LWgGSStuW8,1069
|
|
2
|
+
wop_sdk/__init__.py,sha256=2BD6-HskPCaNPtM9Y_7XG9NYtxC9C7Awwxc9ZE-zL10,1565
|
|
3
|
+
wop_sdk/canonical.py,sha256=pFAaMBIdQ6rQaLCKhDSzGsVqxm7VXjv70-CQHQIiPQA,1497
|
|
4
|
+
wop_sdk/client.py,sha256=YDAsHa0big_8Tlf86GU0m_vWFGfMBFVejxsidfeFr9U,23114
|
|
5
|
+
wop_sdk/digest.py,sha256=f2WxJv8jOavccShGzMF7qQhxEpIW5rGvQ2taj8aJzsI,2491
|
|
6
|
+
wop_sdk/encoding.py,sha256=KNgICfZ6hnjC13oVt377Vg17BI-gfO79pEXsQrCPeZ0,3412
|
|
7
|
+
wop_sdk/envelope.py,sha256=sncxu7h2mBDtFAatp2Pu2s7DiBjH7Xe_l1rDCvlxMWo,9873
|
|
8
|
+
wop_sdk/errors.py,sha256=k4gB9sW169C8exADKo_NK2yhaVR4lLwBjFYDnytPACo,3704
|
|
9
|
+
wop_sdk/keys.py,sha256=PTB8Ot-ssYwj015REkYVcopL8lovMx0hcOG3JoNZ_O0,4339
|
|
10
|
+
wop_sdk/signature.py,sha256=pasDfgPPhbbsDK-5_iG4n2bG5jCI-P8qjzykYCjevJg,2486
|
|
11
|
+
wop_sdk/sm2crypto.py,sha256=oGR9yQynzyaMpiHNmkfxVhR9GEcZ5XPVhwHBRFdzaCo,7259
|
|
12
|
+
wop_sdk/sm4gcm.py,sha256=I5FViIfsyyFSsog7VYnkwRlTT_NNizFrMss6NRh5cjk,3247
|
|
13
|
+
wop_sdk/suites.py,sha256=6TrIxYrGp74sbAylE2-2xYqG_5M1RfHdDSKFYnJdDZw,2959
|
|
14
|
+
wop_sdk/transport_discovery.py,sha256=nqYxTuZMiptdtkj7n6tyISDeryKKIJ_g49GPcSbEKu8,1958
|
|
15
|
+
wop_sdk/config/__init__.py,sha256=t57RgxwyW1NEEgug51tKTjCciR_kRTzBBGZT0WiRXnk,320
|
|
16
|
+
wop_sdk/config/_loader.py,sha256=I4wFw61ITKZhqfUkhZv12sD2zSOMyEG9Zpa9UpU0vN4,4726
|
|
17
|
+
wop_sdk/config/_models.py,sha256=qwf4T2Rfivujmdabp-lhOpeQzhNfW9GYW04mgdVUShU,4250
|
|
18
|
+
wop_sdk/config/_parser.py,sha256=Ol2Sv2rvmmwl7bKomu41V3tJq5nP3DY_nJyBlsawnBg,6997
|
|
19
|
+
wop_sdk/config/_validator.py,sha256=ot5bMspV3GOEiDh2-N4d0UZhIZro1hXml5GZq8ei6tI,5126
|
|
20
|
+
wop_sdk/config/wopSdkConfig.json,sha256=lBzm3y9Aq-BBHERrEdui1RxWLXZimuux86x8NoShJog,372
|
|
21
|
+
wop_sdk/transports/__init__.py,sha256=mvMxa8yW5eAgSGLbmzJJEYgMPFZ-0V7u7u_XKsVQU-o,2401
|
|
22
|
+
wop_sdk/transports/httpx_transport.py,sha256=5tPYU6BnjCMFZj6JVGzvBGjAAED00NqwWsvuR1e9oWc,1478
|
|
23
|
+
wop_sdk/transports/requests_transport.py,sha256=i4YFW_MfWyuqdlG7vKl0sh4vUKn-2TR1eR4c-VgD4Zc,1556
|
|
24
|
+
wop_sdk/transports/urllib_transport.py,sha256=hZB1efYUv_7e5fcK2-DrdEhuaCVqaa96xrznZvN06SM,1895
|
|
25
|
+
wop_python_sdk-0.2.0.dist-info/METADATA,sha256=F5GgyOqIjlUeXYYgvLsiWEJwOUHiR4oRkhDY0HRoKO4,10246
|
|
26
|
+
wop_python_sdk-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
27
|
+
wop_python_sdk-0.2.0.dist-info/top_level.txt,sha256=TotiKMyRTEgc7yV8T6-Hwjl9NdddNjoBY3miEEKSEyY,8
|
|
28
|
+
wop_python_sdk-0.2.0.dist-info/RECORD,,
|
wop_sdk/__init__.py
CHANGED
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
from importlib.metadata import PackageNotFoundError, version as _dist_version
|
|
7
7
|
|
|
8
8
|
from .client import RequestDraft, VerifyResult, WopClient, WopConfig
|
|
9
|
+
from .config import HttpClientSettings, WopSdkConfig, clear_cache, load, load_default
|
|
9
10
|
from .errors import (
|
|
11
|
+
ConfigurationError,
|
|
10
12
|
DecryptError,
|
|
11
13
|
DekConsistencyError,
|
|
12
14
|
DigestMismatchError,
|
|
@@ -15,6 +17,7 @@ from .errors import (
|
|
|
15
17
|
SignatureVerifyError,
|
|
16
18
|
SuiteParseError,
|
|
17
19
|
UnsupportedSuiteError,
|
|
20
|
+
WopGatewayResponseError,
|
|
18
21
|
WopSdkError,
|
|
19
22
|
)
|
|
20
23
|
from .suites import Suite, parse_suite
|
|
@@ -27,20 +30,27 @@ except PackageNotFoundError: # pragma: no cover —— 无分发元数据时的
|
|
|
27
30
|
__version__ = "0.0.0"
|
|
28
31
|
|
|
29
32
|
__all__ = [
|
|
30
|
-
"
|
|
31
|
-
"
|
|
33
|
+
"ConfigurationError",
|
|
34
|
+
"DecryptError",
|
|
35
|
+
"DekConsistencyError",
|
|
36
|
+
"DigestMismatchError",
|
|
37
|
+
"HttpClientSettings",
|
|
38
|
+
"KeyMaterialError",
|
|
39
|
+
"ProtocolFormatError",
|
|
32
40
|
"RequestDraft",
|
|
33
|
-
"
|
|
41
|
+
"SignatureVerifyError",
|
|
34
42
|
"Suite",
|
|
35
|
-
"parse_suite",
|
|
36
|
-
"WopSdkError",
|
|
37
43
|
"SuiteParseError",
|
|
38
44
|
"UnsupportedSuiteError",
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
+
"VerifyResult",
|
|
46
|
+
"WopClient",
|
|
47
|
+
"WopConfig",
|
|
48
|
+
"WopGatewayResponseError",
|
|
49
|
+
"WopSdkConfig",
|
|
50
|
+
"WopSdkError",
|
|
45
51
|
"__version__",
|
|
52
|
+
"clear_cache",
|
|
53
|
+
"load",
|
|
54
|
+
"load_default",
|
|
55
|
+
"parse_suite",
|
|
46
56
|
]
|
wop_sdk/client.py
CHANGED
|
@@ -7,16 +7,25 @@
|
|
|
7
7
|
验签/解密类 reason 模糊(I7),格式/完整性/一致性类 reason 明确(10.2)。
|
|
8
8
|
"""
|
|
9
9
|
import json
|
|
10
|
+
import logging
|
|
10
11
|
import os
|
|
12
|
+
import threading
|
|
11
13
|
import time
|
|
14
|
+
import uuid
|
|
12
15
|
from dataclasses import dataclass
|
|
13
|
-
from typing import Callable, Dict, Optional
|
|
16
|
+
from typing import TYPE_CHECKING, Callable, Dict, Optional, Union
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from .config._models import WopSdkConfig
|
|
20
|
+
from .transports import Transport
|
|
14
21
|
|
|
15
22
|
from .canonical import build_canonical, canonical_headers
|
|
16
23
|
from .digest import build_digest_header, verify_digest_header
|
|
17
24
|
from .encoding import b64url_encode
|
|
18
25
|
from .envelope import open_l2, seal_l2
|
|
26
|
+
from .config._validator import validate_api_path
|
|
19
27
|
from .errors import (
|
|
28
|
+
ConfigurationError,
|
|
20
29
|
DecryptError,
|
|
21
30
|
DekConsistencyError,
|
|
22
31
|
DigestMismatchError,
|
|
@@ -24,6 +33,7 @@ from .errors import (
|
|
|
24
33
|
SignatureVerifyError,
|
|
25
34
|
SuiteParseError,
|
|
26
35
|
UnsupportedSuiteError,
|
|
36
|
+
WopGatewayResponseError,
|
|
27
37
|
WopSdkError,
|
|
28
38
|
)
|
|
29
39
|
from .keys import (
|
|
@@ -33,13 +43,77 @@ from .keys import (
|
|
|
33
43
|
load_sm2_public_key,
|
|
34
44
|
)
|
|
35
45
|
from .signature import sign, verify
|
|
36
|
-
from .sm2crypto import Sm2Ops, sm2_derive_public_hex
|
|
46
|
+
from .sm2crypto import PLATFORM_INBOUND_USER_ID, Sm2Ops, sm2_derive_public_hex
|
|
37
47
|
from .suites import Suite, parse_suite
|
|
38
48
|
|
|
39
49
|
Csprng = Callable[[int], bytes]
|
|
40
50
|
|
|
41
51
|
_LEVELS = ("L0", "L2")
|
|
42
52
|
_DEK_PREFIX = "L2;dek="
|
|
53
|
+
_HEADER_REQUEST_ID = "x-wop-request-id"
|
|
54
|
+
_HEADER_SUB_MCH_ID = "x-wop-sub-mch-id"
|
|
55
|
+
|
|
56
|
+
# 附录 I/I3 日志义务:出向构造点 INFO 打印最终透传头值(非敏感,豁免脱敏)
|
|
57
|
+
_OUT_LOG = logging.getLogger("wop_sdk.outbound")
|
|
58
|
+
|
|
59
|
+
# 附录 I/I2 trim 集 = G2 TrimAll 空白类(空格、\t、\n、\x0B、\f、\r);不用 str.strip()(Unicode 空白超集)
|
|
60
|
+
_TRIM_CHARS = " \t\n\x0B\f\r"
|
|
61
|
+
|
|
62
|
+
# 附录 I/I3:缺省 requestId 生成器(可整体替换——测试确定性锚,与 csprng 注入同级)
|
|
63
|
+
request_id_generator: Callable[[], str] = lambda: uuid.uuid4().hex
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def resolve_request_id(raw: Optional[str]) -> Optional[str]:
|
|
67
|
+
"""附录 I/I2 requestId 校验(构造即拒,configuration 类)。
|
|
68
|
+
|
|
69
|
+
1. trim 前按**原值**逐字符扫描控制字符(< 0x20 或 == 0x7F,含 CR/LF/NUL/DEL)——防头注入;
|
|
70
|
+
2. trim(G2 TrimAll 同集)后为空 → 视为未设置(返回 None,走缺省生成);
|
|
71
|
+
3. trim 后 UTF-8 编码字节 > 128 → 拒(网关 header 缓冲按字节计)。
|
|
72
|
+
返回 trim 后上行值;None = 未设置。
|
|
73
|
+
"""
|
|
74
|
+
if raw is None:
|
|
75
|
+
return None
|
|
76
|
+
for ch in raw:
|
|
77
|
+
if ord(ch) < 0x20 or ord(ch) == 0x7F:
|
|
78
|
+
raise ConfigurationError(f"requestId 含控制字符(防头注入): {ord(ch)}")
|
|
79
|
+
trimmed = raw.strip(_TRIM_CHARS)
|
|
80
|
+
if not trimmed:
|
|
81
|
+
return None
|
|
82
|
+
utf8_len = len(trimmed.encode("utf-8"))
|
|
83
|
+
if utf8_len > 128:
|
|
84
|
+
raise ConfigurationError(f"requestId UTF-8 字节长度不能超过 128(实际 {utf8_len})")
|
|
85
|
+
return trimmed
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def resolve_sub_mch_id(raw: Optional[str]) -> Optional[str]:
|
|
89
|
+
"""ISV D-13 子商户身份头 x-wop-sub-mch-id 校验(构造即拒,configuration 类)。
|
|
90
|
+
|
|
91
|
+
1. trim 前按**原值**逐字符扫描可打印 ASCII(0x20..0x7E)——控制字符(CR/LF/NUL/DEL 等)
|
|
92
|
+
防头注入,非 ASCII 在 HTTP 头编码下不可靠;
|
|
93
|
+
2. trim(G2 TrimAll 同集)后为空 → 视为未设置(返回 None,头缺席 = 应用自身身份,AC-20);
|
|
94
|
+
3. trim 后含内部空格 → 拒(网关 canonical 的 trimall 会折叠内部空白,而身份查询只做
|
|
95
|
+
trim,内部空白破坏签名与身份一一对应);
|
|
96
|
+
4. trim 后长度 > 128 字符 → 拒(ASCII 下字符数 = 字节数)。
|
|
97
|
+
返回 trim 后上行值;None = 未设置。
|
|
98
|
+
"""
|
|
99
|
+
if raw is None:
|
|
100
|
+
return None
|
|
101
|
+
if not isinstance(raw, str):
|
|
102
|
+
# J2 构造即拒:非 str(如数值型 plf_co_id)不得被 str() 归一后静默入签
|
|
103
|
+
raise ConfigurationError(
|
|
104
|
+
"subMchId 须为字符串(子商户 plf_co_id),实际 %s" % type(raw).__name__
|
|
105
|
+
)
|
|
106
|
+
for ch in raw:
|
|
107
|
+
if ord(ch) < 0x20 or ord(ch) > 0x7E:
|
|
108
|
+
raise ConfigurationError(f"subMchId 须为可打印 ASCII(防头注入/签名歧义): {ord(ch)}")
|
|
109
|
+
trimmed = raw.strip(_TRIM_CHARS)
|
|
110
|
+
if not trimmed:
|
|
111
|
+
return None
|
|
112
|
+
if " " in trimmed:
|
|
113
|
+
raise ConfigurationError("subMchId 不能包含内部空白")
|
|
114
|
+
if len(trimmed) > 128:
|
|
115
|
+
raise ConfigurationError(f"subMchId 长度不能超过 128(实际 {len(trimmed)})")
|
|
116
|
+
return trimmed
|
|
43
117
|
|
|
44
118
|
|
|
45
119
|
def _now_ms() -> int:
|
|
@@ -57,6 +131,14 @@ class WopConfig:
|
|
|
57
131
|
platform_public_key: str
|
|
58
132
|
gateway_base_url: Optional[str] = None
|
|
59
133
|
|
|
134
|
+
def __repr__(self) -> str:
|
|
135
|
+
# K16:凭证字段打码
|
|
136
|
+
return (
|
|
137
|
+
f"WopConfig(app_key={self.app_key!r}, suite={self.suite!r}, "
|
|
138
|
+
f"merchant_private_key=****, platform_public_key=****, "
|
|
139
|
+
f"gateway_base_url={self.gateway_base_url!r})"
|
|
140
|
+
)
|
|
141
|
+
|
|
60
142
|
|
|
61
143
|
@dataclass
|
|
62
144
|
class RequestDraft:
|
|
@@ -84,11 +166,14 @@ class VerifyResult:
|
|
|
84
166
|
|
|
85
167
|
|
|
86
168
|
class WopClient:
|
|
87
|
-
"""
|
|
169
|
+
"""协议核心客户端 + 一站式 execute 入口(config-spec K17)。"""
|
|
170
|
+
|
|
171
|
+
_default_lock = threading.Lock()
|
|
172
|
+
_default_client: Optional["WopClient"] = None
|
|
88
173
|
|
|
89
174
|
def __init__(self, config: WopConfig, csprng: Csprng = os.urandom):
|
|
90
175
|
if not config.app_key or not config.app_key.strip():
|
|
91
|
-
raise
|
|
176
|
+
raise ConfigurationError("appKey 不能为空")
|
|
92
177
|
self._config = config
|
|
93
178
|
self._suite = parse_suite(config.suite)
|
|
94
179
|
if self._suite.family == "RSA":
|
|
@@ -101,15 +186,70 @@ class WopClient:
|
|
|
101
186
|
else:
|
|
102
187
|
d = load_sm2_private_key(config.merchant_private_key)
|
|
103
188
|
merchant_pub_hex = sm2_derive_public_hex(d.hex())
|
|
104
|
-
self._signer = Sm2Ops(
|
|
189
|
+
self._signer = Sm2Ops(
|
|
190
|
+
private_key_hex=d.hex(),
|
|
191
|
+
public_xy_hex=merchant_pub_hex,
|
|
192
|
+
user_id=config.app_key,
|
|
193
|
+
)
|
|
105
194
|
platform_pub = load_sm2_public_key(config.platform_public_key)
|
|
106
|
-
|
|
195
|
+
# spec:D15 入向验签 ZA userId = 平台固定值(非商户 appKey;D14 的 appKey 仅限
|
|
196
|
+
# 出向签名者 _signer)。L2 出向加密不走 _sm3_z,user_id 对 seal_l2 无影响。
|
|
197
|
+
self._wrap_pub = Sm2Ops(
|
|
198
|
+
public_xy_hex=platform_pub.xy_hex, user_id=PLATFORM_INBOUND_USER_ID
|
|
199
|
+
)
|
|
107
200
|
self._csprng = csprng
|
|
201
|
+
self._sdk_config: Optional["WopSdkConfig"] = None
|
|
202
|
+
self._transport: Optional["Transport"] = None
|
|
203
|
+
|
|
204
|
+
@classmethod
|
|
205
|
+
def default_client(cls) -> "WopClient":
|
|
206
|
+
"""惰性:load_default → 传输发现 → 构造;并发首调单实例(K15)。"""
|
|
207
|
+
with cls._default_lock:
|
|
208
|
+
if cls._default_client is None:
|
|
209
|
+
from .config import load_default
|
|
210
|
+
|
|
211
|
+
cls._default_client = cls.from_config(load_default())
|
|
212
|
+
return cls._default_client
|
|
213
|
+
|
|
214
|
+
@classmethod
|
|
215
|
+
def from_config(cls, sdk_config: "WopSdkConfig", csprng: Csprng = os.urandom) -> "WopClient":
|
|
216
|
+
"""显式配置构造(不进默认实例缓存,K11)。"""
|
|
217
|
+
from .transport_discovery import discover_transport
|
|
218
|
+
from .transports import UrllibTransport
|
|
219
|
+
|
|
220
|
+
if sdk_config.transport is not None:
|
|
221
|
+
transport = sdk_config.transport
|
|
222
|
+
else:
|
|
223
|
+
transport = discover_transport()
|
|
224
|
+
if isinstance(transport, UrllibTransport):
|
|
225
|
+
# 默认 urllib 传输接线 http_client.read_timeout(毫秒),
|
|
226
|
+
# 未配置时 HttpClientSettings 默认 30s;显式注入的 transport 不改写
|
|
227
|
+
transport = UrllibTransport(timeout_ms=sdk_config.http_client.read_timeout)
|
|
228
|
+
core = WopConfig(
|
|
229
|
+
app_key=sdk_config.app_key,
|
|
230
|
+
suite=sdk_config.suite,
|
|
231
|
+
merchant_private_key=sdk_config.merchant_private_key,
|
|
232
|
+
platform_public_key=sdk_config.platform_public_key,
|
|
233
|
+
gateway_base_url=sdk_config.server_root,
|
|
234
|
+
)
|
|
235
|
+
client = cls(core, csprng=csprng)
|
|
236
|
+
client._sdk_config = sdk_config
|
|
237
|
+
client._transport = transport
|
|
238
|
+
return client
|
|
239
|
+
|
|
240
|
+
@classmethod
|
|
241
|
+
def reset_default(cls) -> None:
|
|
242
|
+
"""丢弃默认实例;须先 clear_cache() 再调用(K26)。"""
|
|
243
|
+
with cls._default_lock:
|
|
244
|
+
cls._default_client = None
|
|
108
245
|
|
|
109
246
|
@property
|
|
110
247
|
def suite(self) -> Suite:
|
|
111
248
|
return self._suite
|
|
112
249
|
|
|
250
|
+
def __repr__(self) -> str:
|
|
251
|
+
return f"WopClient(suite={self._suite.security_req!r}, app_key={self._config.app_key!r})"
|
|
252
|
+
|
|
113
253
|
# ---------- 出向 ----------
|
|
114
254
|
|
|
115
255
|
def build_request(
|
|
@@ -124,15 +264,63 @@ class WopClient:
|
|
|
124
264
|
extra_headers: Optional[Dict[str, str]] = None,
|
|
125
265
|
timestamp_ms: Optional[int] = None,
|
|
126
266
|
nonce: Optional[str] = None,
|
|
267
|
+
request_id: Optional[str] = None,
|
|
268
|
+
sub_mch_id: Optional[str] = None,
|
|
127
269
|
) -> RequestDraft:
|
|
128
270
|
"""构造请求(F9):协议头组装 → L2 可选封装 → canonicalRequest → 签名。
|
|
129
271
|
|
|
130
272
|
timestamp_ms / nonce 为确定性钩子(重放/联调用;镜像 Go WithTimestamp/
|
|
131
273
|
WithNonce)。随机流消费顺序合同(wop-specs/interop/v1):
|
|
132
274
|
[16B nonce 池][CEK][12B IV][k…]——nonce 注入时跳过 nonce 池段。
|
|
275
|
+
request_id 为商户请求标识(附录 I:x-wop-request-id 透传头,恒不入签;
|
|
276
|
+
须为不含个人数据的不透明关联标识);未传/空白 → 缺省生成 UUID 去连字符
|
|
277
|
+
(头恒存在),显式传值 trim 后原值上行,控制字符(trim 前扫描)与超长
|
|
278
|
+
(trim 后 UTF-8 字节 > 128)构造即拒。extra_headers 携带该头等价
|
|
279
|
+
request_id 参数(同解析链、恒不入签);双来源同传构造即拒(configuration)。
|
|
280
|
+
sub_mch_id 为 ISV 子商户身份(D-13,值 = 子商户 plf_co_id):签名前写入
|
|
281
|
+
x-wop-sub-mch-id 并自动纳入 signedHeaders;未传/空白 = 应用自身身份(头缺席,
|
|
282
|
+
与旧版逐字节一致,AC-20)。须为可打印 ASCII、无内部空白、trim 后 ≤128 字符,
|
|
283
|
+
违规构造即拒。extra_headers 携带该头等价 sub_mch_id 参数,双来源同传即拒。
|
|
133
284
|
"""
|
|
134
285
|
if level not in _LEVELS:
|
|
135
|
-
raise
|
|
286
|
+
raise ConfigurationError("level 必须为 L0 或 L2,实际 %r" % level)
|
|
287
|
+
# 附录 I/I2:requestId 构造即校验(fail-fast,不延迟到发送前)。
|
|
288
|
+
# extra_headers 的 x-wop-request-id 等价显式参数(同 trim/控制字符/长度链);
|
|
289
|
+
# 双来源同传 = 歧义,构造即拒(K12 fail-fast 同款)
|
|
290
|
+
header_request_id = next(
|
|
291
|
+
(
|
|
292
|
+
str(value)
|
|
293
|
+
for name, value in (extra_headers or {}).items()
|
|
294
|
+
if name.strip().lower() == _HEADER_REQUEST_ID
|
|
295
|
+
),
|
|
296
|
+
None,
|
|
297
|
+
)
|
|
298
|
+
if header_request_id is not None and request_id is not None:
|
|
299
|
+
raise ConfigurationError(
|
|
300
|
+
"request_id 参数与 extra_headers['x-wop-request-id'] 同时显式提供,请仅保留一处"
|
|
301
|
+
)
|
|
302
|
+
resolved_request_id = resolve_request_id(
|
|
303
|
+
request_id if request_id is not None else header_request_id
|
|
304
|
+
)
|
|
305
|
+
# ISV D-13:subMchId 同解析链(extra_headers 等价参数;双来源同传 = 歧义即拒)
|
|
306
|
+
header_sub_mch_id = next(
|
|
307
|
+
(
|
|
308
|
+
value
|
|
309
|
+
for name, value in (extra_headers or {}).items()
|
|
310
|
+
if name.strip().lower() == _HEADER_SUB_MCH_ID
|
|
311
|
+
),
|
|
312
|
+
None,
|
|
313
|
+
)
|
|
314
|
+
# 两侧各按 J2 解析(trim 后空 = 未设置):只有两侧都解析出值才构成双来源歧义
|
|
315
|
+
param_resolved = resolve_sub_mch_id(sub_mch_id)
|
|
316
|
+
header_resolved = resolve_sub_mch_id(header_sub_mch_id)
|
|
317
|
+
if param_resolved is not None and header_resolved is not None:
|
|
318
|
+
raise ConfigurationError(
|
|
319
|
+
"sub_mch_id 参数与 extra_headers['x-wop-sub-mch-id'] 同时显式提供,请仅保留一处"
|
|
320
|
+
)
|
|
321
|
+
resolved_sub_mch_id = (
|
|
322
|
+
param_resolved if param_resolved is not None else header_resolved
|
|
323
|
+
)
|
|
136
324
|
safe_method = method.strip().upper()
|
|
137
325
|
# spec:interop-v1 随机流消费顺序:nonce 池最前,先于 seal_l2 的 CEK/IV
|
|
138
326
|
if not nonce:
|
|
@@ -151,6 +339,9 @@ class WopClient:
|
|
|
151
339
|
"x-wop-timestamp": str(_now_ms() if timestamp_ms is None else int(timestamp_ms)),
|
|
152
340
|
"x-wop-nonce": nonce,
|
|
153
341
|
}
|
|
342
|
+
# ISV D-13:签名前写入,signedHeaders 自动包含;缺席时头集合与旧行为完全一致
|
|
343
|
+
if resolved_sub_mch_id is not None:
|
|
344
|
+
headers[_HEADER_SUB_MCH_ID] = resolved_sub_mch_id
|
|
154
345
|
if wire is not None:
|
|
155
346
|
# D2:有 body 必产 digest;I1:digest 必入 signedHeaders(下方签名集合即全部头)
|
|
156
347
|
headers["x-wop-content-digest"] = build_digest_header(self._suite, wire)
|
|
@@ -160,6 +351,10 @@ class WopClient:
|
|
|
160
351
|
app_headers: Dict[str, str] = {}
|
|
161
352
|
for name, value in (extra_headers or {}).items():
|
|
162
353
|
low = name.strip().lower()
|
|
354
|
+
if low in (_HEADER_REQUEST_ID, _HEADER_SUB_MCH_ID):
|
|
355
|
+
# request_id 恒不入签(附录 I);sub_mch_id 已在签名前由解析链写入。
|
|
356
|
+
# 若此处再并入会覆盖已验证值 → 签名/身份不一致
|
|
357
|
+
continue
|
|
163
358
|
if low.startswith("x-wop-"):
|
|
164
359
|
headers[low] = str(value).strip()
|
|
165
360
|
else:
|
|
@@ -173,6 +368,11 @@ class WopClient:
|
|
|
173
368
|
headers["x-wop-sign"] = (
|
|
174
369
|
f'{self._suite.security_req} {auth}/{";".join(sorted(iter(headers)))}/{b64url_encode(sig)}'
|
|
175
370
|
)
|
|
371
|
+
# requestId 透传头(附录 I):在签名落盘**之后**写入,保证不在 signedHeaders 冻结清单中;
|
|
372
|
+
# 商户未传(含 trim 后为空)→ 缺省生成,最终头恒存在
|
|
373
|
+
headers[_HEADER_REQUEST_ID] = resolved_request_id or request_id_generator()
|
|
374
|
+
# 附录 I/I3 日志义务:INFO 级打印最终透传头值,供网关 AccessLog 关联排查
|
|
375
|
+
_OUT_LOG.info("x-wop-request-id=%s %s %s", headers[_HEADER_REQUEST_ID], safe_method, path)
|
|
176
376
|
out: Dict[str, str] = dict(headers)
|
|
177
377
|
if wire is not None:
|
|
178
378
|
out.setdefault("content-type", "application/json")
|
|
@@ -182,14 +382,14 @@ class WopClient:
|
|
|
182
382
|
@staticmethod
|
|
183
383
|
def _normalize_body(body: Optional[object]) -> bytes:
|
|
184
384
|
if body is None:
|
|
185
|
-
raise
|
|
385
|
+
raise ConfigurationError("L2 封装需要明文 body")
|
|
186
386
|
if isinstance(body, bytes):
|
|
187
387
|
return body
|
|
188
388
|
if isinstance(body, str):
|
|
189
389
|
return body.encode("utf-8")
|
|
190
390
|
if isinstance(body, dict):
|
|
191
391
|
return json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
192
|
-
raise
|
|
392
|
+
raise ConfigurationError("body 仅接受 bytes/str/dict,实际 %r" % type(body).__name__)
|
|
193
393
|
|
|
194
394
|
# ---------- 入向 ----------
|
|
195
395
|
|
|
@@ -215,6 +415,41 @@ class WopClient:
|
|
|
215
415
|
"""校验平台回调(URI 取回调 path,方法恒 POST)。"""
|
|
216
416
|
return self.verify_response(headers, body, callback_path, method="POST")
|
|
217
417
|
|
|
418
|
+
def execute(
|
|
419
|
+
self,
|
|
420
|
+
method: str,
|
|
421
|
+
path: str,
|
|
422
|
+
body: Optional[Union[bytes, str, dict]] = None,
|
|
423
|
+
*,
|
|
424
|
+
level: str = "L0",
|
|
425
|
+
request_id: Optional[str] = None,
|
|
426
|
+
sub_mch_id: Optional[str] = None,
|
|
427
|
+
) -> VerifyResult:
|
|
428
|
+
"""一站式:签名 → 发送 → 非 2xx 拦截 → 验签解密(§2 execute 语义)。"""
|
|
429
|
+
if self._transport is None or self._sdk_config is None:
|
|
430
|
+
raise ConfigurationError("execute 需要经 from_config/default_client 构造的客户端")
|
|
431
|
+
validate_api_path(path)
|
|
432
|
+
draft = self.build_request(
|
|
433
|
+
method,
|
|
434
|
+
path,
|
|
435
|
+
body,
|
|
436
|
+
level=level,
|
|
437
|
+
expired_seconds=self._sdk_config.expired_seconds,
|
|
438
|
+
request_id=request_id,
|
|
439
|
+
sub_mch_id=sub_mch_id,
|
|
440
|
+
)
|
|
441
|
+
from .transports import send_draft
|
|
442
|
+
|
|
443
|
+
response = send_draft(self._transport, self._sdk_config.server_root, draft)
|
|
444
|
+
if not 200 <= response.status < 300:
|
|
445
|
+
body_len = len(response.body or b"")
|
|
446
|
+
raise WopGatewayResponseError(
|
|
447
|
+
f"WOP 网关返回 HTTP {response.status}(响应体 {body_len} 字节)",
|
|
448
|
+
response.status,
|
|
449
|
+
response.body,
|
|
450
|
+
)
|
|
451
|
+
return self.verify_response(response.headers, response.body, path, method=draft.method)
|
|
452
|
+
|
|
218
453
|
def _verify_flow(
|
|
219
454
|
self, lower: Dict[str, str], body: bytes, path: str, method: str, query_string: str
|
|
220
455
|
) -> VerifyResult:
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""配置加载层(config-spec §3–§4,附录 D Python 绑定)。"""
|
|
3
|
+
from ._loader import clear_cache, load, load_default
|
|
4
|
+
from ._models import HttpClientSettings, WopSdkConfig
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"HttpClientSettings",
|
|
8
|
+
"WopSdkConfig",
|
|
9
|
+
"clear_cache",
|
|
10
|
+
"load",
|
|
11
|
+
"load_default",
|
|
12
|
+
]
|