Skip to content

Commit 22d14be

Browse files
committed
feat(service-automation): the alipay-v3 signer and response verifier, with vectors two official SDKs agree on
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cxRP1AqTeP2PWAhwGK
1 parent 29ded81 commit 22d14be

14 files changed

Lines changed: 850 additions & 30 deletions

‎packages/services/service-automation/src/connector-credential-door.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
*
2828
* The values below are obvious dummies.
2929
*/
30+
import { readFileSync } from 'node:fs';
3031
import { afterEach, describe, expect, it, vi } from 'vitest';
3132
import { LiteKernel } from '@objectstack/core';
3233
import { ObjectQL } from '@objectstack/objectql';
@@ -289,6 +290,57 @@ describe('[#27237] a missing credential degrades its instance; setting it materi
289290
});
290291
});
291292

293+
// ADR-0143 D2.3 — an `alipay-v3` instance names two references: the private
294+
// key it signs with and the Alipay public key it verifies responses with. The
295+
// door lists both against the instance, and setting or replacing either one
296+
// re-materializes it.
297+
describe('[#26710] a signed instance names its vendor public key as a second reference', () => {
298+
const vectors = new URL('../test-vectors/alipay-v3/', import.meta.url);
299+
const PRIVATE_KEY = readFileSync(new URL('PLACEHOLDER-test-only-rsa2048-private-key.pkcs8.b64', vectors), 'ascii').trim();
300+
const PUBLIC_KEY = readFileSync(new URL('PLACEHOLDER-test-only-rsa2048-public-key.spki.b64', vectors), 'ascii').trim();
301+
const alipay = {
302+
name: 'alipay_pay',
303+
label: 'Alipay',
304+
type: 'api',
305+
provider: 'fake',
306+
providerConfig: {},
307+
auth: { type: 'signed', scheme: 'alipay-v3', keyId: '2021000000000000', credentialRef: 'ALIPAY_APP_PRIVATE_KEY', vendorPublicKeyRef: 'ALIPAY_PUBLIC_KEY' },
308+
_packageId: 'com.example.alipay',
309+
};
310+
311+
it('lists both references; the public key missing degrades the instance, and setting or replacing it materializes it', async () => {
312+
const materialized: ConnectorProviderContext[] = [];
313+
const signing: ConnectorProviderFactory = (ctx) => {
314+
materialized.push(ctx);
315+
return {
316+
def: { name: ctx.name, label: ctx.label, type: 'api', authentication: { type: 'none' }, actions: [] } as unknown as Connector,
317+
handlers: {},
318+
requestSignerApplied: true,
319+
};
320+
};
321+
const provider = { ...fakeProvider(), factory: signing };
322+
const { engine } = await boot([alipay], {
323+
provider,
324+
credentialResolver: (ref) => (ref === 'ALIPAY_APP_PRIVATE_KEY' ? PRIVATE_KEY : undefined),
325+
});
326+
expect(materialized).toHaveLength(0);
327+
expect(engine.getConnectorDegradedReason('alipay_pay')).toContain("credential 'ALIPAY_PUBLIC_KEY'");
328+
const listed = Object.fromEntries((await engine.listConnectorCredentialRefs()).map((e) => [e.ref, e]));
329+
expect(listed.ALIPAY_PUBLIC_KEY).toMatchObject({ status: 'missing', declared: true });
330+
expect(listed.ALIPAY_PUBLIC_KEY!.connectors).toEqual([expect.objectContaining({ name: 'alipay_pay', packageId: 'com.example.alipay' })]);
331+
expect(listed.ALIPAY_APP_PRIVATE_KEY!.connectors).toEqual([expect.objectContaining({ name: 'alipay_pay' })]);
332+
333+
await engine.setConnectorCredential({ ref: 'ALIPAY_PUBLIC_KEY', value: PUBLIC_KEY, context: ADMIN });
334+
expect(engine.getConnectorDegradedReason('alipay_pay')).toBeUndefined();
335+
expect(materialized).toHaveLength(1);
336+
expect(materialized[0]!.requestSigner?.scheme).toBe('alipay-v3');
337+
338+
// A replaced public key is a new revision: the instance re-materializes.
339+
await engine.setConnectorCredential({ ref: 'ALIPAY_PUBLIC_KEY', value: `\n${PUBLIC_KEY}\n`, context: ADMIN });
340+
expect(materialized).toHaveLength(2);
341+
});
342+
});
343+
292344
describe('[#27237] the value appears nowhere it is not used', () => {
293345
it('not in a log record, the listing, the connector descriptors or an engine read of the row', async () => {
294346
const out = captureOutput();

‎packages/services/service-automation/src/connector-materialization.test.ts‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
// Boot fails loudly for unknown provider / name conflict / factory failure; a
1010
// credentialRef nothing resolves degrades the instance naming it (#27237).
1111

12-
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
12+
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
1313
import { tmpdir } from 'node:os';
1414
import * as path from 'node:path';
1515
import { describe, it, expect, afterAll, afterEach, vi } from 'vitest';
@@ -30,6 +30,7 @@ import {
3030
} from './plugin.js';
3131
import type { AutomationEngine } from './engine.js';
3232
import { computeAliyunAcs3Signature } from './request-signing/aliyun-acs3-hmac-sha256.js';
33+
import { computeAlipayV3Signature, readAlipayPrivateKey } from './request-signing/alipay-v3.js';
3334

3435
const flush = () => new Promise<void>((r) => setTimeout(r, 0));
3536

@@ -1181,6 +1182,63 @@ describe('ADR-0143 D2.3 — a `signed` instance is handed a request signer, neve
11811182
await kernel.shutdown();
11821183
});
11831184

1185+
// `alipay-v3` names the Alipay public key beside the private key; it
1186+
// resolves through the same chain, and a response is never accepted
1187+
// unverified for want of it.
1188+
describe('alipay-v3: the vendor public key is a second reference', () => {
1189+
const vectors = new URL('../test-vectors/alipay-v3/', import.meta.url);
1190+
const PRIVATE_KEY = readFileSync(new URL('PLACEHOLDER-test-only-rsa2048-private-key.pkcs8.b64', vectors), 'ascii').trim();
1191+
const PUBLIC_KEY = readFileSync(new URL('PLACEHOLDER-test-only-rsa2048-public-key.spki.b64', vectors), 'ascii').trim();
1192+
const alipay: ConnectorInstanceAuth = {
1193+
type: 'signed',
1194+
scheme: 'alipay-v3',
1195+
keyId: '2021000000000000',
1196+
credentialRef: 'ALIPAY_APP_PRIVATE_KEY',
1197+
vendorPublicKeyRef: 'ALIPAY_PUBLIC_KEY',
1198+
};
1199+
const both = (ref: string) => ({ ALIPAY_APP_PRIVATE_KEY: PRIVATE_KEY, ALIPAY_PUBLIC_KEY: PUBLIC_KEY } as Record<string, string>)[ref];
1200+
1201+
it('binds a signer that signs with the private key and verifies with the public key; neither key is in the context', async () => {
1202+
const { factory, calls } = makeSigningProvider(true);
1203+
const kernel = await boot([providerConnector('alipay_pay', { auth: alipay })], { providerFactory: factory, credentialResolver: both });
1204+
const ctx = calls[0]!;
1205+
expect([ctx.requestSigner?.scheme, typeof ctx.requestSigner?.verifyResponse]).toEqual(['alipay-v3', 'function']);
1206+
expect(JSON.stringify(ctx)).not.toContain(PRIVATE_KEY.slice(40, 120));
1207+
1208+
const request = { method: 'POST', url: 'https://openapi.alipay.com/v3/alipay/trade/query', headers: {}, body: '{}' };
1209+
const { authorization } = (await ctx.requestSigner!.sign(request)).headers;
1210+
const [, nonce, timestamp] = /nonce=([^,]+),timestamp=(\d+),/.exec(authorization!)!;
1211+
expect(authorization).toBe(
1212+
computeAlipayV3Signature(request, '2021000000000000', readAlipayPrivateKey(PRIVATE_KEY), nonce!, Number(timestamp)).headers.authorization,
1213+
);
1214+
// An unsigned 2xx is refused: the public key is in force.
1215+
await expect(ctx.requestSigner!.verifyResponse!({ status: 200, headers: { get: () => null }, body: '{}' })).rejects.toThrow(/no complete Alipay signature/);
1216+
await kernel.shutdown();
1217+
});
1218+
1219+
it('degrades the instance naming the public-key reference when only it does not resolve, without calling its factory', async () => {
1220+
const { factory, calls } = makeSigningProvider(true);
1221+
const kernel = await boot([providerConnector('alipay_pay', { auth: alipay })], {
1222+
providerFactory: factory,
1223+
credentialResolver: (ref) => (ref === 'ALIPAY_APP_PRIVATE_KEY' ? PRIVATE_KEY : undefined),
1224+
});
1225+
expect(calls).toHaveLength(0);
1226+
const engine = automationOf(kernel);
1227+
expect(engine.getConnectorDegradedReason('alipay_pay')).toContain('ALIPAY_PUBLIC_KEY');
1228+
await kernel.shutdown();
1229+
});
1230+
1231+
it('fails boot when the public key is not a key: a configuration fault, its value not echoed', async () => {
1232+
const { factory } = makeSigningProvider(true);
1233+
const boot26710 = boot([providerConnector('alipay_pay', { auth: alipay })], {
1234+
providerFactory: factory,
1235+
credentialResolver: (ref) => (ref === 'ALIPAY_PUBLIC_KEY' ? 'not-a-public-key-26710' : both(ref)),
1236+
});
1237+
await expect(boot26710).rejects.toThrow(/a key it names cannot sign or verify/);
1238+
await expect(boot26710).rejects.not.toThrow(/not-a-public-key-26710/);
1239+
});
1240+
});
1241+
11841242
it('CONTROL: a static kind is handed its credential and no signer', async () => {
11851243
const { factory, calls } = makeFakeProvider();
11861244
const kernel = await boot([providerConnector('k_bearer', { auth: { type: 'bearer', credentialRef: 'TOKEN' } })], {

‎packages/services/service-automation/src/plugin.ts‎

Lines changed: 57 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,19 @@ function credentialRefOf(auth: ConnectorInstanceAuth | undefined): string | unde
397397
return auth.credentialRef;
398398
}
399399

400+
/**
401+
* ADR-0143 D2.3 — the vendor public-key reference a `signed` instance names
402+
* beside its key, for a scheme whose vendor signs its responses (`alipay-v3`).
403+
*/
404+
function vendorPublicKeyRefOf(auth: ConnectorInstanceAuth | undefined): string | undefined {
405+
return auth?.type === 'signed' && auth.scheme === 'alipay-v3' ? auth.vendorPublicKeyRef : undefined;
406+
}
407+
408+
/** [#27237] Every reference an instance's `auth` names: its `credentialRef`, and a vendor public key's. */
409+
function credentialRefsOf(auth: ConnectorInstanceAuth | undefined): string[] {
410+
return [credentialRefOf(auth), vendorPublicKeyRefOf(auth)].filter((ref): ref is string => ref !== undefined);
411+
}
412+
400413
/** The `basic` username an instance sends beside its secret — what its `Authorization` header encodes with it. */
401414
function basicUsernameOf(auth: ConnectorInstanceAuth | undefined): string | undefined {
402415
return auth?.type === 'basic' ? auth.username : undefined;
@@ -2211,7 +2224,7 @@ export class AutomationServicePlugin implements Plugin {
22112224
// read is not one that is absent, so the rows count as unreadable then.
22122225
let chain: ConnectorCredentialChain = { vault: this.options.credentialResolver };
22132226
let credentialRows: Map<string, ConnectorCredentialRecord> | undefined = new Map();
2214-
if ([...desired.values()].some((d) => credentialRefOf(d.entry.auth) !== undefined)) {
2227+
if ([...desired.values()].some((d) => credentialRefsOf(d.entry.auth).length > 0)) {
22152228
try {
22162229
chain = await this.connectorCredentialChain(ctx);
22172230
if (chain.store) credentialRows = await chain.store.list();
@@ -2227,11 +2240,11 @@ export class AutomationServicePlugin implements Plugin {
22272240
}
22282241
const credentialSources = new Map<string, string>();
22292242
for (const d of desired.values()) {
2230-
const ref = credentialRefOf(d.entry.auth);
2231-
if (ref === undefined) continue;
2232-
const fingerprint = connectorCredentialFingerprint(chain, ref, credentialRows);
2233-
credentialSources.set(ref, fingerprint);
2234-
d.signature += `|credential:${fingerprint}`;
2243+
for (const ref of credentialRefsOf(d.entry.auth)) {
2244+
const fingerprint = connectorCredentialFingerprint(chain, ref, credentialRows);
2245+
credentialSources.set(ref, fingerprint);
2246+
d.signature += `|credential:${fingerprint}`;
2247+
}
22352248
}
22362249
// A refusal of a value the door does not hold stands until an upstream
22372250
// accepts the reference — or the reference stops resolving from the
@@ -2355,20 +2368,48 @@ export class AutomationServicePlugin implements Plugin {
23552368
}
23562369
credential = resolution;
23572370
}
2371+
// ADR-0143 D2.3 — a scheme that verifies responses names the
2372+
// vendor's public key beside the signing key; it resolves through
2373+
// the same chain and degrades the instance the same way, so a
2374+
// response is never accepted unverified for want of it.
2375+
const vendorRef = vendorPublicKeyRefOf(entry.auth);
2376+
let vendorPublicKey: string | undefined;
2377+
if (vendorRef !== undefined) {
2378+
let resolution: ConnectorCredentialResolution;
2379+
try {
2380+
resolution = await resolveConnectorCredential(chain, vendorRef, credentialRows);
2381+
} catch (err) {
2382+
fail(
2383+
`[Automation] connector instance '${name}' (provider '${provider}'): auth resolution failed (ADR-0097 §3).`,
2384+
err,
2385+
);
2386+
continue;
2387+
}
2388+
if (resolution.kind !== 'resolved') {
2389+
await this.degradeConnectorForCredential(engine, ctx, {
2390+
name, entry, provider, signature, existing, ref: vendorRef, resolution,
2391+
});
2392+
continue;
2393+
}
2394+
vendorPublicKey = resolution.value;
2395+
}
23582396
// ADR-0143 D2.3, D4 — a `signed` instance's key is bound to the
23592397
// signer its scheme names, here, and the provider receives only
23602398
// the signer: the key never crosses into a provider package. A key
2361-
// that cannot sign at all is a configuration fault, like an
2362-
// unparseable retry policy below.
2399+
// that cannot sign (or a vendor key that cannot verify) is a
2400+
// configuration fault, like an unparseable retry policy below.
23632401
let auth: ResolvedConnectorAuth | undefined;
23642402
let requestSigner: ConnectorRequestSigner | undefined;
23652403
if (entry.auth?.type === 'signed') {
23662404
try {
2367-
requestSigner = createConnectorRequestSigner(name, entry.auth, credential?.value ?? '');
2405+
requestSigner = createConnectorRequestSigner(name, entry.auth, {
2406+
key: credential?.value ?? '',
2407+
...(vendorPublicKey === undefined ? {} : { vendorPublicKey }),
2408+
});
23682409
} catch (err) {
23692410
fail(
2370-
`[Automation] connector instance '${name}' (provider '${provider}'): its signing key cannot sign ` +
2371-
`(ADR-0143 D2.3).`,
2411+
`[Automation] connector instance '${name}' (provider '${provider}'): a key it names cannot sign or ` +
2412+
`verify (ADR-0143 D2.3).`,
23722413
err,
23732414
);
23742415
continue;
@@ -2873,12 +2914,12 @@ export class AutomationServicePlugin implements Plugin {
28732914
const entry = raw as DeclaredConnectorItem & { _packageId?: unknown };
28742915
if (typeof entry?.name !== 'string' || entry.name.length === 0) continue;
28752916
if (typeof entry.provider !== 'string' || entry.provider.length === 0) continue;
2876-
const ref = credentialRefOf(entry.auth);
2877-
if (ref === undefined) continue;
28782917
const packageId = typeof entry._packageId === 'string' && entry._packageId.length > 0 ? entry._packageId : undefined;
2879-
const list = out.get(ref) ?? [];
2880-
if (!list.some((c) => c.name === entry.name)) list.push({ name: entry.name, ...(packageId ? { packageId } : {}) });
2881-
out.set(ref, list);
2918+
for (const ref of credentialRefsOf(entry.auth)) {
2919+
const list = out.get(ref) ?? [];
2920+
if (!list.some((c) => c.name === entry.name)) list.push({ name: entry.name, ...(packageId ? { packageId } : {}) });
2921+
out.set(ref, list);
2922+
}
28822923
}
28832924
return out;
28842925
}

0 commit comments

Comments
 (0)