Commit cf45b2a0 by 张立顺

test: add guarded ROP test client

1 parent 98836795
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
assertAllowedE2EEnvironment,
redactSensitive
} from './support/environmentGuard.mjs'
const TEST_BASE = 'http://dj.test.glsx.com.cn/rop-dj-car-boutique'
describe('order lifecycle environment guard', () => {
it('IT-OL-SAFE-001: explicit E2E switch is required', () => {
assert.throws(
() => assertAllowedE2EEnvironment({ baseUrl: TEST_BASE, enabled: false }),
/RUN_ORDER_E2E=1/
)
})
it('IT-OL-SAFE-002: non-test and path-variant URLs are rejected', () => {
const rejected = [
'https://dj.glsx.com.cn/rop-dj-car-boutique',
'http://dj.beta.glsx.com.cn/rop-dj-car-boutique',
'http://192.168.3.226:9711/rop-dj-car-boutique',
'http://example.test/rop-dj-car-boutique',
`${TEST_BASE}/router`,
`${TEST_BASE}?source=test`,
`${TEST_BASE}#swagger`,
'http://name:password@dj.test.glsx.com.cn/rop-dj-car-boutique'
]
for (const baseUrl of rejected) {
assert.throws(
() => assertAllowedE2EEnvironment({ baseUrl, enabled: true }),
/not allowlisted/
)
}
})
it('IT-OL-SAFE-003: exact test base URL passes', () => {
const result = assertAllowedE2EEnvironment({
baseUrl: TEST_BASE,
enabled: true
})
assert.equal(result.origin, 'http://dj.test.glsx.com.cn')
assert.equal(result.pathname, '/rop-dj-car-boutique')
})
it('IT-OL-SAFE-004: recursive redaction masks sensitive keys without mutation', () => {
const source = {
mobile: 'value-a',
smsCode: 'value-b',
nested: {
sessionId: 'value-c',
sign: 'value-d',
secret: 'value-e',
appKey: 'value-f',
ordinary: 'visible'
},
list: [{ signature: 'value-g', count: 2 }]
}
const redacted = redactSensitive(source)
assert.equal(redacted.mobile, '[REDACTED]')
assert.equal(redacted.smsCode, '[REDACTED]')
assert.equal(redacted.nested.sessionId, '[REDACTED]')
assert.equal(redacted.nested.sign, '[REDACTED]')
assert.equal(redacted.nested.secret, '[REDACTED]')
assert.equal(redacted.nested.appKey, '[REDACTED]')
assert.equal(redacted.nested.ordinary, 'visible')
assert.equal(redacted.list[0].signature, '[REDACTED]')
assert.equal(source.nested.secret, 'value-e')
assert.notEqual(redacted, source)
})
})
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { createRopClient } from './support/ropClient.mjs'
const TEST_BASE = 'http://dj.test.glsx.com.cn/rop-dj-car-boutique'
const METHOD = 'dj.api.smartcarlife.order.createWithPay'
const jsonResponse = value => ({
ok: true,
status: 200,
async text() {
return JSON.stringify(value)
}
})
const createHarness = ({ response = { code: 0, data: { id: 7 } }, fetchError } = {}) => {
const signerCalls = []
const fetchCalls = []
const logCalls = []
const credentials = {
appKey: 'test-app-key',
secret: 'test-secret',
sign(params, secret, noSignAttr) {
signerCalls.push({ params: { ...params }, secret, noSignAttr })
return { ...params, sign: 'test-signature' }
}
}
const fetchImpl = async (url, options) => {
fetchCalls.push({ url, options })
if (fetchError) throw fetchError
return jsonResponse(response)
}
const logger = {
debug(label, details) {
logCalls.push({ label, details })
}
}
return { credentials, fetchImpl, logger, signerCalls, fetchCalls, logCalls }
}
describe('signed ROP test client', () => {
it('IT-OL-ROP-001: signs and form-encodes required common fields', async () => {
const harness = createHarness()
const client = createRopClient({ baseUrl: TEST_BASE, ...harness })
const result = await client.post(METHOD, { marker: 'case-1' })
assert.deepEqual(result, { code: 0, data: { id: 7 } })
assert.equal(harness.signerCalls.length, 1)
assert.deepEqual(harness.signerCalls[0].params, {
marker: 'case-1',
v: '1.0.0',
method: METHOD,
format: 'json',
locale: 'zh_CN',
source: 'dj-wechat',
appKey: 'test-app-key'
})
assert.equal(harness.signerCalls[0].secret, 'test-secret')
assert.deepEqual(harness.signerCalls[0].noSignAttr, [])
assert.equal(harness.fetchCalls.length, 1)
assert.equal(
harness.fetchCalls[0].url,
`${TEST_BASE}/router?method=${encodeURIComponent(METHOD)}`
)
assert.equal(harness.fetchCalls[0].options.method, 'POST')
assert.equal(
harness.fetchCalls[0].options.headers['content-type'],
'application/x-www-form-urlencoded'
)
const body = new URLSearchParams(harness.fetchCalls[0].options.body)
assert.equal(body.get('marker'), 'case-1')
assert.equal(body.get('method'), METHOD)
assert.equal(body.get('sign'), 'test-signature')
})
it('IT-OL-ROP-002: business failure remains available to workflow assertions', async () => {
const response = { code: -1, message: 'business rejected', data: null }
const harness = createHarness({ response })
const client = createRopClient({ baseUrl: TEST_BASE, ...harness })
assert.deepEqual(await client.post(METHOD, { marker: 'case-2' }), response)
})
it('IT-OL-ROP-003: invalid JSON error names method without leaking request data', async () => {
const harness = createHarness()
harness.fetchImpl = async () => ({
ok: true,
status: 200,
async text() {
return 'not-json'
}
})
const client = createRopClient({ baseUrl: TEST_BASE, ...harness })
await assert.rejects(
client.post(METHOD, { customerPhone: 'private-value' }),
error => {
assert.match(error.message, new RegExp(METHOD.replaceAll('.', '\\.')))
assert.doesNotMatch(error.message, /private-value/)
return true
}
)
})
it('IT-OL-ROP-004: network error is sanitized', async () => {
const harness = createHarness({
fetchError: new Error('network failed with private-value')
})
const client = createRopClient({ baseUrl: TEST_BASE, ...harness })
await assert.rejects(client.post(METHOD, { sessionId: 'private-value' }), error => {
assert.match(error.message, new RegExp(METHOD.replaceAll('.', '\\.')))
assert.doesNotMatch(error.message, /private-value/)
return true
})
})
it('IT-OL-ROP-005: diagnostic logs are recursively redacted', async () => {
const harness = createHarness()
const client = createRopClient({ baseUrl: TEST_BASE, ...harness })
await client.post(METHOD, {
mobile: 'private-mobile',
nested: { sessionId: 'private-session', ordinary: 'visible' }
})
const serialized = JSON.stringify(harness.logCalls)
assert.doesNotMatch(serialized, /private-mobile|private-session|test-app-key|test-signature/)
assert.match(serialized, /visible/)
})
it('IT-OL-ROP-006: project adapter loads the selected test signer without exposing values', async () => {
const { loadProjectRopCredentials } = await import(
'./support/projectRopCredentials.mjs'
)
const credentials = await loadProjectRopCredentials()
assert.equal(typeof credentials.appKey, 'string')
assert.ok(credentials.appKey.length > 0)
assert.equal(typeof credentials.secret, 'string')
assert.ok(credentials.secret.length > 0)
assert.equal(typeof credentials.sign, 'function')
const signed = credentials.sign(
{ appKey: credentials.appKey, method: 'dj.api.test', marker: 'adapter' },
credentials.secret,
[]
)
assert.match(signed.sign, /^[0-9A-F]{40}$/)
})
})
const ALLOWED_BASE = 'http://dj.test.glsx.com.cn/rop-dj-car-boutique'
const allowedUrl = new URL(ALLOWED_BASE)
const sensitiveKeyPattern = /mobile|code|session|sign|secret|appKey/i
const notAllowed = () =>
new Error('E2E base URL is not allowlisted for order lifecycle tests')
export function assertAllowedE2EEnvironment({ baseUrl, enabled }) {
if (enabled !== true) {
throw new Error('RUN_ORDER_E2E=1 is required for real order lifecycle tests')
}
let url
try {
url = new URL(baseUrl)
} catch {
throw notAllowed()
}
const exactBase =
url.protocol === allowedUrl.protocol &&
url.hostname === allowedUrl.hostname &&
url.port === allowedUrl.port &&
url.pathname === allowedUrl.pathname &&
url.search === '' &&
url.hash === '' &&
url.username === '' &&
url.password === ''
if (!exactBase) {
throw notAllowed()
}
return url
}
const isPlainObject = value => {
if (value === null || typeof value !== 'object') return false
const prototype = Object.getPrototypeOf(value)
return prototype === Object.prototype || prototype === null
}
export function redactSensitive(value) {
if (Array.isArray(value)) {
return value.map(item => redactSensitive(item))
}
if (!isPlainObject(value)) {
return value
}
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
sensitiveKeyPattern.test(key) ? '[REDACTED]' : redactSensitive(item)
])
)
}
export { ALLOWED_BASE }
import { readFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const require = createRequire(import.meta.url)
const repositoryRoot = fileURLToPath(new URL('../../../', import.meta.url))
const TEST_ENV_INDEX = 2
const TEST_DOMAIN = 'https://dj.test.glsx.com.cn'
const asDataModule = (source, label) =>
`data:text/javascript;base64,${Buffer.from(
`${source}\n//# sourceURL=${label}\n`,
'utf8'
).toString('base64')}`
const replaceRequired = (source, pattern, replacement, label) => {
if (!pattern.test(source)) {
throw new Error(`Unable to load project ROP credentials: missing ${label}`)
}
return source.replace(pattern, replacement)
}
async function loadTestEnvironment() {
const sourcePath = path.join(repositoryRoot, 'utils/request/environment.js')
let source = await readFile(sourcePath, 'utf8')
source = replaceRequired(
source,
/import\s+\{\s*envIndex\s*\}\s+from\s+['"]~\/config['"];?/,
`const envIndex = ${TEST_ENV_INDEX}`,
'environment selector import'
)
source = replaceRequired(
source,
/module\.exports\s*=/,
'export default',
'environment export'
)
const module = await import(asDataModule(source, 'order-lifecycle-environment.js'))
if (module.default?.domain?.dj !== TEST_DOMAIN) {
throw new Error('Project credential adapter did not select the test environment')
}
return module.default
}
async function loadProjectHttpModule(environment) {
const contextKey = `__orderLifecycleRopContext_${Date.now()}_${Math.random()
.toString(36)
.slice(2)}`
globalThis[contextKey] = {
environment,
sha1: require(path.join(repositoryRoot, 'utils/lib/sha1.js')),
qs: require(path.join(repositoryRoot, 'utils/lib/qs.js'))
}
try {
const sourcePath = path.join(repositoryRoot, 'utils/request/http.js')
let source = await readFile(sourcePath, 'utf8')
source = replaceRequired(
source,
/import\s+environment\s+from\s+['"]\.\/environment\.js['"];?/,
`const environment = globalThis[${JSON.stringify(contextKey)}].environment`,
'environment import'
)
source = replaceRequired(
source,
/import\s+sha1\s+from\s+['"]~\/utils\/lib\/sha1['"];?/,
`const sha1 = globalThis[${JSON.stringify(contextKey)}].sha1`,
'sha1 import'
)
source = replaceRequired(
source,
/import\s+qs\s+from\s+['"]~\/utils\/lib\/qs['"];?/,
`const qs = globalThis[${JSON.stringify(contextKey)}].qs`,
'qs import'
)
source = replaceRequired(
source,
/module\.exports\s*=/,
'export default',
'HTTP module export'
)
const module = await import(asDataModule(source, `order-lifecycle-http-${contextKey}.js`))
return module.default
} finally {
delete globalThis[contextKey]
}
}
let credentialPromise
export async function loadProjectRopCredentials() {
credentialPromise ??= (async () => {
const environment = await loadTestEnvironment()
const http = await loadProjectHttpModule(environment)
const selected = http?.secretKey?.dj
if (!selected?.appKey || !selected?.secret || typeof http?.sign !== 'function') {
throw new Error('Project test ROP credentials are incomplete')
}
return {
appKey: selected.appKey,
secret: selected.secret,
sign: http.sign
}
})()
const credentials = await credentialPromise
return { ...credentials }
}
import {
assertAllowedE2EEnvironment,
redactSensitive
} from './environmentGuard.mjs'
const COMMON_FIELDS = {
v: '1.0.0',
format: 'json',
locale: 'zh_CN',
source: 'dj-wechat'
}
const sanitizedError = (phase, method) =>
new Error(`ROP ${phase} failed for ${method}`)
const toFormBody = signedParams => {
const form = new URLSearchParams()
for (const [key, value] of Object.entries(signedParams)) {
if (value === undefined) continue
if (value === null) {
form.append(key, '')
} else if (typeof value === 'object') {
form.append(key, JSON.stringify(value))
} else {
form.append(key, String(value))
}
}
return form.toString()
}
const safeDebug = (logger, label, details) => {
try {
logger?.debug?.(label, redactSensitive(details))
} catch {
// Diagnostics must never change workflow behavior.
}
}
export function createRopClient({
baseUrl,
credentials,
fetchImpl = globalThis.fetch,
logger
}) {
const allowedBase = assertAllowedE2EEnvironment({
baseUrl,
enabled: true
}).toString()
if (!credentials?.appKey || !credentials?.secret) {
throw new TypeError('ROP credentials require appKey and secret')
}
if (typeof credentials.sign !== 'function') {
throw new TypeError('ROP credentials.sign must be a function')
}
if (typeof fetchImpl !== 'function') {
throw new TypeError('fetchImpl must be a function')
}
return {
async post(method, data = {}) {
const params = {
...data,
...COMMON_FIELDS,
method,
appKey: credentials.appKey
}
let signed
try {
signed = credentials.sign(params, credentials.secret, [])
} catch {
throw sanitizedError('signing', method)
}
const url = `${allowedBase}/router?method=${encodeURIComponent(method)}`
safeDebug(logger, 'rop.request', { method, data })
let response
try {
response = await fetchImpl(url, {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
body: toFormBody(signed)
})
} catch {
throw sanitizedError('network request', method)
}
let parsed
try {
parsed = JSON.parse(await response.text())
} catch {
throw sanitizedError('response parsing', method)
}
safeDebug(logger, 'rop.response', {
method,
status: response.status,
response: parsed
})
return parsed
}
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!