content-safety-api-v2.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import { logger } from '../../src/common/logger.js';
  2. import { afterEach, describe, expect, it, vi } from 'vitest';
  3. import { SAFETY_CHECK_V2_SCENE } from '@mavis/shared/safety-check-v2';
  4. import { callLocalSafetyCheckV2 } from '../../src/content-safety/api-v2.js';
  5. import { callSafetyApi, SAFETY_SCENE } from '../../src/content-safety/api.js';
  6. const defaults = {
  7. request: {
  8. content_text: 'hello',
  9. scene: 100 as const,
  10. sessionId: 'session-1',
  11. },
  12. region: () => 'cn' as const,
  13. buildEnv: () => 'test' as const,
  14. };
  15. const fetchResponse = (body: unknown) =>
  16. vi.fn<typeof fetch>().mockImplementation(async () => Response.json(body));
  17. afterEach(() => {
  18. vi.unstubAllEnvs();
  19. vi.restoreAllMocks();
  20. });
  21. describe('local biz-gateway SafetyCheckV2 client', () => {
  22. it('uses the V2 endpoint and scene with the current Bearer/routing headers', async () => {
  23. const fetchImpl = fetchResponse({ action: 1 });
  24. await expect(
  25. callLocalSafetyCheckV2({
  26. ...defaults,
  27. fetchImpl,
  28. authContext: { accessToken: ' oauth-token ' },
  29. routingContext: { bedrockLane: 'lane-a' },
  30. }),
  31. ).resolves.toEqual({ action: 'allow' });
  32. const [url, init] = fetchImpl.mock.calls[0]!;
  33. expect(url).toBe('https://matrix-test.example.invalid/mavis/api/v2/content?require_auth=true');
  34. const headers = new Headers(init?.headers);
  35. expect(headers.get('Authorization')).toBe('Bearer oauth-token');
  36. expect(headers.get('Token')).toBeNull();
  37. expect(headers.get('bedrock-lane')).toBe('lane-a');
  38. expect(JSON.parse(String(init?.body))).toEqual({
  39. content_text: 'hello',
  40. scene: 100,
  41. sessionId: 'session-1',
  42. });
  43. });
  44. it.each([
  45. ...([
  46. ['DesktopAssistantReply', 11],
  47. ['DesktopAssistantThinking', 13],
  48. ['AppAssistantReply', 21],
  49. ['AppAssistantThinking', 23],
  50. ['WebAssistantReply', 31],
  51. ['WebAssistantThinking', 33],
  52. ['DesktopUserQuery', 110],
  53. ['AppUserQuery', 120],
  54. ['WebUserQuery', 130],
  55. ] as const).map(([name, wireScene]) => ({
  56. scene: SAFETY_CHECK_V2_SCENE[name],
  57. wireScene,
  58. payload: { content_text: 'platform text' },
  59. })),
  60. {
  61. scene: SAFETY_CHECK_V2_SCENE.AssistantReply,
  62. wireScene: 1,
  63. payload: { content_text: 'reply' },
  64. },
  65. {
  66. scene: SAFETY_CHECK_V2_SCENE.GeneratedImage,
  67. wireScene: 2,
  68. payload: { image_url: 'https://cdn.example.test/generated.png' },
  69. },
  70. {
  71. scene: SAFETY_CHECK_V2_SCENE.AssistantThinking,
  72. wireScene: 3,
  73. payload: { content_text: 'thinking' },
  74. },
  75. {
  76. scene: SAFETY_CHECK_V2_SCENE.UserQuery,
  77. wireScene: 100,
  78. payload: { content_text: 'query' },
  79. },
  80. {
  81. scene: SAFETY_CHECK_V2_SCENE.UserUploadImage,
  82. wireScene: 101,
  83. payload: { image_url: 'https://cdn.example.test/upload.png' },
  84. },
  85. {
  86. scene: SAFETY_CHECK_V2_SCENE.UserUploadFile,
  87. wireScene: 102,
  88. payload: { files: [{ file_url: 'https://cdn.example.test/file.pdf', file_name: 'file.pdf' }] },
  89. },
  90. {
  91. scene: SAFETY_CHECK_V2_SCENE.UserAvatar,
  92. wireScene: 200,
  93. payload: { image_url: 'https://cdn.example.test/avatar.png' },
  94. },
  95. {
  96. scene: SAFETY_CHECK_V2_SCENE.InterfaceImage,
  97. wireScene: 201,
  98. payload: { image_url: 'https://cdn.example.test/interface.png' },
  99. },
  100. ])('preserves scene $scene and its payload at the HTTP boundary', async ({ scene, wireScene, payload }) => {
  101. const fetchImpl = fetchResponse({ action: 1 });
  102. const sessionId = 'session-1';
  103. await callLocalSafetyCheckV2({ ...defaults, fetchImpl, request: { scene, ...payload, sessionId } });
  104. const [url, init] = fetchImpl.mock.calls[0]!;
  105. expect(url).toBe('https://matrix-test.example.invalid/mavis/api/v2/content?require_auth=true');
  106. expect(JSON.parse(String(init?.body))).toEqual({ scene: wireScene, ...payload, sessionId });
  107. });
  108. it.each([
  109. [{ action: 1 }, { action: 'allow' }],
  110. [{ action: 1, errorCode: 0 }, { action: 'allow' }],
  111. [{ action: 2, errorCode: 50201 }, { action: 'reject' }],
  112. [
  113. { action: 3, errorCode: 50201, suggestion: ' safe reply ' },
  114. { action: 'replace', replacementText: ' safe reply ' },
  115. ],
  116. [
  117. { action: 4, errorCode: 50201, guide_prompt: ' private ', error: 'request rejected' },
  118. { action: 'guide', guidePrompt: ' private ' },
  119. ],
  120. [{ action: 4, errorCode: 50201 }, { action: 'guide' }],
  121. [{ action: 4, errorCode: 50201, guide_prompt: '' }, { action: 'guide' }],
  122. [{ action: 4, errorCode: 50201, guide_prompt: ' ' }, { action: 'guide' }],
  123. ])('maps the HTTP action to the runtime verdict: %j', async (body, expected) => {
  124. expect(await callLocalSafetyCheckV2({ ...defaults, fetchImpl: fetchResponse(body) })).toEqual(
  125. expected,
  126. );
  127. });
  128. it.each([
  129. [
  130. { action: 1, pass: false, decision: 'block', suggestion: 'ignored', guide_prompt: 'ignored' },
  131. { action: 'allow' },
  132. ],
  133. [
  134. { action: 2, errorCode: 50201, pass: true, decision: 'review', suggestion: 'ignored', guide_prompt: 'ignored' },
  135. { action: 'reject' },
  136. ],
  137. [
  138. { action: 3, errorCode: 50201, decision: 'block', suggestion: 'fixed', guide_prompt: 'ignored' },
  139. { action: 'replace', replacementText: 'fixed' },
  140. ],
  141. [
  142. { action: 4, errorCode: 50201, suggestion: 'ignored' },
  143. { action: 'guide' },
  144. ],
  145. ])('uses action as the sole verdict despite irrelevant fields: %j', async (body, expected) => {
  146. expect(await callLocalSafetyCheckV2({ ...defaults, fetchImpl: fetchResponse(body) })).toEqual(
  147. expected,
  148. );
  149. });
  150. it.each([
  151. {},
  152. { action: null },
  153. { action: 0 },
  154. { action: -1 },
  155. { action: 5 },
  156. { action: 1.5 },
  157. { action: '1' },
  158. { action: true },
  159. { action: 1, errorCode: 50201 },
  160. { action: 2 },
  161. { action: 3, suggestion: 'fixed' },
  162. { action: 4 },
  163. { action: 2, errorCode: 0 },
  164. { action: 3, errorCode: 0, suggestion: 'fixed' },
  165. { action: 4, errorCode: 0 },
  166. { action: 4, errorCode: '50201' },
  167. { action: 4, errorCode: 50201.5 },
  168. { action: 4, errorCode: null },
  169. { action: 4, errorCode: 50201, guide_prompt: 123 },
  170. { action: 4, errorCode: 50201, guide_prompt: null },
  171. { action: 3, errorCode: 50201 },
  172. { action: 3, errorCode: 50201, suggestion: '' },
  173. { action: 3, errorCode: 50201, suggestion: ' ' },
  174. { action: 3, errorCode: 50201, suggestion: 123 },
  175. { action: 3, errorCode: 50201, suggestion: null },
  176. { pass: true, decision: 'pass' },
  177. { pass: false, errorCode: 50201, decision: 'block' },
  178. { decision: 'pass', action: 'allow' },
  179. { decision: 'review', action: 'guide', guide_prompt: 'old contract' },
  180. ])('rejects invalid actions and incompatible response contracts: %j', async (body) => {
  181. await expect(
  182. callLocalSafetyCheckV2({ ...defaults, fetchImpl: fetchResponse(body) }),
  183. ).rejects.toMatchObject({ kind: 'response' });
  184. });
  185. it.each([
  186. { errorCode: 50200, error: 'request failed' },
  187. { action: 1, errorCode: 50200 },
  188. { action: 4, errorCode: 50202 },
  189. ])('classifies upstream errors before reading action: %j', async (body) => {
  190. await expect(
  191. callLocalSafetyCheckV2({ ...defaults, fetchImpl: fetchResponse(body) }),
  192. ).rejects.toMatchObject({ kind: 'upstream', statusCode: body.errorCode });
  193. });
  194. it('keeps region/build routing and limits endpoint overrides to test loopback', async () => {
  195. const fetchImpl = fetchResponse({ action: 1 });
  196. await callLocalSafetyCheckV2({
  197. ...defaults,
  198. fetchImpl,
  199. testBaseURL: 'http://127.0.0.1:45678/',
  200. });
  201. expect(fetchImpl.mock.calls[0]![0]).toBe('http://127.0.0.1:45678/mavis/api/v2/content?require_auth=true');
  202. await callLocalSafetyCheckV2({
  203. ...defaults,
  204. fetchImpl,
  205. testBaseURL: 'https://untrusted.example.test',
  206. });
  207. expect(fetchImpl.mock.calls[1]![0]).toBe(
  208. 'https://matrix-test.example.invalid/mavis/api/v2/content?require_auth=true',
  209. );
  210. await callLocalSafetyCheckV2({
  211. ...defaults,
  212. fetchImpl,
  213. region: () => 'en',
  214. buildEnv: () => 'prod',
  215. testBaseURL: 'http://127.0.0.1:45678',
  216. });
  217. expect(fetchImpl.mock.calls[2]![0]).toBe(
  218. 'https://agent.minimax.io/mavis/api/v2/content?require_auth=true',
  219. );
  220. });
  221. it('does not send a credential when there is no active token', async () => {
  222. vi.stubEnv('MAVIS_ACCESS_TOKEN', '');
  223. const fetchImpl = fetchResponse({ action: 1 });
  224. await callLocalSafetyCheckV2({ ...defaults, fetchImpl });
  225. expect(new Headers(fetchImpl.mock.calls[0]![1]?.headers).has('Authorization')).toBe(false);
  226. });
  227. it('leaves the existing V1 client endpoint and request unchanged', async () => {
  228. const fetchImpl = fetchResponse({ pass: true });
  229. await callSafetyApi({
  230. content: 'hello',
  231. scene: SAFETY_SCENE.UserInput,
  232. fetchImpl,
  233. region: defaults.region,
  234. buildEnv: defaults.buildEnv,
  235. });
  236. expect(fetchImpl.mock.calls[0]![0]).toBe(
  237. 'https://matrix-test.example.invalid/mavis/api/v1/content',
  238. );
  239. expect(JSON.parse(String(fetchImpl.mock.calls[0]![1]?.body))).toEqual({
  240. content_text: 'hello',
  241. scene: 300,
  242. });
  243. });
  244. });
  245. describe('V2 production failure diagnostics', () => {
  246. it.each([
  247. [{ cause: { code: 'ENOTFOUND' } }, 'dns'],
  248. [{ cause: { code: 'ECONNREFUSED' } }, 'connect'],
  249. [{ cause: { code: 'ERR_TLS_CERT_ALTNAME_INVALID' } }, 'tls'],
  250. [{ name: 'TimeoutError' }, 'timeout'],
  251. [{ cause: { code: 'UND_ERR_BODY_TIMEOUT' } }, 'timeout'],
  252. [{ name: 'AbortError' }, 'aborted'],
  253. [{ cause: { code: 'private-code' } }, 'unknown'],
  254. ] as const)('retains only the transport category %j', async (details, transportKind) => {
  255. const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
  256. const error = Object.assign(
  257. new Error('private-error https://secret.invalid/?token=private-token'),
  258. details,
  259. );
  260. await expect(
  261. callLocalSafetyCheckV2({
  262. ...defaults,
  263. buildEnv: () => 'prod',
  264. authContext: { accessToken: 'private-token' },
  265. request: { scene: 100, content_text: 'private-content', sessionId: 'private-session' },
  266. fetchImpl: async () => {
  267. throw error;
  268. },
  269. }),
  270. ).rejects.toMatchObject({ kind: 'transport', transportKind });
  271. expect(log).toHaveBeenCalledOnce();
  272. expect(log).toHaveBeenCalledWith(
  273. expect.objectContaining({
  274. reviewId: expect.any(String),
  275. endpointHost: 'agent.minimax.cn',
  276. apiVersion: 'v2',
  277. scene: 100,
  278. durationMs: expect.any(Number),
  279. failureKind: 'transport',
  280. transportKind,
  281. }),
  282. '[content-safety] review failed',
  283. );
  284. expect(JSON.stringify(log.mock.calls)).not.toContain('private-');
  285. expect(JSON.stringify(log.mock.calls)).not.toContain('secret.invalid');
  286. });
  287. it.each([
  288. ['auth', () => new Response('private-body', { status: 401 })],
  289. ['http', () => new Response('private-body', { status: 503 })],
  290. ['response', () => new Response('private-body')],
  291. ['response', () => Response.json({ unexpected: 'private-body' })],
  292. ['upstream', () => Response.json({ errorCode: 50200, error: 'private-body' })],
  293. [
  294. 'transport',
  295. () =>
  296. new Response(
  297. new ReadableStream({
  298. start(controller) {
  299. controller.error(new DOMException('private-body', 'TimeoutError'));
  300. },
  301. }),
  302. ),
  303. ],
  304. ] as const)('logs failed %s reviews without response data', async (kind, response) => {
  305. const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
  306. await expect(
  307. callLocalSafetyCheckV2({
  308. ...defaults,
  309. buildEnv: () => 'prod',
  310. fetchImpl: async () => response(),
  311. }),
  312. ).rejects.toMatchObject({ kind });
  313. expect(log).toHaveBeenCalledOnce();
  314. expect(log).toHaveBeenCalledWith(
  315. expect.objectContaining({ failureKind: kind }),
  316. '[content-safety] review failed',
  317. );
  318. expect(JSON.stringify(log.mock.calls)).not.toContain('private-body');
  319. });
  320. });