Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ jobs:
run: |
python -m pip install --upgrade pip
# pytest/pytest-bdd 属测试工具链而非运行时依赖,CI 显式安装;
# 上限锁定:pytest 9.2 移除 FixtureManager._arg2fixturedefs,pytest-bdd(≤9.0)尚未跟进,
# 不限版即全量 BDD 用例 AttributeError(与业务代码无关);8.4.2/8.1.0 为最近一次全绿组合
# coverage[toml]:py<3.11 需 tomli 才能读 pyproject.toml 的 coverage 配置
pip install -e '.[httpx,requests]' pytest pytest-bdd pytest-cov 'coverage[toml]'
pip install -e '.[httpx,requests]' 'pytest==8.4.2' 'pytest-bdd==8.1.0' pytest-cov 'coverage[toml]'
- name: Test with coverage gate (line+branch ≥ 98%, vector conformance must pass)
run: python -m pytest --cov=wop_sdk --cov-branch --cov-fail-under=98
- name: Coverage detail (line & branch)
Expand Down
22 changes: 22 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,28 @@ else:
# integrity / consistency errors are explicit
```

## ISV Sub-Merchant Identity (ISV D-13)

When calling business APIs on behalf of a sub-merchant, pass `sub_mch_id` per request
(value = the sub-merchant's `plf_co_id`):

```python
draft = client.build_request("POST", "/gateway/order/create", body, level="L0",
sub_mch_id="PLF-SUB-001")
# one-shot:
result = client.execute("POST", "/gateway/order/create", body, level="L0",
sub_mch_id="PLF-SUB-001")
```

The SDK writes `x-wop-sub-mch-id` before signing and includes it in the `x-wop-sign`
signedHeaders. Leading/trailing whitespace is trimmed; the value must be printable ASCII
(0x20–0x7E), contain no internal whitespace, and be at most 128 characters — violations
raise `ConfigurationError`. Omitting it (or passing blank) keeps the app's own identity:
the header is absent and the header set/signature are byte-identical to earlier versions
(AC-20). Passing the header via `extra_headers` is equivalent to the parameter; supplying
both is rejected. The header takes effect only when the gateway sub-merchant gray gate is
open for the app and the app is an ISV app (`app_type=20`).

## Key Preparation

Keys are passed as strings (PEM or single-line Base64) and parsed inside the SDK
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,24 @@ else:
print(result.reason) # 验签/解密失败对外模糊(I7),格式/完整性/一致性类明确
```

## ISV 子商户身份(ISV D-13)

代子商户调用业务 API 时,按请求传 `sub_mch_id`(值 = 子商户 `plf_co_id`):

```python
draft = client.build_request("POST", "/gateway/order/create", body, level="L0",
sub_mch_id="PLF-SUB-001")
# 一站式调用:
result = client.execute("POST", "/gateway/order/create", body, level="L0",
sub_mch_id="PLF-SUB-001")
```

SDK 在签名前写入 `x-wop-sub-mch-id`,并自动纳入 `x-wop-sign` 的 signedHeaders。
首尾空白 trim 后发送;仅接受可打印 ASCII(0x20–0x7E)、无内部空白、≤128 字符,
违规抛 `ConfigurationError`。不传或纯空白 = 应用自身身份,头缺席,请求头集合与签名
与旧版逐字节一致(AC-20)。`extra_headers` 携带该头等价于参数;双来源同传构造即拒。
该头仅在网关子商户灰度放行且应用为 ISV 应用(`app_type=20`)时生效。

## 密钥准备

密钥入参为字符串(PEM 或 Base64 单行),SDK 内部解析(D12 分发契约):
Expand Down
67 changes: 64 additions & 3 deletions src/wop_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
_LEVELS = ("L0", "L2")
_DEK_PREFIX = "L2;dek="
_HEADER_REQUEST_ID = "x-wop-request-id"
_HEADER_SUB_MCH_ID = "x-wop-sub-mch-id"

# 附录 I/I3 日志义务:出向构造点 INFO 打印最终透传头值(非敏感,豁免脱敏)
_OUT_LOG = logging.getLogger("wop_sdk.outbound")
Expand Down Expand Up @@ -84,6 +85,37 @@ def resolve_request_id(raw: Optional[str]) -> Optional[str]:
return trimmed


def resolve_sub_mch_id(raw: Optional[str]) -> Optional[str]:
"""ISV D-13 子商户身份头 x-wop-sub-mch-id 校验(构造即拒,configuration 类)。

1. trim 前按**原值**逐字符扫描可打印 ASCII(0x20..0x7E)——控制字符(CR/LF/NUL/DEL 等)
防头注入,非 ASCII 在 HTTP 头编码下不可靠;
2. trim(G2 TrimAll 同集)后为空 → 视为未设置(返回 None,头缺席 = 应用自身身份,AC-20);
3. trim 后含内部空格 → 拒(网关 canonical 的 trimall 会折叠内部空白,而身份查询只做
trim,内部空白破坏签名与身份一一对应);
4. trim 后长度 > 128 字符 → 拒(ASCII 下字符数 = 字节数)。
返回 trim 后上行值;None = 未设置。
"""
if raw is None:
return None
if not isinstance(raw, str):
# J2 构造即拒:非 str(如数值型 plf_co_id)不得被 str() 归一后静默入签
raise ConfigurationError(
"subMchId 须为字符串(子商户 plf_co_id),实际 %s" % type(raw).__name__
)
for ch in raw:
if ord(ch) < 0x20 or ord(ch) > 0x7E:
raise ConfigurationError(f"subMchId 须为可打印 ASCII(防头注入/签名歧义): {ord(ch)}")
trimmed = raw.strip(_TRIM_CHARS)
if not trimmed:
return None
if " " in trimmed:
raise ConfigurationError("subMchId 不能包含内部空白")
if len(trimmed) > 128:
raise ConfigurationError(f"subMchId 长度不能超过 128(实际 {len(trimmed)})")
return trimmed


def _now_ms() -> int:
"""毫秒时间戳(F9);独立函数便于测试冻结。"""
return int(time.time() * 1000)
Expand Down Expand Up @@ -233,6 +265,7 @@ def build_request(
timestamp_ms: Optional[int] = None,
nonce: Optional[str] = None,
request_id: Optional[str] = None,
sub_mch_id: Optional[str] = None,
) -> RequestDraft:
"""构造请求(F9):协议头组装 → L2 可选封装 → canonicalRequest → 签名。

Expand All @@ -244,6 +277,10 @@ def build_request(
(头恒存在),显式传值 trim 后原值上行,控制字符(trim 前扫描)与超长
(trim 后 UTF-8 字节 > 128)构造即拒。extra_headers 携带该头等价
request_id 参数(同解析链、恒不入签);双来源同传构造即拒(configuration)。
sub_mch_id 为 ISV 子商户身份(D-13,值 = 子商户 plf_co_id):签名前写入
x-wop-sub-mch-id 并自动纳入 signedHeaders;未传/空白 = 应用自身身份(头缺席,
与旧版逐字节一致,AC-20)。须为可打印 ASCII、无内部空白、trim 后 ≤128 字符,
违规构造即拒。extra_headers 携带该头等价 sub_mch_id 参数,双来源同传即拒。
"""
if level not in _LEVELS:
raise ConfigurationError("level 必须为 L0 或 L2,实际 %r" % level)
Expand All @@ -265,6 +302,25 @@ def build_request(
resolved_request_id = resolve_request_id(
request_id if request_id is not None else header_request_id
)
# ISV D-13:subMchId 同解析链(extra_headers 等价参数;双来源同传 = 歧义即拒)
header_sub_mch_id = next(
(
value
for name, value in (extra_headers or {}).items()
if name.strip().lower() == _HEADER_SUB_MCH_ID
),
None,
)
# 两侧各按 J2 解析(trim 后空 = 未设置):只有两侧都解析出值才构成双来源歧义
param_resolved = resolve_sub_mch_id(sub_mch_id)
header_resolved = resolve_sub_mch_id(header_sub_mch_id)
if param_resolved is not None and header_resolved is not None:
raise ConfigurationError(
"sub_mch_id 参数与 extra_headers['x-wop-sub-mch-id'] 同时显式提供,请仅保留一处"
)
resolved_sub_mch_id = (
param_resolved if param_resolved is not None else header_resolved
)
safe_method = method.strip().upper()
# spec:interop-v1 随机流消费顺序:nonce 池最前,先于 seal_l2 的 CEK/IV
if not nonce:
Expand All @@ -283,6 +339,9 @@ def build_request(
"x-wop-timestamp": str(_now_ms() if timestamp_ms is None else int(timestamp_ms)),
"x-wop-nonce": nonce,
}
# ISV D-13:签名前写入,signedHeaders 自动包含;缺席时头集合与旧行为完全一致
if resolved_sub_mch_id is not None:
headers[_HEADER_SUB_MCH_ID] = resolved_sub_mch_id
if wire is not None:
# D2:有 body 必产 digest;I1:digest 必入 signedHeaders(下方签名集合即全部头)
headers["x-wop-content-digest"] = build_digest_header(self._suite, wire)
Expand All @@ -292,9 +351,9 @@ def build_request(
app_headers: Dict[str, str] = {}
for name, value in (extra_headers or {}).items():
low = name.strip().lower()
if low == _HEADER_REQUEST_ID:
# 恒不入签(附录 I):值已在解析链消费;若并入 headers 会被签名后
# 覆盖 → 签名集合含旧值、线上是新值,网关验签必败且 SDK 零报错
if low in (_HEADER_REQUEST_ID, _HEADER_SUB_MCH_ID):
# request_id 恒不入签(附录 I);sub_mch_id 已在签名前由解析链写入。
# 若此处再并入会覆盖已验证值 → 签名/身份不一致
continue
if low.startswith("x-wop-"):
headers[low] = str(value).strip()
Expand Down Expand Up @@ -364,6 +423,7 @@ def execute(
*,
level: str = "L0",
request_id: Optional[str] = None,
sub_mch_id: Optional[str] = None,
) -> VerifyResult:
"""一站式:签名 → 发送 → 非 2xx 拦截 → 验签解密(§2 execute 语义)。"""
if self._transport is None or self._sdk_config is None:
Expand All @@ -376,6 +436,7 @@ def execute(
level=level,
expired_seconds=self._sdk_config.expired_seconds,
request_id=request_id,
sub_mch_id=sub_mch_id,
)
from .transports import send_draft

Expand Down
Loading
Loading