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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import { afterEach, describe, expect, it, vi } from 'vitest';
  2. import { SAFETY_CHECK_V2_SCENE } from '@mavis/shared/safety-check-v2';
  3. import { callLocalSafetyCheckV2 } from '../../src/content-safety/api-v2.js';
  4. import { callSafetyApi, SAFETY_SCENE } from '../../src/content-safety/api.js';
  5. const defaults = {
  6. request: {
  7. content_text: 'hello',
  8. scene: 100 as const,
  9. sessionId: 'session-1',
  10. },
  11. region: () => 'cn' as const,
  12. buildEnv: () => 'test' as const,
  13. };
  14. const fetchResponse = (body: unknown) =>
  15. vi.fn<typeof fetch>().mockImplementation(async () => Response.json(body));
  16. afterEach(() => vi.unstubAllEnvs());
  17. describe('local biz-gateway SafetyCheckV2 client', () => {
  18. it('uses the V2 endpoint and scene with the current Bearer/routing headers', async () => {
  19. const fetchImpl = fetchResponse({ action: 1 });
  20. await expect(
  21. callLocalSafetyCheckV2({
  22. ...defaults,
  23. fetchImpl,
  24. authContext: { accessToken: ' oauth-token ' },
  25. routingContext: { bedrockLane: 'lane-a' },
  26. }),
  27. ).resolves.toEqual({ action: 'allow' });
  28. const [url, init] = fetchImpl.mock.calls[0]!;
  29. expect(url).toBe('https://matrix-test.example.invalid/mavis/api/v2/content?require_auth=true');
  30. const headers = new Headers(init?.headers);
  31. expect(headers.get('Authorization')).toBe('Bearer oauth-token');
  32. expect(headers.get('Token')).toBeNull();
  33. expect(headers.get('bedrock-lane')).toBe('lane-a');
  34. expect(JSON.parse(String(init?.body))).toEqual({
  35. content_text: 'hello',
  36. scene: 100,
  37. sessionId: 'session-1',
  38. });
  39. });
  40. it.each([
  41. ...([
  42. ['DesktopAssistantReply', 11],
  43. ['DesktopAssistantThinking', 13],
  44. ['AppAssistantReply', 21],
  45. ['AppAssistantThinking', 23],
  46. ['WebAssistantReply', 31],
  47. ['WebAssistantThinking', 33],
  48. ['DesktopUserQuery', 110],
  49. ['AppUserQuery', 120],
  50. ['WebUserQuery', 130],
  51. ] as const).map(([name, wireScene]) => ({
  52. scene: SAFETY_CHECK_V2_SCENE[name],
  53. wireScene,
  54. payload: { content_text: 'platform text' },
  55. })),
  56. {
  57. scene: SAFETY_CHECK_V2_SCENE.AssistantReply,
  58. wireScene: 1,
  59. payload: { content_text: 'reply' },
  60. },
  61. {
  62. scene: SAFETY_CHECK_V2_SCENE.GeneratedImage,
  63. wireScene: 2,
  64. payload: { image_url: 'https://cdn.example.test/generated.png' },
  65. },
  66. {
  67. scene: SAFETY_CHECK_V2_SCENE.AssistantThinking,
  68. wireScene: 3,
  69. payload: { content_text: 'thinking' },
  70. },
  71. {
  72. scene: SAFETY_CHECK_V2_SCENE.UserQuery,
  73. wireScene: 100,
  74. payload: { content_text: 'query' },
  75. },
  76. {
  77. scene: SAFETY_CHECK_V2_SCENE.UserUploadImage,
  78. wireScene: 101,
  79. payload: { image_url: 'https://cdn.example.test/upload.png' },
  80. },
  81. {
  82. scene: SAFETY_CHECK_V2_SCENE.UserUploadFile,
  83. wireScene: 102,
  84. payload: { files: [{ file_url: 'https://cdn.example.test/file.pdf', file_name: 'file.pdf' }] },
  85. },
  86. {
  87. scene: SAFETY_CHECK_V2_SCENE.UserAvatar,
  88. wireScene: 200,
  89. payload: { image_url: 'https://cdn.example.test/avatar.png' },
  90. },
  91. {
  92. scene: SAFETY_CHECK_V2_SCENE.InterfaceImage,
  93. wireScene: 201,
  94. payload: { image_url: 'https://cdn.example.test/interface.png' },
  95. },
  96. ])('preserves scene $scene and its payload at the HTTP boundary', async ({ scene, wireScene, payload }) => {
  97. const fetchImpl = fetchResponse({ action: 1 });
  98. const sessionId = 'session-1';
  99. await callLocalSafetyCheckV2({ ...defaults, fetchImpl, request: { scene, ...payload, sessionId } });
  100. const [url, init] = fetchImpl.mock.calls[0]!;
  101. expect(url).toBe('https://matrix-test.example.invalid/mavis/api/v2/content?require_auth=true');
  102. expect(JSON.parse(String(init?.body))).toEqual({ scene: wireScene, ...payload, sessionId });
  103. });
  104. it.each([
  105. [{ action: 1 }, { action: 'allow' }],
  106. [{ action: 1, errorCode: 0 }, { action: 'allow' }],
  107. [{ action: 2, errorCode: 50201 }, { action: 'reject' }],
  108. [
  109. { action: 3, errorCode: 50201, suggestion: ' safe reply ' },
  110. { action: 'replace', replacementText: ' safe reply ' },
  111. ],
  112. [
  113. { action: 4, errorCode: 50201, guide_prompt: ' private ', error: 'request rejected' },
  114. { action: 'guide', guidePrompt: ' private ' },
  115. ],
  116. [{ action: 4, errorCode: 50201 }, { action: 'guide' }],
  117. [{ action: 4, errorCode: 50201, guide_prompt: '' }, { action: 'guide' }],
  118. [{ action: 4, errorCode: 50201, guide_prompt: ' ' }, { action: 'guide' }],
  119. ])('maps the HTTP action to the runtime verdict: %j', async (body, expected) => {
  120. expect(await callLocalSafetyCheckV2({ ...defaults, fetchImpl: fetchResponse(body) })).toEqual(
  121. expected,
  122. );
  123. });
  124. it.each([
  125. [
  126. { action: 1, pass: false, decision: 'block', suggestion: 'ignored', guide_prompt: 'ignored' },
  127. { action: 'allow' },
  128. ],
  129. [
  130. { action: 2, errorCode: 50201, pass: true, decision: 'review', suggestion: 'ignored', guide_prompt: 'ignored' },
  131. { action: 'reject' },
  132. ],
  133. [
  134. { action: 3, errorCode: 50201, decision: 'block', suggestion: 'fixed', guide_prompt: 'ignored' },
  135. { action: 'replace', replacementText: 'fixed' },
  136. ],
  137. [
  138. { action: 4, errorCode: 50201, suggestion: 'ignored' },
  139. { action: 'guide' },
  140. ],
  141. ])('uses action as the sole verdict despite irrelevant fields: %j', async (body, expected) => {
  142. expect(await callLocalSafetyCheckV2({ ...defaults, fetchImpl: fetchResponse(body) })).toEqual(
  143. expected,
  144. );
  145. });
  146. it.each([
  147. {},
  148. { action: null },
  149. { action: 0 },
  150. { action: -1 },
  151. { action: 5 },
  152. { action: 1.5 },
  153. { action: '1' },
  154. { action: true },
  155. { action: 1, errorCode: 50201 },
  156. { action: 2 },
  157. { action: 3, suggestion: 'fixed' },
  158. { action: 4 },
  159. { action: 2, errorCode: 0 },
  160. { action: 3, errorCode: 0, suggestion: 'fixed' },
  161. { action: 4, errorCode: 0 },
  162. { action: 4, errorCode: '50201' },
  163. { action: 4, errorCode: 50201.5 },
  164. { action: 4, errorCode: null },
  165. { action: 4, errorCode: 50201, guide_prompt: 123 },
  166. { action: 4, errorCode: 50201, guide_prompt: null },
  167. { action: 3, errorCode: 50201 },
  168. { action: 3, errorCode: 50201, suggestion: '' },
  169. { action: 3, errorCode: 50201, suggestion: ' ' },
  170. { action: 3, errorCode: 50201, suggestion: 123 },
  171. { action: 3, errorCode: 50201, suggestion: null },
  172. { pass: true, decision: 'pass' },
  173. { pass: false, errorCode: 50201, decision: 'block' },
  174. { decision: 'pass', action: 'allow' },
  175. { decision: 'review', action: 'guide', guide_prompt: 'old contract' },
  176. ])('rejects invalid actions and incompatible response contracts: %j', async (body) => {
  177. await expect(
  178. callLocalSafetyCheckV2({ ...defaults, fetchImpl: fetchResponse(body) }),
  179. ).rejects.toMatchObject({ kind: 'response' });
  180. });
  181. it.each([
  182. { errorCode: 50200, error: 'request failed' },
  183. { action: 1, errorCode: 50200 },
  184. { action: 4, errorCode: 50202 },
  185. ])('classifies upstream errors before reading action: %j', async (body) => {
  186. await expect(
  187. callLocalSafetyCheckV2({ ...defaults, fetchImpl: fetchResponse(body) }),
  188. ).rejects.toMatchObject({ kind: 'upstream', statusCode: body.errorCode });
  189. });
  190. it('keeps region/build routing and limits endpoint overrides to test loopback', async () => {
  191. const fetchImpl = fetchResponse({ action: 1 });
  192. await callLocalSafetyCheckV2({
  193. ...defaults,
  194. fetchImpl,
  195. testBaseURL: 'http://127.0.0.1:45678/',
  196. });
  197. expect(fetchImpl.mock.calls[0]![0]).toBe('http://127.0.0.1:45678/mavis/api/v2/content?require_auth=true');
  198. await callLocalSafetyCheckV2({
  199. ...defaults,
  200. fetchImpl,
  201. testBaseURL: 'https://untrusted.example.test',
  202. });
  203. expect(fetchImpl.mock.calls[1]![0]).toBe(
  204. 'https://matrix-test.example.invalid/mavis/api/v2/content?require_auth=true',
  205. );
  206. await callLocalSafetyCheckV2({
  207. ...defaults,
  208. fetchImpl,
  209. region: () => 'en',
  210. buildEnv: () => 'prod',
  211. testBaseURL: 'http://127.0.0.1:45678',
  212. });
  213. expect(fetchImpl.mock.calls[2]![0]).toBe(
  214. 'https://agent.minimax.io/mavis/api/v2/content?require_auth=true',
  215. );
  216. });
  217. it('does not send a credential when there is no active token', async () => {
  218. vi.stubEnv('MAVIS_ACCESS_TOKEN', '');
  219. const fetchImpl = fetchResponse({ action: 1 });
  220. await callLocalSafetyCheckV2({ ...defaults, fetchImpl });
  221. expect(new Headers(fetchImpl.mock.calls[0]![1]?.headers).has('Authorization')).toBe(false);
  222. });
  223. it('leaves the existing V1 client endpoint and request unchanged', async () => {
  224. const fetchImpl = fetchResponse({ pass: true });
  225. await callSafetyApi({
  226. content: 'hello',
  227. scene: SAFETY_SCENE.UserInput,
  228. fetchImpl,
  229. region: defaults.region,
  230. buildEnv: defaults.buildEnv,
  231. });
  232. expect(fetchImpl.mock.calls[0]![0]).toBe(
  233. 'https://matrix-test.example.invalid/mavis/api/v1/content',
  234. );
  235. expect(JSON.parse(String(fetchImpl.mock.calls[0]![1]?.body))).toEqual({
  236. content_text: 'hello',
  237. scene: 300,
  238. });
  239. });
  240. });