|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * **#26710 acceptance (ADR-0143 Acceptance, `signed` line)**, as the |
| 5 | + * maintainer ruled on 2026-10-31: the local end-to-end run counts as the |
| 6 | + * acceptance, with no live sandbox call owed. |
| 7 | + * |
| 8 | + * A declarative `provider: 'openapi'` instance over an Alipay v3-shaped |
| 9 | + * document (JSON; the `alipay.trade.query` operation as the vendor's document |
| 10 | + * declares it) with `auth: { type: 'signed', scheme: 'alipay-v3', … }` |
| 11 | + * dispatches through a real boot (LiteKernel + AutomationServicePlugin + |
| 12 | + * ConnectorOpenApiPlugin). A local stand-in for the Alipay gateway (the |
| 13 | + * provider's `fetchImpl`) checks the request's `ALIPAY-SHA256withRSA` |
| 14 | + * signature with the app's public key and signs its answer with its own key, |
| 15 | + * as Alipay does. Two key pairs, generated here, keep the roles apart: the app |
| 16 | + * pair signs requests, the "Alipay" pair signs responses. |
| 17 | + * |
| 18 | + * 1. A signed request is accepted by the gateway, and the gateway's signed |
| 19 | + * response is verified and returned, through a flow `connector_action`. |
| 20 | + * 2. A response altered after the gateway signed it fails the dispatch, and |
| 21 | + * its body never reaches the flow; so does an unsigned 2xx. |
| 22 | + * 3. The private key appears in no request and no connector descriptor. |
| 23 | + */ |
| 24 | + |
| 25 | +import { createSign, createVerify, generateKeyPairSync, randomUUID, type KeyObject } from 'node:crypto'; |
| 26 | +import { describe, expect, it } from 'vitest'; |
| 27 | +import { LiteKernel } from '@objectstack/core'; |
| 28 | +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; |
| 29 | +import { ConnectorOpenApiPlugin } from './connector-openapi-plugin.js'; |
| 30 | + |
| 31 | +/** The `alipay.trade.query` operation as Alipay's v3 OpenAPI document declares it, schemas trimmed. */ |
| 32 | +const alipayV3Document = { |
| 33 | + openapi: '3.0.3', |
| 34 | + info: { title: '支付宝开放平台API', version: '2026-09-23' }, |
| 35 | + servers: [{ url: 'https://openapi.alipay.com' }], |
| 36 | + paths: { |
| 37 | + '/v3/alipay/trade/query': { |
| 38 | + post: { |
| 39 | + operationId: 'alipay.trade.query', |
| 40 | + summary: '统一收单交易查询', |
| 41 | + requestBody: { |
| 42 | + required: false, |
| 43 | + content: { 'application/json': { schema: { type: 'object', properties: { out_trade_no: { type: 'string' }, trade_no: { type: 'string' } } } } }, |
| 44 | + }, |
| 45 | + responses: { '200': { description: 'common response' } }, |
| 46 | + }, |
| 47 | + }, |
| 48 | + }, |
| 49 | +}; |
| 50 | + |
| 51 | +/** A key pair as Alipay's console hands them out: bare base64, PKCS#8 and SPKI. */ |
| 52 | +function keyPair() { |
| 53 | + const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); |
| 54 | + return { |
| 55 | + privateKey, |
| 56 | + publicKey, |
| 57 | + privateText: privateKey.export({ format: 'der', type: 'pkcs8' }).toString('base64'), |
| 58 | + publicText: publicKey.export({ format: 'der', type: 'spki' }).toString('base64'), |
| 59 | + }; |
| 60 | +} |
| 61 | +const app = keyPair(); |
| 62 | +const alipay = keyPair(); |
| 63 | + |
| 64 | +const TRADE = '{"trade_no":"2013112011001004330000121536","out_trade_no":"20150320010101001","trade_status":"TRADE_SUCCESS"}'; |
| 65 | + |
| 66 | +type Mode = 'signed' | 'tampered' | 'unsigned'; |
| 67 | +type Seen = { url: string; headers: Record<string, string>; requestVerified: boolean }; |
| 68 | + |
| 69 | +/** The local Alipay gateway: verifies the request signature, answers signed (or, by `mode`, not). */ |
| 70 | +function alipayGateway(appPublicKey: KeyObject, alipayPrivateKey: KeyObject, mode: { current: Mode }) { |
| 71 | + const seen: Seen[] = []; |
| 72 | + const impl = (async (url: string, init: RequestInit) => { |
| 73 | + const headers = Object.fromEntries(Object.entries(init.headers as Record<string, string>).map(([k, v]) => [k.toLowerCase(), v])); |
| 74 | + const target = new URL(url); |
| 75 | + const auth = /^ALIPAY-SHA256withRSA (app_id=[^,]+,nonce=[^,]+,timestamp=\d+),sign=(.+)$/.exec(headers.authorization ?? ''); |
| 76 | + const content = auth ? `${auth[1]}\n${init.method}\n${target.pathname}${target.search}\n${(init.body as string | undefined) ?? ''}\n` : ''; |
| 77 | + const requestVerified = auth !== null && createVerify('RSA-SHA256').update(content, 'utf8').verify(appPublicKey, auth[2]!, 'base64'); |
| 78 | + seen.push({ url, headers, requestVerified }); |
| 79 | + if (!requestVerified) { |
| 80 | + return new Response('{"code":"invalid-signature","message":"验签出错"}', { status: 401, headers: { 'content-type': 'application/json' } }); |
| 81 | + } |
| 82 | + const timestamp = String(Date.now()); |
| 83 | + const nonce = randomUUID(); |
| 84 | + const signature = createSign('RSA-SHA256').update(`${timestamp}\n${nonce}\n${TRADE}\n`, 'utf8').sign(alipayPrivateKey, 'base64'); |
| 85 | + const body = mode.current === 'tampered' ? TRADE.replace('TRADE_SUCCESS', 'TRADE_CLOSED') : TRADE; |
| 86 | + const signedHeaders = mode.current === 'unsigned' |
| 87 | + ? {} |
| 88 | + : { 'alipay-timestamp': timestamp, 'alipay-nonce': nonce, 'alipay-signature': signature }; |
| 89 | + return new Response(body, { status: 200, headers: { 'content-type': 'application/json', ...signedHeaders } }); |
| 90 | + }) as unknown as typeof fetch; |
| 91 | + return { impl, seen }; |
| 92 | +} |
| 93 | + |
| 94 | +async function boot(mode: { current: Mode }) { |
| 95 | + const gateway = alipayGateway(app.publicKey, alipay.privateKey, mode); |
| 96 | + const declared = [{ |
| 97 | + name: 'alipay_pay', |
| 98 | + label: 'Alipay', |
| 99 | + type: 'api', |
| 100 | + provider: 'openapi', |
| 101 | + providerConfig: { spec: alipayV3Document }, |
| 102 | + auth: { |
| 103 | + type: 'signed', |
| 104 | + scheme: 'alipay-v3', |
| 105 | + keyId: '2021000000000000', |
| 106 | + credentialRef: 'ALIPAY_APP_PRIVATE_KEY_26710', |
| 107 | + vendorPublicKeyRef: 'ALIPAY_PUBLIC_KEY_26710', |
| 108 | + }, |
| 109 | + }]; |
| 110 | + const references: Record<string, string> = { ALIPAY_APP_PRIVATE_KEY_26710: app.privateText, ALIPAY_PUBLIC_KEY_26710: alipay.publicText }; |
| 111 | + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); |
| 112 | + kernel.use(new AutomationServicePlugin({ credentialResolver: (ref) => references[ref] })); |
| 113 | + kernel.use(new ConnectorOpenApiPlugin({ fetchImpl: gateway.impl })); |
| 114 | + kernel.use({ |
| 115 | + name: 'test.metadata', |
| 116 | + type: 'standard', |
| 117 | + version: '1.0.0', |
| 118 | + dependencies: [], |
| 119 | + async init(ctx: { registerService(name: string, service: unknown): void }) { |
| 120 | + ctx.registerService('objectql', { registry: { listItems: (t: string) => (t === 'connector' ? declared : []) } }); |
| 121 | + }, |
| 122 | + async start() {}, |
| 123 | + } as never); |
| 124 | + await kernel.bootstrap(); |
| 125 | + return { engine: kernel.getService<AutomationEngine>('automation'), seen: gateway.seen, kernel }; |
| 126 | +} |
| 127 | + |
| 128 | +async function queryTradeByFlow(engine: AutomationEngine, flow: string) { |
| 129 | + engine.registerFlow(flow, { |
| 130 | + name: flow, label: flow, type: 'autolaunched', |
| 131 | + nodes: [ |
| 132 | + { id: 'start', type: 'start', label: 'Start' }, |
| 133 | + { |
| 134 | + id: 'query', type: 'connector_action', label: 'Query trade', |
| 135 | + connectorConfig: { connectorId: 'alipay_pay', actionId: 'alipay.trade.query', input: { body: { out_trade_no: '20150320010101001' } } }, |
| 136 | + }, |
| 137 | + { id: 'end', type: 'end', label: 'End' }, |
| 138 | + ], |
| 139 | + edges: [{ id: 'e1', source: 'start', target: 'query' }, { id: 'e2', source: 'query', target: 'end' }], |
| 140 | + } as never); |
| 141 | + return engine.execute(flow, {} as never); |
| 142 | +} |
| 143 | + |
| 144 | +describe('#26710 acceptance — an openapi instance over the Alipay v3 document, signed and verified end to end', () => { |
| 145 | + it('1. the gateway accepts the signed request, and its signed response is verified and returned', async () => { |
| 146 | + const { engine, seen, kernel } = await boot({ current: 'signed' }); |
| 147 | + try { |
| 148 | + expect(engine.getConnectorDegradedReason('alipay_pay')).toBeUndefined(); |
| 149 | + const result = await queryTradeByFlow(engine, 'query_trade'); |
| 150 | + expect(result.success, result.error).toBe(true); |
| 151 | + expect(seen).toHaveLength(1); |
| 152 | + expect(seen[0]!.requestVerified).toBe(true); |
| 153 | + expect(seen[0]!.url).toBe('https://openapi.alipay.com/v3/alipay/trade/query'); |
| 154 | + expect(seen[0]!.headers.authorization).toMatch(/^ALIPAY-SHA256withRSA app_id=2021000000000000,nonce=[0-9a-f-]{36},timestamp=\d{13},sign=/); |
| 155 | + |
| 156 | + const query = engine.resolveConnectorAction('alipay_pay', 'alipay.trade.query')!; |
| 157 | + expect(await query({ body: { out_trade_no: '20150320010101001' } }, {} as never)).toEqual({ |
| 158 | + status: 200, ok: true, body: JSON.parse(TRADE), |
| 159 | + }); |
| 160 | + expect(seen[1]!.requestVerified).toBe(true); |
| 161 | + // Every call is signed afresh. |
| 162 | + expect(seen[1]!.headers.authorization).not.toBe(seen[0]!.headers.authorization); |
| 163 | + } finally { |
| 164 | + await kernel.shutdown().catch(() => {}); |
| 165 | + } |
| 166 | + }); |
| 167 | + |
| 168 | + it('2. a response altered after Alipay signed it, or an unsigned 2xx, fails the dispatch and its body never reaches the flow', async () => { |
| 169 | + const mode: { current: Mode } = { current: 'tampered' }; |
| 170 | + const { engine, seen, kernel } = await boot(mode); |
| 171 | + try { |
| 172 | + const tampered = await queryTradeByFlow(engine, 'query_tampered'); |
| 173 | + expect(tampered.success).toBe(false); |
| 174 | + expect(tampered.error).toContain('does not verify against the public key its vendorPublicKeyRef names'); |
| 175 | + expect(JSON.stringify(tampered)).not.toContain('TRADE_CLOSED'); |
| 176 | + expect(seen[0]!.requestVerified).toBe(true); |
| 177 | + |
| 178 | + mode.current = 'unsigned'; |
| 179 | + const unsigned = await queryTradeByFlow(engine, 'query_unsigned'); |
| 180 | + expect(unsigned.success).toBe(false); |
| 181 | + expect(unsigned.error).toContain('carries no complete Alipay signature'); |
| 182 | + expect(JSON.stringify(unsigned)).not.toContain('TRADE_SUCCESS'); |
| 183 | + |
| 184 | + // CONTROL: the same instance, answered signed, succeeds. |
| 185 | + mode.current = 'signed'; |
| 186 | + expect((await queryTradeByFlow(engine, 'query_signed')).success).toBe(true); |
| 187 | + } finally { |
| 188 | + await kernel.shutdown().catch(() => {}); |
| 189 | + } |
| 190 | + }); |
| 191 | + |
| 192 | + it('3. the private key is in no request and no connector descriptor', async () => { |
| 193 | + const { engine, seen, kernel } = await boot({ current: 'signed' }); |
| 194 | + try { |
| 195 | + await queryTradeByFlow(engine, 'query_trade'); |
| 196 | + const fragment = app.privateText.slice(64, 160); |
| 197 | + expect(JSON.stringify(seen)).not.toContain(fragment); |
| 198 | + expect(JSON.stringify(engine.getConnectorDescriptors())).not.toContain(fragment); |
| 199 | + } finally { |
| 200 | + await kernel.shutdown().catch(() => {}); |
| 201 | + } |
| 202 | + }); |
| 203 | +}); |
0 commit comments