content-safety-api-fail-policy.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. // Standalone client fail-policy tests; the desktop HTTP route is outside this distribution.
  2. import { afterEach, describe, expect, it, vi } from 'vitest';
  3. import {
  4. callSafetyApi,
  5. createContentSafetyChecker,
  6. reviewBlocks,
  7. SAFETY_SCENE,
  8. } from '../../src/content-safety/api.js';
  9. import { logger } from '../../src/common/logger.js';
  10. const region = () => 'cn' as const;
  11. const buildEnv = () => 'test' as const;
  12. const originalBuildEnv = process.env.MAVIS_BUILD_ENV;
  13. afterEach(() => {
  14. vi.restoreAllMocks();
  15. if (originalBuildEnv === undefined) delete process.env.MAVIS_BUILD_ENV;
  16. else process.env.MAVIS_BUILD_ENV = originalBuildEnv;
  17. });
  18. function jsonResponse(body: unknown, status = 200): Response {
  19. return new Response(JSON.stringify(body), {
  20. status,
  21. headers: { 'Content-Type': 'application/json' },
  22. });
  23. }
  24. describe('callSafetyApi fail-policy classification', () => {
  25. it('returns local_error when fetch throws (offline / DNS / refused)', async () => {
  26. const fetchImpl = vi.fn(async () => {
  27. throw new Error('network down');
  28. }) as unknown as typeof fetch;
  29. const result = await callSafetyApi({
  30. content: 'hello',
  31. scene: SAFETY_SCENE.UserInput,
  32. fetchImpl,
  33. region,
  34. buildEnv,
  35. });
  36. expect(result.pass).toBe(false);
  37. expect(result.errorKind).toBe('local_error');
  38. });
  39. it('returns api_error when the gateway responds with a 5xx', async () => {
  40. const fetchImpl = vi.fn(async () =>
  41. jsonResponse({ error: 'upstream exploded' }, 502),
  42. ) as unknown as typeof fetch;
  43. const result = await callSafetyApi({
  44. content: 'hello',
  45. scene: SAFETY_SCENE.UserInput,
  46. fetchImpl,
  47. region,
  48. buildEnv,
  49. });
  50. expect(result.pass).toBe(false);
  51. expect(result.errorKind).toBe('api_error');
  52. });
  53. it('distinguishes expired auth from other fail-closed 4xx responses', async () => {
  54. for (const status of [401, 403]) {
  55. const fetchImpl = vi.fn(async () =>
  56. jsonResponse({ error: 'unauthorized' }, status),
  57. ) as unknown as typeof fetch;
  58. const result = await callSafetyApi({
  59. content: 'hello',
  60. scene: SAFETY_SCENE.UserInput,
  61. fetchImpl,
  62. region,
  63. buildEnv,
  64. });
  65. // A missing / expired token (401/403) or a bad request (4xx) is NOT a
  66. // gateway degradation: there is no valid verdict on our side, so we fail
  67. // closed. Classifying it as api_error would let an unauthenticated user
  68. // bypass every content gate.
  69. expect(result.pass).toBe(false);
  70. expect(result.errorKind).toBe('auth_error');
  71. }
  72. const badRequest = await callSafetyApi({
  73. content: 'hello',
  74. scene: SAFETY_SCENE.UserInput,
  75. fetchImpl: vi.fn(async () => jsonResponse({ error: 'bad request' }, 400)) as unknown as typeof fetch,
  76. region,
  77. buildEnv,
  78. });
  79. expect(badRequest.errorKind).toBe('local_error');
  80. });
  81. it('returns local_error when the gateway returns a non-JSON 2xx body', async () => {
  82. const fetchImpl = vi.fn(
  83. async () => new Response('not json at all', { status: 200 }),
  84. ) as unknown as typeof fetch;
  85. const result = await callSafetyApi({
  86. content: 'hello',
  87. scene: SAFETY_SCENE.UserInput,
  88. fetchImpl,
  89. region,
  90. buildEnv,
  91. });
  92. expect(result.pass).toBe(false);
  93. expect(result.errorKind).toBe('local_error');
  94. });
  95. it('returns local_error when the 2xx JSON has no boolean pass/safe field', async () => {
  96. const fetchImpl = vi.fn(async () =>
  97. jsonResponse({ reason: 'weird shape' }),
  98. ) as unknown as typeof fetch;
  99. const result = await callSafetyApi({
  100. content: 'hello',
  101. scene: SAFETY_SCENE.UserInput,
  102. fetchImpl,
  103. region,
  104. buildEnv,
  105. });
  106. expect(result.pass).toBe(false);
  107. expect(result.errorKind).toBe('local_error');
  108. });
  109. it('returns api_error when the gateway explicitly reports service-unavailable (50200)', async () => {
  110. const fetchImpl = vi.fn(async () =>
  111. jsonResponse({ pass: false, errorCode: 50200 }),
  112. ) as unknown as typeof fetch;
  113. const result = await callSafetyApi({
  114. content: 'hello',
  115. scene: SAFETY_SCENE.UserInput,
  116. fetchImpl,
  117. region,
  118. buildEnv,
  119. });
  120. expect(result.pass).toBe(false);
  121. expect(result.errorKind).toBe('api_error');
  122. });
  123. it('returns rejected when the gateway reviews and rejects the content', async () => {
  124. const fetchImpl = vi.fn(async () =>
  125. jsonResponse({ pass: false, reason: 'blocked by policy' }),
  126. ) as unknown as typeof fetch;
  127. const result = await callSafetyApi({
  128. content: 'bad stuff',
  129. scene: SAFETY_SCENE.UserInput,
  130. fetchImpl,
  131. region,
  132. buildEnv,
  133. });
  134. expect(result.pass).toBe(false);
  135. expect(result.errorKind).toBe('rejected');
  136. });
  137. it('passes through a clean approval with no errorKind', async () => {
  138. const fetchImpl = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  139. const result = await callSafetyApi({
  140. content: 'hello',
  141. scene: SAFETY_SCENE.UserInput,
  142. fetchImpl,
  143. region,
  144. buildEnv,
  145. });
  146. expect(result.pass).toBe(true);
  147. expect(result.errorKind).toBeUndefined();
  148. });
  149. it('sends a private object key without a client URL', async () => {
  150. const fetchImpl = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  151. await callSafetyApi({
  152. content: '',
  153. scene: SAFETY_SCENE.UserInput,
  154. attachments: [
  155. {
  156. objectKey: '11111111-2222-3333-4444-555555555555',
  157. fileName: 'screen.png',
  158. },
  159. ],
  160. fetchImpl,
  161. region,
  162. buildEnv,
  163. });
  164. expect(fetchImpl).toHaveBeenCalledWith(
  165. 'https://matrix-test.example.invalid/mavis/api/v1/content?require_auth=true',
  166. expect.anything(),
  167. );
  168. const init = (fetchImpl as unknown as ReturnType<typeof vi.fn>).mock.calls[0]?.[1] as RequestInit;
  169. expect(JSON.parse(String(init.body))).toMatchObject({
  170. files: [
  171. {
  172. object_key: '11111111-2222-3333-4444-555555555555',
  173. file_name: 'screen.png',
  174. },
  175. ],
  176. });
  177. });
  178. it.each([
  179. undefined,
  180. [{ fileUrl: 'https://cdn.hailuoai.com/legacy.png', fileName: 'legacy.png' }],
  181. ])('preserves the auth policy for legacy text and URL requests: %j', async (attachments) => {
  182. const fetchImpl = vi.fn(async () => jsonResponse({ pass: true }));
  183. await callSafetyApi({
  184. content: 'hello',
  185. scene: SAFETY_SCENE.UserInput,
  186. attachments,
  187. fetchImpl,
  188. region,
  189. buildEnv,
  190. });
  191. expect(fetchImpl).toHaveBeenCalledWith(
  192. 'https://matrix-test.example.invalid/mavis/api/v1/content',
  193. expect.anything(),
  194. );
  195. });
  196. it('sends the managed lane only for non-prod content-safety calls', async () => {
  197. const fetchImpl = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  198. await callSafetyApi({
  199. content: 'hello',
  200. scene: SAFETY_SCENE.UserInput,
  201. authContext: { accessToken: 'jwt-token' },
  202. routingContext: { bedrockLane: 'lane-a' },
  203. fetchImpl,
  204. region,
  205. buildEnv,
  206. });
  207. const requestInit = (fetchImpl as unknown as ReturnType<typeof vi.fn>).mock.calls[0]?.[
  208. 1
  209. ] as RequestInit;
  210. expect(new Headers(requestInit.headers).get('bedrock-lane')).toBe('lane-a');
  211. const prodFetch = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  212. await callSafetyApi({
  213. content: 'hello',
  214. scene: SAFETY_SCENE.UserInput,
  215. routingContext: { bedrockLane: 'lane-a' },
  216. fetchImpl: prodFetch,
  217. region,
  218. buildEnv: () => 'prod',
  219. });
  220. const prodInit = (prodFetch as unknown as ReturnType<typeof vi.fn>).mock.calls[0]?.[1] as RequestInit;
  221. expect(new Headers(prodInit.headers).get('bedrock-lane')).toBeNull();
  222. });
  223. it('sends Shared OAuth access tokens as a Bearer credential', async () => {
  224. const fetchImpl = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  225. await callSafetyApi({
  226. content: 'hello',
  227. scene: SAFETY_SCENE.UserInput,
  228. authContext: { accessToken: 'shared-oauth-token' },
  229. fetchImpl,
  230. region,
  231. buildEnv,
  232. });
  233. const requestInit = (fetchImpl as unknown as ReturnType<typeof vi.fn>).mock.calls[0]?.[
  234. 1
  235. ] as RequestInit;
  236. const headers = new Headers(requestInit.headers);
  237. expect(headers.get('Authorization')).toBe('Bearer shared-oauth-token');
  238. expect(headers.get('Token')).toBeNull();
  239. });
  240. it.each([
  241. ['auth', () => jsonResponse({ error: 'private-response' }, 401), 401],
  242. ['http', () => jsonResponse({ error: 'private-response' }, 503), 503],
  243. ['response', () => new Response('private-response'), 200],
  244. ['response', () => jsonResponse(null), 200],
  245. ['response', () => jsonResponse({ secret: 'private-response' }), 200],
  246. [
  247. 'transport',
  248. () => {
  249. throw new TypeError('private-error https://secret.invalid/?token=private-token', {
  250. cause: { code: 'ENOTFOUND' },
  251. });
  252. },
  253. undefined,
  254. ],
  255. [
  256. 'transport',
  257. () =>
  258. new Response(
  259. new ReadableStream({
  260. start(controller) {
  261. controller.error(new DOMException('private-error', 'TimeoutError'));
  262. },
  263. }),
  264. ),
  265. 200,
  266. ],
  267. ] as const)(
  268. 'logs redacted %s failures in production',
  269. async (failureKind, response, statusCode) => {
  270. const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
  271. const result = await callSafetyApi({
  272. content: 'private-content',
  273. scene: SAFETY_SCENE.UserInput,
  274. authContext: { accessToken: 'private-token' },
  275. attachments: [{ fileUrl: 'https://secret.invalid/private-file', fileName: 'private-name' }],
  276. fetchImpl: async () => response(),
  277. region,
  278. buildEnv: () => 'prod',
  279. });
  280. expect(result.pass).toBe(false);
  281. expect(reviewBlocks(result)).toBe(failureKind !== 'http');
  282. expect(log).toHaveBeenCalledOnce();
  283. expect(log).toHaveBeenCalledWith(
  284. expect.objectContaining({
  285. reviewId: expect.any(String),
  286. endpointHost: 'agent.minimax.cn',
  287. apiVersion: 'v1',
  288. scene: SAFETY_SCENE.UserInput,
  289. durationMs: expect.any(Number),
  290. failureKind,
  291. ...(statusCode === undefined ? { transportKind: 'dns' } : { statusCode }),
  292. }),
  293. '[content-safety] review failed',
  294. );
  295. const serialized = JSON.stringify(log.mock.calls);
  296. expect(serialized).not.toContain('private-');
  297. expect(serialized).not.toContain('secret.invalid');
  298. expect(serialized).not.toContain('https://');
  299. },
  300. );
  301. it('does not log successful reviews in production', async () => {
  302. const log = vi.spyOn(logger, 'warn').mockImplementation(() => {});
  303. await callSafetyApi({
  304. content: 'hello',
  305. scene: SAFETY_SCENE.UserInput,
  306. authContext: { accessToken: 'shared-oauth-token' },
  307. fetchImpl: vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch,
  308. region,
  309. buildEnv: () => 'prod',
  310. });
  311. expect(log).not.toHaveBeenCalled();
  312. });
  313. it('uses a loopback test endpoint only for test builds', async () => {
  314. const testFetch = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  315. await callSafetyApi({
  316. content: 'hello',
  317. scene: SAFETY_SCENE.UserInput,
  318. fetchImpl: testFetch,
  319. region,
  320. buildEnv,
  321. testBaseURL: 'http://127.0.0.1:43123/',
  322. });
  323. expect(testFetch).toHaveBeenCalledWith(
  324. 'http://127.0.0.1:43123/mavis/api/v1/content',
  325. expect.any(Object),
  326. );
  327. const prodFetch = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  328. await callSafetyApi({
  329. content: 'hello',
  330. scene: SAFETY_SCENE.UserInput,
  331. fetchImpl: prodFetch,
  332. region,
  333. buildEnv: () => 'prod',
  334. testBaseURL: 'http://127.0.0.1:43123',
  335. });
  336. expect(prodFetch).toHaveBeenCalledWith(
  337. 'https://agent.minimax.cn/mavis/api/v1/content',
  338. expect.any(Object),
  339. );
  340. });
  341. it('ignores non-loopback test endpoint overrides', async () => {
  342. const fetchImpl = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  343. await callSafetyApi({
  344. content: 'hello',
  345. scene: SAFETY_SCENE.UserInput,
  346. fetchImpl,
  347. region,
  348. buildEnv,
  349. testBaseURL: 'https://example.com',
  350. });
  351. expect(fetchImpl).toHaveBeenCalledWith(
  352. 'https://matrix-test.example.invalid/mavis/api/v1/content',
  353. expect.any(Object),
  354. );
  355. });
  356. });
  357. describe('reviewBlocks shared fail-policy predicate', () => {
  358. it('blocks rejected + local_error, degrade-passes api_error, allows a clean pass', () => {
  359. expect(reviewBlocks({ pass: false, errorKind: 'rejected' })).toBe(true);
  360. expect(reviewBlocks({ pass: false, errorKind: 'local_error' })).toBe(true);
  361. expect(reviewBlocks({ pass: false, errorKind: 'auth_error' })).toBe(true);
  362. expect(reviewBlocks({ pass: false, errorKind: 'api_error' })).toBe(false);
  363. expect(reviewBlocks({ pass: true })).toBe(false);
  364. });
  365. });
  366. describe('createContentSafetyChecker airtight contract', () => {
  367. it.each([401, 403])(
  368. 'recovers HTTP %i once with a new token and preserves the review payload',
  369. async (status) => {
  370. let accessToken = 'old-token';
  371. const fetchImpl = vi
  372. .fn<typeof fetch>()
  373. .mockResolvedValueOnce(new Response('{}', { status }))
  374. .mockResolvedValueOnce(jsonResponse({ pass: true }));
  375. const authContextInvalidator = vi.fn(async (rejected?: string) => {
  376. expect(rejected).toBe('old-token');
  377. accessToken = 'new-token';
  378. });
  379. const check = createContentSafetyChecker({
  380. authContextGetter: () => ({ accessToken }),
  381. authContextInvalidator,
  382. fetchImpl,
  383. region,
  384. buildEnv,
  385. });
  386. expect(await check('review this', SAFETY_SCENE.UserInput)).toMatchObject({ pass: true });
  387. expect(authContextInvalidator).toHaveBeenCalledOnce();
  388. expect(fetchImpl).toHaveBeenCalledTimes(2);
  389. expect(new Headers(fetchImpl.mock.calls[0]?.[1]?.headers).get('Authorization')).toBe(
  390. 'Bearer old-token',
  391. );
  392. expect(new Headers(fetchImpl.mock.calls[1]?.[1]?.headers).get('Authorization')).toBe(
  393. 'Bearer new-token',
  394. );
  395. expect(fetchImpl.mock.calls[1]?.[1]?.body).toBe(fetchImpl.mock.calls[0]?.[1]?.body);
  396. },
  397. );
  398. it.each(['unchanged', 'logged-out', 'throws'] as const)(
  399. 'keeps auth failures closed when recovery is %s',
  400. async (mode) => {
  401. let accessToken: string | undefined = 'old-token';
  402. const fetchImpl = vi
  403. .fn<typeof fetch>()
  404. .mockResolvedValue(new Response('{}', { status: 401 }));
  405. const check = createContentSafetyChecker({
  406. authContextGetter: () => (accessToken ? { accessToken } : undefined),
  407. authContextInvalidator: async () => {
  408. if (mode === 'logged-out') accessToken = undefined;
  409. if (mode === 'throws') throw new Error('refresh unavailable');
  410. },
  411. fetchImpl,
  412. region,
  413. buildEnv,
  414. });
  415. const result = await check('review this', SAFETY_SCENE.UserInput);
  416. expect(result).toMatchObject({ pass: false, errorKind: 'auth_error' });
  417. expect(reviewBlocks(result)).toBe(true);
  418. expect(fetchImpl).toHaveBeenCalledOnce();
  419. },
  420. );
  421. it('does not loop when the new token is also rejected', async () => {
  422. let accessToken = 'old-token';
  423. const fetchImpl = vi
  424. .fn<typeof fetch>()
  425. .mockImplementation(async () => new Response('{}', { status: 401 }));
  426. const authContextInvalidator = vi.fn(async () => {
  427. accessToken = 'new-token';
  428. });
  429. const check = createContentSafetyChecker({
  430. authContextGetter: () => ({ accessToken }),
  431. authContextInvalidator,
  432. fetchImpl,
  433. region,
  434. buildEnv,
  435. });
  436. expect(await check('review this', SAFETY_SCENE.UserInput)).toMatchObject({
  437. pass: false,
  438. errorKind: 'auth_error',
  439. });
  440. expect(fetchImpl).toHaveBeenCalledTimes(2);
  441. expect(authContextInvalidator).toHaveBeenCalledOnce();
  442. });
  443. it('does not refresh anonymous or non-auth review failures', async () => {
  444. const authContextInvalidator = vi.fn();
  445. for (const [token, status] of [
  446. [undefined, 401],
  447. ['token', 400],
  448. ['token', 500],
  449. ['token', 200],
  450. ] as const) {
  451. const check = createContentSafetyChecker({
  452. authContextGetter: () => (token ? { accessToken: token } : undefined),
  453. authContextInvalidator,
  454. fetchImpl: async () => new Response(JSON.stringify({ pass: false }), { status }),
  455. region,
  456. buildEnv,
  457. });
  458. await check('review this', SAFETY_SCENE.UserInput);
  459. }
  460. expect(authContextInvalidator).not.toHaveBeenCalled();
  461. });
  462. it('resolves to a local_error result instead of throwing when the auth getter throws', async () => {
  463. const checker = createContentSafetyChecker({
  464. authContextGetter: () => {
  465. throw new Error('auth resolution blew up');
  466. },
  467. fetchImpl: (async () => jsonResponse({ pass: true })) as unknown as typeof fetch,
  468. region,
  469. buildEnv,
  470. });
  471. const result = await checker('hello', SAFETY_SCENE.ConfigField);
  472. // The checker never rejects: callers can trust `errorKind` + `reviewBlocks`
  473. // and never need their own try/catch.
  474. expect(result.pass).toBe(false);
  475. expect(result.errorKind).toBe('local_error');
  476. expect(reviewBlocks(result)).toBe(true);
  477. });
  478. });