cmvr-wms/scripts/projectdev/api-contract-audit.cjs

137 lines
13 KiB
JavaScript
Raw Normal View History

// Inventory every published endpoint. Probe authentication, then safe reads/exports.
// Business writes are exercised separately by rollback-only Java tests and browser mocks.
const fs = require('node:fs'), path = require('node:path'), assert = require('node:assert/strict')
const { backend, username, password } = require('./vue3-test-runtime.cjs')
const out = path.resolve('.codex-tmp/full-flow-audit')
const methods = new Set(['get', 'post', 'put', 'delete', 'patch'])
const publicPaths = new Set(['/login', '/register', '/captchaImage'])
const rows = [], failures = []
async function request(method, url, token, data) {
const headers = token ? { Authorization: 'Bearer ' + token } : {}
if (data !== undefined) headers['Content-Type'] = 'application/json'
const response = await fetch(backend + url, { method, headers, body: data === undefined ? undefined : JSON.stringify(data), signal: AbortSignal.timeout(25000) })
const type = response.headers.get('content-type') || '', bytes = new Uint8Array(await response.arrayBuffer())
let body
if (type.includes('json')) { try { body = JSON.parse(new TextDecoder().decode(bytes)) } catch {} }
return { status: response.status, code: body?.code, message: body?.msg, bytes: bytes.length, type, body }
}
const redact = r => ({ status: r.status, code: r.code, message: r.code && r.code !== 200 ? r.message : undefined, bytes: r.bytes })
const dataRows = r => r?.body?.rows || r?.body?.data?.rows || (Array.isArray(r?.body?.data) ? r.body.data : [])
function absentPath(p) { return p.replace(/\{[^}]+\}/g, '0') }
function fail(row, stage, result) { failures.push({ method: row.method, path: row.path, stage, ...redact(result) }) }
function isInternalError(result) { return /NullPointer|SQLSyntax|BadSqlGrammar|java\.|IndexOutOfBounds|Cannot invoke|Cannot read|For input string|Exception|### SQL/i.test(result.message || '') || result.status >= 500 }
// Only these exact negative contracts may be counted as a missing-fixture check.
// A failure on a real usable fixture, a new business error, or code=0 is a failure.
function expectedReadRejection(p, result, fixture) {
if (result.status !== 200 || result.code !== 500 || isInternalError(result)) return undefined
const contracts = {
'/warehouse/purchase/sheet/unbatched': [!fixture.unbatched, '明细已组批或已删除,请刷新列表', 'No unbatched purchase exists; only missing-ID rejection is covered.'],
'/warehouse/out/{id}/returns': [!!fixture.out && !fixture.out.costEventId, '该历史出库未补录成本链,不能自动撤销或退料;现有库存已作为期初保留', 'Selected historical out-record has no cost chain; legacy protection is expected.'],
'/warehouse/in/pending-groups/{key}': [!fixture.pending, '来源编号无效', 'No pending receipt group exists; only malformed-key rejection is covered.'],
'/project/loans/{id}/returns': [!fixture.loan, '借用记录不存在', 'No project loan exists; only missing-ID rejection is covered.'],
'/production/tasks/shortages': [!fixture.openTask, '生产任务不存在', 'No open production task exists; only missing-ID rejection is covered.']
}
for (const path of ['/tool/gen/{tableId}', '/tool/gen/preview/{tableId}', '/tool/gen/column/{tableId}']) contracts[path] = [!fixture.gen, '生成配置不存在或已删除,请返回列表刷新', 'No imported generation configuration exists; only missing-ID rejection is covered.']
const rule = contracts[p]
return rule?.[0] && result.message === rule[1] ? rule[2] : undefined
}
function selectUsableFixture(records, predicate, fallback = false) {
return records.find(predicate) || (fallback ? records[0] : undefined)
}
async function main() {
fs.mkdirSync(out, { recursive: true })
const spec = await (await fetch(backend + '/v3/api-docs')).json()
for (const [p, operations] of Object.entries(spec.paths)) for (const [method, operation] of Object.entries(operations)) if (methods.has(method)) rows.push({ method: method.toUpperCase(), path: p, controller: operation.tags?.[0], tests: {} })
const login = await request('POST', '/login', undefined, { username, password })
assert.equal(login.code, 200, 'test login'); const token = login.body.token
// A missing token cannot reach protected mutations. Public authentication endpoints are handled explicitly.
for (const row of rows) {
if (publicPaths.has(row.path) || row.path === '/' && row.method === 'GET') { row.tests.authentication = { result: 'public endpoint' }; continue }
const result = await request(row.method, absentPath(row.path), undefined, ['POST', 'PUT', 'PATCH'].includes(row.method) ? {} : undefined)
row.tests.authentication = { result: result.code === 401 || result.status === 401 ? 'PASS' : 'FAIL', ...redact(result) }
if (row.tests.authentication.result === 'FAIL') fail(row, 'authentication', result)
}
console.log('Authentication probes completed:', rows.length)
const lists = {
project: '/project/info/list', item: '/warehouse/product/list', area: '/warehouse/area/list', purchase: '/warehouse/purchase/list', batch: '/warehouse/purchase/batch/list',
stock: '/warehouse/stock/list', in: '/warehouse/in/list', out: '/warehouse/out/list', check: '/warehouse/check/list', job: '/warehouse/batch/list', task: '/production/tasks/page', bom: '/production/bom/list',
dept: '/system/dept/list', post: '/system/post/list', notice: '/system/notice/list', dict: '/system/dict/type/list', config: '/system/config/list', gen: '/tool/gen/list', schedule: '/monitor/job/list', jobLog: '/monitor/jobLog/list',
unbatched: '/warehouse/purchase/list?unbatched=true', openTask: '/production/tasks/page?status=OPEN', loan: '/project/loans', pending: '/warehouse/in/pending-groups'
}
const fixture = {}, collections = {}, fixtureCoverage = {}
for (const [name, url] of Object.entries(lists)) {
const result = await request('GET', url + (url.includes('?') ? '&' : '?') + 'pageNum=1&pageSize=100', token)
assert.equal(result.status, 200, 'Fixture list HTTP status: ' + name)
assert.equal(result.code, 200, 'Fixture list response: ' + name + ': ' + result.message)
collections[name] = dataRows(result)
fixture[name] = collections[name][0]
fixtureCoverage[name] = { scanned: collections[name].length, total: result.body.total ?? result.body.data?.total ?? collections[name].length }
}
fixture.unbatched = selectUsableFixture(collections.unbatched, row => row.id && row.purchaseBatchId == null)
fixture.openTask = selectUsableFixture(collections.openTask, row => row.id && row.status === 'OPEN')
fixture.out = selectUsableFixture(collections.out.filter(row => row.active !== false), row => row.costEventId, true)
fixture.pending = selectUsableFixture(collections.pending, row => /^[BPO]:[0-9]{1,18}$/.test(row.key || ''))
const arrivalCandidates = []
// Availability requires acceptance; an unaccepted arrival is not a valid positive fixture.
for (const purchase of collections.purchase) {
const result = await request('GET', '/warehouse/purchase/arrival/' + purchase.id, token)
assert.equal(result.code, 200, 'Arrival fixture lookup must succeed')
arrivalCandidates.push(...dataRows(result))
if (arrivalCandidates.some(row => Number(row.acceptanceStatus) === 1)) break
}
fixture.arrival = selectUsableFixture(arrivalCandidates, row => Number(row.acceptanceStatus) === 1)
fixtureCoverage.arrival = { scanned: arrivalCandidates.length, selectedAccepted: Number(fixture.arrival?.acceptanceStatus) === 1, purchaseScanLimit: collections.purchase.length }
const id = name => fixture[name]?.id || 0
const params = { projectId: id('project'), itemId: id('item'), userId: 1, roleId: 1, menuId: 2100, deptId: fixture.dept?.deptId || 0, postId: fixture.post?.postId || 0, noticeId: fixture.notice?.noticeId || 0,
dictId: fixture.dict?.dictId || 0, dictType: 'wms_item_unit', dictCode: 0, configId: fixture.config?.configId || 0, configKey: 'sys.account.registerUser', tableId: fixture.gen?.tableId || 0,
jobId: fixture.schedule?.jobId || 0, jobLogId: fixture.jobLog?.jobLogId || 0, requestId: id('purchase'), arrivalId: id('arrival'), kind: 'STOCK', cacheName: 'audit_nonexistent:', cacheKey: 'audit_nonexistent', key: fixture.pending?.key || 'audit_nonexistent' }
function routeId(p) {
if (p.startsWith('/warehouse/suppliers/')) return 0
if (p.startsWith('/project/loans/')) return id('loan')
for (const [prefix, name] of [['/warehouse/purchase/sheet/', 'batch'], ['/warehouse/purchase/batch/', 'batch'], ['/warehouse/purchase/', 'purchase'], ['/warehouse/product/', 'item'], ['/warehouse/stock/', 'stock'], ['/warehouse/in/', 'in'], ['/warehouse/out/', 'out'], ['/warehouse/check/', 'check'], ['/warehouse/batch/', 'job'], ['/warehouse/area/', 'area'], ['/project/info/', 'project'], ['/production/tasks/', 'task'], ['/production/bom/', 'bom']]) if (p.startsWith(prefix)) return id(name)
return 0
}
const unsafeReads = new Map([
['/tool/gen/synchDb/{tableName}', 'Synchronizes stored generation metadata'], ['/tool/gen/genCode/{tableName}', 'Writes generated code to configured filesystem'], ['/monitor/logininfor/unlock/{userName}', 'Changes account lock state'],
['/tool/gen/download/{tableName}', 'Requires an imported generation fixture'], ['/tool/gen/batchGenCode', 'Requires imported generation fixtures'], ['/common/download', 'Requires a test download file'], ['/common/download/resource', 'Requires a test uploaded resource']
])
const query = {
'/warehouse/stock/events': { projectId: id('project'), itemId: id('item') }, '/warehouse/stock/adjustments': { projectId: id('project'), itemId: id('item') },
'/system/role/authUser/allocatedList': { roleId: 1 }, '/system/role/authUser/unallocatedList': { roleId: 1 }, '/system/notice/readUsers/list': { noticeId: params.noticeId },
'/warehouse/purchase/sheet/unbatched': { ids: id('unbatched') }, '/warehouse/purchase/returns': { arrivalId: id('arrival') }, '/project/loans/options': { projectId: id('project'), itemId: id('item') },
'/production/tasks/shortages': { taskIds: id('openTask') }, '/production/tasks/reference': { bomId: id('bom'), projectId: id('project') }, '/production/tasks/cost-history': { itemId: id('item') },
'/production/bom/options': { itemId: id('item') }
}
for (const row of rows) {
if (row.method !== 'GET') continue
if (unsafeReads.has(row.path)) { row.tests.read = { result: 'NOT RUN', reason: unsafeReads.get(row.path) }; continue }
if (row.path === '/warehouse/purchase/returns/{arrivalId}/availability' && !fixture.arrival) {
row.tests.read = { result: 'NOT RUN', reason: 'No accepted arrival exists in scanned purchases; availability is covered by rollback-only service/controller tests, not live positive HTTP.' }; continue
}
const values = { ...params, id: routeId(row.path) }
if (row.path.startsWith('/warehouse/batch/')) values.jobId = id('job')
const url = row.path.replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(values[name] ?? 0)) + '?' + new URLSearchParams({ pageNum: 1, pageSize: 2, ...(query[row.path] || {}) })
const result = await request('GET', url, token)
const rejectionReason = expectedReadRejection(row.path, result, fixture)
const ok = result.status < 400 && (result.code === undefined || result.code === 200)
row.tests.read = { result: ok ? 'PASS' : rejectionReason ? 'MISSING FIXTURE / REJECTED' : 'FAIL', ...(rejectionReason ? { reason: rejectionReason } : {}), ...redact(result) }
if (!ok && !rejectionReason) fail(row, 'read', result)
}
for (const row of rows.filter(r => r.method === 'POST' && (/\/export$/.test(r.path) || /\/(?:importTemplate|import-template)$/.test(r.path) || r.path === '/warehouse/initialization/{kind}/template'))) {
const url = row.path.replace(/\{id\}/g, id('bom')).replace('{kind}', 'STOCK') + '?' + new URLSearchParams({ itemId: id('item'), pageNum: 1, pageSize: 2 })
// Exports use @ModelAttribute; never post the business DTO or execute a transaction.
const result = await request('POST', url, token)
const ok = result.status === 200 && result.code === undefined && result.bytes > 0
row.tests.export = { result: ok ? 'PASS' : 'FAIL', ...redact(result) }
if (row.tests.export.result === 'FAIL') fail(row, 'export', result)
}
// Explicitly report write coverage as separate rollback/mocked suites, not live HTTP business writes.
for (const row of rows) if (row.method !== 'GET' && !row.tests.export) row.tests.businessWrite = { result: 'NOT EXECUTED ON EXISTING RECORDS', reason: 'See rollback-only backend suites and mocked UI workflow regressions; authentication checked here.' }
const summary = { total: rows.length, authenticationPassed: rows.filter(r => r.tests.authentication?.result === 'PASS').length, readsPassed: rows.filter(r => r.tests.read?.result === 'PASS').length, exportsPassed: rows.filter(r => r.tests.export?.result === 'PASS').length, missingFixtures: rows.filter(r => Object.values(r.tests).some(t => t.result === 'MISSING FIXTURE / REJECTED')).length, failures }
fs.writeFileSync(path.join(out, 'api-results.json'), JSON.stringify({ at: new Date().toISOString(), summary, fixtureCoverage, endpoints: rows }, null, 2))
console.log(JSON.stringify(summary, null, 2))
assert.deepEqual(failures, [], 'API failures must be reviewed and fixed')
}
module.exports = { expectedReadRejection, selectUsableFixture }
if (require.main === module) main().catch(error => { console.error(error); process.exitCode = 1 })