diff --git a/README.en.md b/README.en.md index faf65fe..1dea413 100644 --- a/README.en.md +++ b/README.en.md @@ -52,6 +52,31 @@ 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. **Only leading/trailing spaces are trimmed; any control character is +rejected even at the ends**; the value must be printable ASCII (0x20–0x7E), contain no +internal whitespace, and be at most 128 characters — violations raise `ConfigurationError`; +non-string input also raises `ConfigurationError` (never silently coerced). 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 +applies only to ISV apps (`app_type=20`); **prerequisite**: the gateway must already +deploy D-13 (conditional signing) — otherwise the header passes through as unknown and +the request runs as the app's own identity, silently losing the sub-merchant identity. + ## Key Preparation Keys are passed as strings (PEM or single-line Base64) and parsed inside the SDK diff --git a/README.md b/README.md index b9581db..d37622b 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,26 @@ 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`;非字符串入参同样抛 `ConfigurationError` +(不会静默强转)。不传或纯空白 = 应用自身身份,头缺席,请求头集合与签名与旧版逐字节一致 +(AC-20)。`extra_headers` 携带该头等价于参数;双来源同传构造即拒。该头仅对 ISV 应用 +(`app_type=20`)生效;**前置**:网关须已部署 D-13(条件入签),未部署时该头按未知头透传、 +请求以应用自身身份执行,子商户身份会静默丢失。 + ## 密钥准备 密钥入参为字符串(PEM 或 Base64 单行),SDK 内部解析(D12 分发契约): diff --git a/src/wop_sdk/client.py b/src/wop_sdk/client.py index d421098..89f7bec 100644 --- a/src/wop_sdk/client.py +++ b/src/wop_sdk/client.py @@ -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") @@ -84,6 +85,35 @@ 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 = 未设置。非 str 输入一律 configuration(不抛裸 TypeError)。 + """ + if raw is None: + return None + if not isinstance(raw, str): + # 防裸 TypeError;也防 str() 强转把 None 变成 "None" 静默入签 + raise ConfigurationError(f"subMchId 须为字符串,实际 {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) @@ -233,6 +263,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 → 签名。 @@ -244,6 +275,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) @@ -265,6 +300,22 @@ 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, + ) + if header_sub_mch_id is not None and sub_mch_id is not None: + raise ConfigurationError( + "sub_mch_id 参数与 extra_headers['x-wop-sub-mch-id'] 同时显式提供,请仅保留一处" + ) + resolved_sub_mch_id = resolve_sub_mch_id( + sub_mch_id if sub_mch_id is not None else header_sub_mch_id + ) safe_method = method.strip().upper() # spec:interop-v1 随机流消费顺序:nonce 池最前,先于 seal_l2 的 CEK/IV if not nonce: @@ -283,6 +334,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) @@ -292,9 +346,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() @@ -364,6 +418,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: @@ -376,6 +431,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 diff --git a/tests/test_config.py b/tests/test_config.py index dbd3bf0..8054947 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -277,6 +277,22 @@ def send(self, method, url, headers, body): assert result.ok assert draft_holder["url"] == "https://gw.example.com/gateway/gateway/order/create" + def test_execute_carries_sub_mch_id(self, valid_sdk_config): + # 一站式入口透传子商户身份:发出请求头含 x-wop-sub-mch-id + client = WopClient.from_config(valid_sdk_config, csprng=lambda n: b"Z" * n) + seen = {} + + class RecordingTransport: + def send(self, method, url, headers, body): + seen["headers"] = dict(headers) + draft = client.build_request("POST", PATH, b'{"code":0}') + return HttpResponse(200, draft.headers, draft.wire_body) + + client._transport = RecordingTransport() + result = client.execute("POST", PATH, b'{"code":0}', sub_mch_id="PLF-SUB-001") + assert result.ok + assert seen["headers"].get("x-wop-sub-mch-id") == "PLF-SUB-001" + def test_execute_non_2xx_raises_gateway_error(self, valid_sdk_config): client = WopClient.from_config(valid_sdk_config) diff --git a/tests/test_submchid.py b/tests/test_submchid.py new file mode 100644 index 0000000..b83e90c --- /dev/null +++ b/tests/test_submchid.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +"""ISV D-13:子商户身份头 x-wop-sub-mch-id 入签与 AC-20 零回归。""" +import pytest + +import wop_sdk.client as client_mod +from wop_sdk.canonical import build_canonical, canonical_headers +from wop_sdk.client import WopClient, WopConfig +from wop_sdk.encoding import b64url_decode +from wop_sdk.errors import ConfigurationError +from wop_sdk.keys import load_rsa_public_key +from wop_sdk.signature import verify + +RSA_REQ = "WOP-RSA3072-SHA256" +PATH = "/gateway/order.create" + + +@pytest.fixture(scope="module") +def vec_keys(vectors): + return vectors["keys"] + + +@pytest.fixture(scope="module") +def rsa_client(vec_keys): + return WopClient( + WopConfig( + app_key="app_10012481831", + suite=RSA_REQ, + merchant_private_key=vec_keys["rsa3072"]["privatePkcs8B64"], + platform_public_key=vec_keys["rsa3072"]["publicSpkiB64"], + ), + csprng=lambda n: b"\x5a" * n, + ) + + +def _assert_signature_valid(client, draft, pub_b64): + suite_part, rest = draft.headers["x-wop-sign"].split(" ", 1) + version, expired, names, sig = rest.split("/") + assert suite_part == RSA_REQ + signed_map = {n: draft.headers[n] for n in names.split(";")} + canonical = build_canonical( + f"{version}/{expired}", draft.method, draft.path, "", canonical_headers(signed_map) + ) + verify( + client.suite, + load_rsa_public_key(pub_b64), + canonical.encode("utf-8"), + b64url_decode(sig), + ) + + +class TestSubMchIdSigned: + def test_signed_and_signature_valid(self, rsa_client, vec_keys): + cases = [ + (b'{"k":1}', "L0", ["x-wop-appkey", "x-wop-content-digest", "x-wop-nonce", + "x-wop-sub-mch-id", "x-wop-timestamp"]), + (None, "L0", ["x-wop-appkey", "x-wop-nonce", "x-wop-sub-mch-id", + "x-wop-timestamp"]), + (b'{"amount":1}', "L2", ["x-wop-appkey", "x-wop-content-digest", "x-wop-encrypt", + "x-wop-nonce", "x-wop-sub-mch-id", "x-wop-timestamp"]), + ] + for body, level, want in cases: + draft = rsa_client.build_request( + "POST", PATH, body, level=level, timestamp_ms=1774340000000, nonce="n", + request_id="req-001", sub_mch_id="PLF-SUB-001", + ) + assert draft.headers["x-wop-sub-mch-id"] == "PLF-SUB-001" + signed_names = draft.headers["x-wop-sign"].split(" ", 1)[1].split("/")[2].split(";") + assert signed_names == want + assert "x-wop-request-id" not in signed_names + _assert_signature_valid(rsa_client, draft, vec_keys["rsa3072"]["publicSpkiB64"]) + + def test_trimmed_upstream(self, rsa_client): + draft = rsa_client.build_request("GET", PATH, sub_mch_id=" PLF-SUB-001 ") + assert draft.headers["x-wop-sub-mch-id"] == "PLF-SUB-001" + + def test_extra_headers_equivalent_and_signed(self, rsa_client): + draft = rsa_client.build_request( + "GET", PATH, extra_headers={"X-Wop-Sub-Mch-Id": " PLF-SUB-001 "} + ) + assert draft.headers["x-wop-sub-mch-id"] == "PLF-SUB-001" + signed_names = draft.headers["x-wop-sign"].split(" ", 1)[1].split("/")[2].split(";") + assert "x-wop-sub-mch-id" in signed_names + + def test_both_sources_rejected(self, rsa_client): + with pytest.raises(ConfigurationError, match="x-wop-sub-mch-id"): + rsa_client.build_request( + "GET", PATH, sub_mch_id="p1", + extra_headers={"x-wop-sub-mch-id": "p2"}, + ) + + +class TestSubMchIdInbound: + def test_inbound_ignores_unsigned_sub_mch_header(self, rsa_client): + # 附录 J/J3:入向(响应/回调)不消费 x-wop-sub-mch-id——额外携带未入签的该头仍通过 + draft = rsa_client.build_request("POST", PATH, b'{"code":0}') + headers = dict(draft.headers) + headers["x-wop-sub-mch-id"] = "PLF-SUB-001" # 签名完成后追加,不在 signedHeaders + result = rsa_client.verify_response(headers, draft.wire_body, PATH) + assert result.ok, result.reason + + +class TestSubMchIdZeroRegression: # spec:AC-20 + def test_absent_or_blank_behaves_as_before(self, rsa_client, monkeypatch): + monkeypatch.setattr(client_mod, "request_id_generator", lambda: "fixed" + "0" * 27) + common = dict(timestamp_ms=1774340000000, nonce="n1") + baseline = rsa_client.build_request("POST", PATH, b'{"k":1}', **common) + for blank in (None, "", " "): + draft = rsa_client.build_request("POST", PATH, b'{"k":1}', sub_mch_id=blank, **common) + assert "x-wop-sub-mch-id" not in draft.headers + assert draft.headers == baseline.headers + + +class TestSubMchIdValidation: + @pytest.mark.parametrize( + "bad", ["a\nb", "a\rb", "a\x00b", "a\tb", "\tsub", "sub\t", "a\x7fb"] + ) + def test_control_chars_rejected_pre_trim(self, rsa_client, bad): + with pytest.raises(ConfigurationError, match="可打印 ASCII"): + rsa_client.build_request("GET", PATH, sub_mch_id=bad) + + def test_non_ascii_rejected_without_echo(self, rsa_client): + with pytest.raises(ConfigurationError, match="可打印 ASCII") as exc: + rsa_client.build_request("GET", PATH, sub_mch_id="PLF中文") + assert "中文" not in str(exc.value) + + @pytest.mark.parametrize("bad", ["PLF SUB", "PLF SUB"]) + def test_internal_space_rejected(self, rsa_client, bad): + with pytest.raises(ConfigurationError, match="内部空白"): + rsa_client.build_request("GET", PATH, sub_mch_id=bad) + + def test_length_boundary(self, rsa_client): + ok = rsa_client.build_request("GET", PATH, sub_mch_id="x" * 128) + assert ok.headers["x-wop-sub-mch-id"] == "x" * 128 + with pytest.raises(ConfigurationError, match="实际 129"): + rsa_client.build_request("GET", PATH, sub_mch_id="x" * 129) + + def test_printable_ascii_boundary(self, rsa_client): + draft = rsa_client.build_request("GET", PATH, sub_mch_id="!~") + assert draft.headers["x-wop-sub-mch-id"] == "!~" + + @pytest.mark.parametrize("bad", [12345, 12.5, b"PLF-SUB-001", ["x"]]) + def test_non_str_param_rejected_as_configuration(self, rsa_client, bad): + # 参数路径原值进校验链:非 str 一律 configuration,不抛裸 TypeError + with pytest.raises(ConfigurationError, match="须为字符串"): + rsa_client.build_request("GET", PATH, sub_mch_id=bad) + + def test_extra_headers_non_str_rejected_as_configuration(self, rsa_client): + # 修复前 str(123) 会强转后入签;现原值进同一校验链 + with pytest.raises(ConfigurationError, match="须为字符串"): + rsa_client.build_request("GET", PATH, extra_headers={"x-wop-sub-mch-id": 123}) + + def test_extra_headers_none_means_absent(self, rsa_client, monkeypatch): + # 修复前 str(None)="None" 会静默入签错误身份;现视为未设置,头缺席 + monkeypatch.setattr(client_mod, "request_id_generator", lambda: "fixed" + "0" * 27) + common = dict(timestamp_ms=1774340000000, nonce="n1") + baseline = rsa_client.build_request("GET", PATH, **common) + draft = rsa_client.build_request( + "GET", PATH, extra_headers={"x-wop-sub-mch-id": None}, **common + ) + assert "x-wop-sub-mch-id" not in draft.headers + assert draft.headers == baseline.headers