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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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('logs a sanitized upstream response in local test environments', async () => {
  241. const log = vi.spyOn(logger, 'info').mockImplementation(() => {});
  242. const fetchImpl = vi.fn(async () =>
  243. new Response(JSON.stringify({ code: 401, message: 'auth failed' }), {
  244. status: 401,
  245. headers: {
  246. 'Content-Type': 'application/json',
  247. 'Trace-Id': 'trace-content-safety-test',
  248. },
  249. }),
  250. ) as unknown as typeof fetch;
  251. await callSafetyApi({
  252. content: 'must-not-appear-in-log',
  253. scene: SAFETY_SCENE.UserInput,
  254. authContext: { accessToken: 'must-not-appear-token' },
  255. fetchImpl,
  256. region,
  257. buildEnv,
  258. });
  259. expect(log).toHaveBeenCalledWith(
  260. expect.objectContaining({
  261. url: 'https://matrix-test.example.invalid/mavis/api/v1/content',
  262. method: 'POST',
  263. status: 401,
  264. scene: SAFETY_SCENE.UserInput,
  265. hasBearer: true,
  266. durationMs: expect.any(Number),
  267. upstreamTraceId: 'trace-content-safety-test',
  268. }),
  269. '[content-safety] upstream response',
  270. );
  271. const serialized = JSON.stringify(log.mock.calls);
  272. expect(serialized).not.toContain('must-not-appear-token');
  273. expect(serialized).not.toContain('must-not-appear-in-log');
  274. });
  275. it('does not emit the temporary upstream diagnostic in production', async () => {
  276. const log = vi.spyOn(logger, 'info').mockImplementation(() => {});
  277. await callSafetyApi({
  278. content: 'hello',
  279. scene: SAFETY_SCENE.UserInput,
  280. authContext: { accessToken: 'shared-oauth-token' },
  281. fetchImpl: vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch,
  282. region,
  283. buildEnv: () => 'prod',
  284. });
  285. expect(log).not.toHaveBeenCalled();
  286. });
  287. it('uses a loopback test endpoint only for test builds', async () => {
  288. const testFetch = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  289. await callSafetyApi({
  290. content: 'hello',
  291. scene: SAFETY_SCENE.UserInput,
  292. fetchImpl: testFetch,
  293. region,
  294. buildEnv,
  295. testBaseURL: 'http://127.0.0.1:43123/',
  296. });
  297. expect(testFetch).toHaveBeenCalledWith(
  298. 'http://127.0.0.1:43123/mavis/api/v1/content',
  299. expect.any(Object),
  300. );
  301. const prodFetch = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  302. await callSafetyApi({
  303. content: 'hello',
  304. scene: SAFETY_SCENE.UserInput,
  305. fetchImpl: prodFetch,
  306. region,
  307. buildEnv: () => 'prod',
  308. testBaseURL: 'http://127.0.0.1:43123',
  309. });
  310. expect(prodFetch).toHaveBeenCalledWith(
  311. 'https://agent.minimax.cn/mavis/api/v1/content',
  312. expect.any(Object),
  313. );
  314. });
  315. it('ignores non-loopback test endpoint overrides', async () => {
  316. const fetchImpl = vi.fn(async () => jsonResponse({ pass: true })) as unknown as typeof fetch;
  317. await callSafetyApi({
  318. content: 'hello',
  319. scene: SAFETY_SCENE.UserInput,
  320. fetchImpl,
  321. region,
  322. buildEnv,
  323. testBaseURL: 'https://example.com',
  324. });
  325. expect(fetchImpl).toHaveBeenCalledWith(
  326. 'https://matrix-test.example.invalid/mavis/api/v1/content',
  327. expect.any(Object),
  328. );
  329. });
  330. });
  331. describe('reviewBlocks shared fail-policy predicate', () => {
  332. it('blocks rejected + local_error, degrade-passes api_error, allows a clean pass', () => {
  333. expect(reviewBlocks({ pass: false, errorKind: 'rejected' })).toBe(true);
  334. expect(reviewBlocks({ pass: false, errorKind: 'local_error' })).toBe(true);
  335. expect(reviewBlocks({ pass: false, errorKind: 'auth_error' })).toBe(true);
  336. expect(reviewBlocks({ pass: false, errorKind: 'api_error' })).toBe(false);
  337. expect(reviewBlocks({ pass: true })).toBe(false);
  338. });
  339. });
  340. describe('createContentSafetyChecker airtight contract', () => {
  341. it.each([401, 403])(
  342. 'recovers HTTP %i once with a new token and preserves the review payload',
  343. async (status) => {
  344. let accessToken = 'old-token';
  345. const fetchImpl = vi
  346. .fn<typeof fetch>()
  347. .mockResolvedValueOnce(new Response('{}', { status }))
  348. .mockResolvedValueOnce(jsonResponse({ pass: true }));
  349. const authContextInvalidator = vi.fn(async (rejected?: string) => {
  350. expect(rejected).toBe('old-token');
  351. accessToken = 'new-token';
  352. });
  353. const check = createContentSafetyChecker({
  354. authContextGetter: () => ({ accessToken }),
  355. authContextInvalidator,
  356. fetchImpl,
  357. region,
  358. buildEnv,
  359. });
  360. expect(await check('review this', SAFETY_SCENE.UserInput)).toMatchObject({ pass: true });
  361. expect(authContextInvalidator).toHaveBeenCalledOnce();
  362. expect(fetchImpl).toHaveBeenCalledTimes(2);
  363. expect(new Headers(fetchImpl.mock.calls[0]?.[1]?.headers).get('Authorization')).toBe(
  364. 'Bearer old-token',
  365. );
  366. expect(new Headers(fetchImpl.mock.calls[1]?.[1]?.headers).get('Authorization')).toBe(
  367. 'Bearer new-token',
  368. );
  369. expect(fetchImpl.mock.calls[1]?.[1]?.body).toBe(fetchImpl.mock.calls[0]?.[1]?.body);
  370. },
  371. );
  372. it.each(['unchanged', 'logged-out', 'throws'] as const)(
  373. 'keeps auth failures closed when recovery is %s',
  374. async (mode) => {
  375. let accessToken: string | undefined = 'old-token';
  376. const fetchImpl = vi
  377. .fn<typeof fetch>()
  378. .mockResolvedValue(new Response('{}', { status: 401 }));
  379. const check = createContentSafetyChecker({
  380. authContextGetter: () => (accessToken ? { accessToken } : undefined),
  381. authContextInvalidator: async () => {
  382. if (mode === 'logged-out') accessToken = undefined;
  383. if (mode === 'throws') throw new Error('refresh unavailable');
  384. },
  385. fetchImpl,
  386. region,
  387. buildEnv,
  388. });
  389. const result = await check('review this', SAFETY_SCENE.UserInput);
  390. expect(result).toMatchObject({ pass: false, errorKind: 'auth_error' });
  391. expect(reviewBlocks(result)).toBe(true);
  392. expect(fetchImpl).toHaveBeenCalledOnce();
  393. },
  394. );
  395. it('does not loop when the new token is also rejected', async () => {
  396. let accessToken = 'old-token';
  397. const fetchImpl = vi
  398. .fn<typeof fetch>()
  399. .mockImplementation(async () => new Response('{}', { status: 401 }));
  400. const authContextInvalidator = vi.fn(async () => {
  401. accessToken = 'new-token';
  402. });
  403. const check = createContentSafetyChecker({
  404. authContextGetter: () => ({ accessToken }),
  405. authContextInvalidator,
  406. fetchImpl,
  407. region,
  408. buildEnv,
  409. });
  410. expect(await check('review this', SAFETY_SCENE.UserInput)).toMatchObject({
  411. pass: false,
  412. errorKind: 'auth_error',
  413. });
  414. expect(fetchImpl).toHaveBeenCalledTimes(2);
  415. expect(authContextInvalidator).toHaveBeenCalledOnce();
  416. });
  417. it('does not refresh anonymous or non-auth review failures', async () => {
  418. const authContextInvalidator = vi.fn();
  419. for (const [token, status] of [
  420. [undefined, 401],
  421. ['token', 400],
  422. ['token', 500],
  423. ['token', 200],
  424. ] as const) {
  425. const check = createContentSafetyChecker({
  426. authContextGetter: () => (token ? { accessToken: token } : undefined),
  427. authContextInvalidator,
  428. fetchImpl: async () => new Response(JSON.stringify({ pass: false }), { status }),
  429. region,
  430. buildEnv,
  431. });
  432. await check('review this', SAFETY_SCENE.UserInput);
  433. }
  434. expect(authContextInvalidator).not.toHaveBeenCalled();
  435. });
  436. it('resolves to a local_error result instead of throwing when the auth getter throws', async () => {
  437. const checker = createContentSafetyChecker({
  438. authContextGetter: () => {
  439. throw new Error('auth resolution blew up');
  440. },
  441. fetchImpl: (async () => jsonResponse({ pass: true })) as unknown as typeof fetch,
  442. region,
  443. buildEnv,
  444. });
  445. const result = await checker('hello', SAFETY_SCENE.ConfigField);
  446. // The checker never rejects: callers can trust `errorKind` + `reviewBlocks`
  447. // and never need their own try/catch.
  448. expect(result.pass).toBe(false);
  449. expect(result.errorKind).toBe('local_error');
  450. expect(reviewBlocks(result)).toBe(true);
  451. });
  452. });