import { describe, expect, it, vi, beforeEach } from 'vitest'; import { readFileSync } from 'node:fs'; /** * 主系统对接「授权一致性」防护(设计:docs/design/20261022-主系统对接授权一致性防护.md)。 * * 钉住三条防复发红线: * ① 推送方 client 与本地配置不一致 ⇒ 判定为拒绝(不能"单进来了、却回写不出去"); * ② 导入前出站不可用 ⇒ 预检失败(不建单)+ 写失败台账 + 首次通知; * ③ 出站 401/403/404 ⇒ token 层统一落台账/通知(覆盖报告、回写、事实刷新)。 */ const mocks = vi.hoisted(() => ({ poolQuery: vi.fn(), recordFailure: vi.fn(), notify: vi.fn(), findBranch: vi.fn(), token: vi.fn(), integrationEnabled: vi.fn(), })); vi.mock('../src/db', () => ({ pool: { query: (...args: unknown[]) => mocks.poolQuery(...args) }, })); vi.mock('../src/config', () => ({ config: { mainSystemIntegration: { clientId: 'erp_configured_client' } }, })); vi.mock('../src/services/mainSystem/config', () => ({ isMainSystemIntegrationEnabled: (...args: unknown[]) => mocks.integrationEnabled(...args), })); vi.mock('../src/services/mainSystem/token', () => ({ getMainSystemToken: (...args: unknown[]) => mocks.token(...args), })); vi.mock('../src/services/branchAccessCode', () => ({ findBranchCodeByAccessCode: (...args: unknown[]) => mocks.findBranch(...args), })); vi.mock('../src/services/mainSystemImportFailureService', () => ({ recordMainSystemImportFailure: (...args: unknown[]) => mocks.recordFailure(...args), })); vi.mock('../src/services/notificationService', () => ({ notifyRoleUsers: (...args: unknown[]) => mocks.notify(...args), })); vi.mock('../src/services/orderDeliveryDate', () => ({ formatChinaDate: () => '2026-10-22', })); const { evaluatePushClientIdentity, recordForeignClientPush, recordOutboundAuthFailure, ensureOutboundAuthForImport, configuredPushClientId, } = await import('../src/services/mainSystemAuthConsistencyGuard'); beforeEach(() => { vi.clearAllMocks(); mocks.poolQuery.mockResolvedValue({ rows: [] }); mocks.recordFailure.mockResolvedValue({ attempts: 1, isFirst: true }); mocks.notify.mockResolvedValue(true); mocks.findBranch.mockResolvedValue(null); mocks.integrationEnabled.mockReturnValue(true); mocks.token.mockResolvedValue({ kind: 'ok', token: 't', branchCode: 'BR002', expiresAt: Date.now() + 60000 }); }); describe('入站来源守卫:推送方 client 必须与本地配置一致', () => { it('一致 ⇒ 放行', () => { expect( evaluatePushClientIdentity({ bodyClientId: 'erp_configured_client', configuredClientId: 'erp_configured_client', }).ok ).toBe(true); }); it('不一致 ⇒ 拒绝,并带出双方 client_id(body 优先)', () => { const result = evaluatePushClientIdentity({ bodyClientId: 'devcore_race_client', headerClientId: 'erp_configured_client', configuredClientId: 'erp_configured_client', }); expect(result.ok).toBe(false); if (!result.ok) { expect(result.reason).toBe('client_mismatch'); expect(result.pushedClientId).toBe('devcore_race_client'); expect(result.configuredClientId).toBe('erp_configured_client'); } }); it('body 缺字段时回退请求头 X-Client-Id', () => { const result = evaluatePushClientIdentity({ headerClientId: 'devcore_race_client', configuredClientId: 'erp_configured_client', }); expect(result.ok).toBe(false); }); it('推送方/本地任一缺失 ⇒ 放行(老版本主系统兼容,不改现行为)', () => { expect(evaluatePushClientIdentity({ configuredClientId: 'erp_configured_client' }).ok).toBe(true); expect(evaluatePushClientIdentity({ bodyClientId: 'x', configuredClientId: '' }).ok).toBe(true); }); it('configuredPushClientId 返回配置值', () => { expect(configuredPushClientId()).toBe('erp_configured_client'); }); }); describe('推送来源异常:落失败台账 + 首次通知', () => { it('识别出我方分公司并写台账(error_code=push_client_mismatch),首次失败通知一次', async () => { mocks.findBranch.mockResolvedValue('BR002'); await recordForeignClientPush({ event: 'preparations.allocated', payload: { client_id: 'devcore_race_client', subsystem_code: 'SCQEM2X7B6P5', branch_code: 'BR002', order_code: 'ORD_WEB_20261022_BR002_0001', data: [{ task_day: '2026-10-22' }], }, pushedClientId: 'devcore_race_client', configuredClientId: 'erp_configured_client', }); expect(mocks.recordFailure).toHaveBeenCalledTimes(1); const arg = mocks.recordFailure.mock.calls[0][0] as Record; expect(arg.errorCode).toBe('push_client_mismatch'); expect(arg.branchCode).toBe('BR002'); expect(arg.deliveryDate).toBe('2026-10-22'); expect(arg.mainOrderCode).toBe('ORD_WEB_20261022_BR002_0001'); expect(mocks.notify).toHaveBeenCalledTimes(1); expect((mocks.notify.mock.calls[0][0] as Record).title).toContain('推送来源异常'); }); it('非首次失败不再重复通知(台账 attempts 累加)', async () => { mocks.recordFailure.mockResolvedValue({ attempts: 3, isFirst: false }); await recordForeignClientPush({ event: 'preparations.allocated', payload: { order_code: 'ORD_WEB_20261022_BR002_0001', data: [] }, pushedClientId: 'devcore_race_client', configuredClientId: 'erp_configured_client', }); expect(mocks.recordFailure).toHaveBeenCalledTimes(1); expect(mocks.notify).not.toHaveBeenCalled(); }); }); describe('出站授权失败:台账 + 首次通知', () => { it('按供应商反查绑定镜像归位,写 outbound_auth_forbidden', async () => { mocks.poolQuery.mockResolvedValue({ rows: [{ branch_code: 'BR002', main_branch_code: 'BR002' }] }); await recordOutboundAuthFailure({ supplierCode: 'SUP37831443', reason: 'forbidden: 未授权访问该供应商', }); const arg = mocks.recordFailure.mock.calls[0][0] as Record; expect(arg.errorCode).toBe('outbound_auth_forbidden'); expect(arg.branchCode).toBe('BR002'); expect(arg.mainBranchCode).toBe('BR002'); expect(mocks.notify).toHaveBeenCalledTimes(1); expect((mocks.notify.mock.calls[0][0] as Record).title).toContain('授权失效'); }); it('查不到绑定也能落台账(branch=UNKNOWN / main_branch=* 便于排障,不抛错)', async () => { mocks.poolQuery.mockResolvedValue({ rows: [] }); await recordOutboundAuthFailure({ supplierCode: 'SUP_UNKNOWN', reason: 'forbidden' }); const arg = mocks.recordFailure.mock.calls[0][0] as Record; expect(arg.branchCode).toBe('UNKNOWN'); expect(arg.mainBranchCode).toBe('*'); }); }); describe('导入前「出站可用」预检', () => { it('token 正常 ⇒ 放行', async () => { await expect( ensureOutboundAuthForImport({ branchCode: 'BR002', supplierCode: 'SUP37831443' }) ).resolves.toEqual({ ok: true }); expect(mocks.token).toHaveBeenCalledWith('SUP37831443'); }); it('授权失败 ⇒ 本轮不建单(false)+ 台账/通知(异步落盘)', async () => { mocks.token.mockResolvedValue({ kind: 'unavailable', reason: '换取对接 Token 失败(forbidden: 未授权访问该供应商)', }); const result = await ensureOutboundAuthForImport({ branchCode: 'BR002', supplierCode: 'SUP37831443', deliveryDate: '2026-10-22', mainBranchCode: 'BR002', mainOrderCode: 'ORD_WEB_20261022_BR002_0001', }); expect(result.ok).toBe(false); await vi.waitFor(() => expect(mocks.recordFailure).toHaveBeenCalledTimes(1)); const arg = mocks.recordFailure.mock.calls[0][0] as Record; expect(arg.errorCode).toBe('outbound_auth_forbidden'); expect(arg.deliveryDate).toBe('2026-10-22'); await vi.waitFor(() => expect(mocks.notify).toHaveBeenCalledTimes(1)); }); it('集成开关未启用(本地/测试)⇒ 放行,保持旧行为', async () => { mocks.integrationEnabled.mockReturnValue(false); await expect( ensureOutboundAuthForImport({ branchCode: 'BR002', supplierCode: 'SUP37831443' }) ).resolves.toEqual({ ok: true }); expect(mocks.token).not.toHaveBeenCalled(); }); it('未配置凭据(not_configured)不当作授权不一致 ⇒ 放行', async () => { mocks.token.mockResolvedValue({ kind: 'not_configured', reason: '未配置对接凭据' }); await expect( ensureOutboundAuthForImport({ branchCode: 'BR002', supplierCode: 'SUP37831443' }) ).resolves.toEqual({ ok: true }); }); }); describe('接线契约:webhook/token/导入必须接上防护(源码级钉住)', () => { const read = (path: string) => readFileSync(path, 'utf8'); it('webhook 路由:来源守卫 + 出站预检 + 导入后立即推报告', () => { const route = read('src/routes/mainSystemIntegration.ts'); expect(route).toContain('evaluatePushClientIdentity'); expect(route).toContain('recordForeignClientPush'); expect(route).toContain("reason: 'push_client_mismatch'"); expect(route).toContain('ensureOutboundAuthForImport'); expect(route).toContain("reason: 'outbound_auth_unavailable'"); expect(route).toContain('triggerReportPush'); }); it('token 层:授权类失败(401/403/404)挂钩出站告警', () => { const token = read('src/services/mainSystem/token.ts'); expect(token).toContain('scheduleOutboundAuthFailureAlert'); expect(token).toContain('recordOutboundAuthFailure'); expect(token).toContain('status !== 401 && status !== 403 && status !== 404'); }); it('导入成功后立即触发报告推送(拉取通道)', () => { const importer = read('src/services/mainSystemOrderImport.ts'); expect(importer).toContain('triggerReportPush'); }); });