local-permission-facade.test.ts 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076
  1. /**
  2. * LocalPermissionFacade end-to-end tests.
  3. *
  4. * Covers the PROD orchestration path (facade.checkPermission), which the
  5. * v2 unit tests under packages/agent-core/test/unit/permission-v2/ DO NOT
  6. * exercise — they target the still-dead `assessCommand` /
  7. * `PermissionServiceV2` pipeline that ships in MR-7.
  8. *
  9. * Surface tested here:
  10. * - off mode short-circuits after the Windows runtime safety boundary
  11. * - acceptEdits is normalized to default before engine
  12. * - bypassPermissions ('never') downgrades every ASK verdict to ALLOW
  13. * at the public entrypoint (see `applyAskGate`). The 22-trigger
  14. * invariant table lives in local-permission-ask-gate.test.ts; this
  15. * file only pins the H5 curl-pipe-shell + credential paths so the
  16. * facade ↔ gate plumbing is exercised end-to-end.
  17. * - localHardCheck.deny (UNC, root rm) is bypass-immune across all
  18. * askPolicy and runs BEFORE the gate, so the gate cannot weaken it
  19. * - sandbox self-paths: dataDir + ~/.minimax auto-allow ONLY for
  20. * read-only tools (read/glob/grep/list) so reading a SKILL.md is
  21. * friction-free; writes still go through the normal ask flow
  22. * because fs-permission's credential/.env/.git-sensitive guards
  23. * only run on the read side, never on writes. Even on the read
  24. * side, sensitive files inside dataDir still ASK.
  25. * - rewrittenInput (rm → mavis-trash) survives the ask branch
  26. * - localeHint is derived from inline latestUserMessages
  27. * - cloud-gateway timeout / block / confirm route to ask-user with
  28. * formatted reason prefixes (Auto classifier / Blocked / timed out)
  29. * - cloud-gateway allow rewrites to allow with rewrittenInput preserved
  30. * - cloud-gateway throw is caught and routed to ask-user
  31. * - acceptEdits seed adds 3 global rules; idempotent
  32. */
  33. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
  34. import { homedir, tmpdir } from 'node:os';
  35. import path from 'node:path';
  36. import { readWindowsTrashExecution } from '@mavis/permission';
  37. import { describe, expect, it, vi } from 'vitest';
  38. import type {
  39. CloudClassifyRequest,
  40. CloudClassifyVerdict,
  41. CloudGatewayClient,
  42. } from '@mavis/permission';
  43. import {
  44. LocalPermissionFacade,
  45. type LocalPermissionFacadeDeps,
  46. } from '../../src/permissions/facade.js';
  47. import { LocalPermissionRuleStore } from '../../src/permissions/rules.js';
  48. import { LocalPluginHookPermissionStore } from '../../src/permissions/plugin-hook-permissions.js';
  49. import type { LocalRuntimeConfig } from '../../src/config/types.js';
  50. import { logger } from '../../src/common/logger.js';
  51. import {
  52. TRASH_CMD_LAUNCHER_CONTENT,
  53. TRASH_SCRIPT_WIN_CONTENT,
  54. } from '../../src/infra/trash-script-win.js';
  55. import { ensureTrashScript } from '../../src/infra/ensure-trash-script.js';
  56. function freshFacade(
  57. opts: {
  58. permissionMode?: LocalRuntimeConfig['permissionMode'];
  59. policyOwner?: 'engine' | 'core';
  60. cloudGateway?: CloudGatewayClient;
  61. platform?: NodeJS.Platform;
  62. shellFamily?: 'cmd' | 'powershell';
  63. workspaceDir?: string;
  64. sandbox?: LocalRuntimeConfig['sandbox'];
  65. seedPosixTrash?: boolean;
  66. } = {},
  67. ): {
  68. facade: LocalPermissionFacade;
  69. ruleStore: LocalPermissionRuleStore;
  70. pluginHookPermissionStore: LocalPluginHookPermissionStore;
  71. dataDir: string;
  72. } {
  73. const dataDir = mkdtempSync(path.join(tmpdir(), 'aa-facade-'));
  74. const config: LocalRuntimeConfig = {
  75. dataDir,
  76. permissionMode: opts.permissionMode ?? 'default',
  77. permission: { policyOwner: opts.policyOwner ?? 'core' },
  78. ...(opts.sandbox ? { sandbox: opts.sandbox } : {}),
  79. } as LocalRuntimeConfig;
  80. const effectivePlatform = opts.platform ?? process.platform;
  81. if (
  82. opts.seedPosixTrash !== false &&
  83. (effectivePlatform === 'darwin' || effectivePlatform === 'linux')
  84. ) {
  85. ensureTrashScript(dataDir, effectivePlatform);
  86. }
  87. const ruleStore = new LocalPermissionRuleStore(() => dataDir);
  88. const pluginHookPermissionStore = new LocalPluginHookPermissionStore({ dataDir });
  89. const deps: LocalPermissionFacadeDeps = {
  90. ruleStore,
  91. pluginHookPermissionStore,
  92. configGetter: () => config,
  93. getSessionById: async () => undefined,
  94. getLocalAgent: async () =>
  95. opts.workspaceDir ? { defaultWorkspaceDir: opts.workspaceDir } : undefined,
  96. cloudGateway: opts.cloudGateway,
  97. ...(opts.platform ? { platform: opts.platform } : {}),
  98. ...(opts.shellFamily ? { shellFamily: opts.shellFamily } : {}),
  99. ...(opts.platform === 'win32' ? { trashRuntimeProbe: () => true } : {}),
  100. };
  101. return {
  102. facade: new LocalPermissionFacade(deps),
  103. ruleStore,
  104. pluginHookPermissionStore,
  105. dataDir,
  106. };
  107. }
  108. function seedWindowsTrashRuntime(dataDir: string): void {
  109. const binDir = path.join(dataDir, 'bin');
  110. mkdirSync(binDir, { recursive: true });
  111. writeFileSync(path.join(binDir, 'mavis-trash.js'), TRASH_SCRIPT_WIN_CONTENT, 'utf8');
  112. writeFileSync(path.join(binDir, 'mavis-trash.cmd'), TRASH_CMD_LAUNCHER_CONTENT, 'utf8');
  113. }
  114. function sandboxConfig(
  115. enabled: boolean,
  116. filesystemMode:
  117. | 'read_only'
  118. | 'workspace_write'
  119. | 'delete_guard'
  120. | 'full_access' = 'workspace_write',
  121. ): NonNullable<LocalRuntimeConfig['sandbox']> {
  122. return {
  123. enabled,
  124. filesystem: {
  125. policy: { mode: filesystemMode },
  126. denyRead: [],
  127. denyWrite: [],
  128. },
  129. network: { policy: { mode: 'allow_all' }, deniedDomains: [] },
  130. localAccess: 'open',
  131. };
  132. }
  133. function cleanup(dataDir: string): void {
  134. try {
  135. rmSync(dataDir, { recursive: true, force: true });
  136. } catch {
  137. /* ignore */
  138. }
  139. }
  140. describe('LocalPermissionFacade', () => {
  141. it('asks instead of evaluating with empty rules when the permission store is corrupt', async () => {
  142. const { facade, dataDir } = freshFacade({ policyOwner: 'core' });
  143. try {
  144. writeFileSync(path.join(dataDir, 'permission.json'), '{"version":2,"allow":[', 'utf8');
  145. const result = await facade.checkPermission({
  146. toolName: 'bash',
  147. input: { command: 'echo safe' },
  148. });
  149. expect(result.behavior).toBe('ask');
  150. expect(result.reason).toMatch(/permission rule store/i);
  151. } finally {
  152. cleanup(dataDir);
  153. }
  154. });
  155. it('does not downgrade an unhealthy permission store to allow in bypass mode', async () => {
  156. const { facade, dataDir } = freshFacade({
  157. permissionMode: 'bypassPermissions',
  158. policyOwner: 'core',
  159. });
  160. try {
  161. writeFileSync(path.join(dataDir, 'permission.json'), '{"version":2,"allow":[', 'utf8');
  162. const result = await facade.checkPermission({
  163. toolName: 'bash',
  164. input: { command: 'echo safe' },
  165. });
  166. expect(result.behavior).toBe('deny');
  167. expect(result.reason).toMatch(/permission rule store/i);
  168. } finally {
  169. cleanup(dataDir);
  170. }
  171. });
  172. it('logs the concrete checker reason for each Bash subcommand', async () => {
  173. const info = vi.spyOn(logger, 'info').mockImplementation(() => undefined);
  174. const { facade, dataDir } = freshFacade({ policyOwner: 'core' });
  175. try {
  176. const result = await facade.checkPermission({
  177. toolName: 'bash',
  178. sessionId: 'mvs_observability',
  179. input: { command: 'rm /tmp/private-output.log' },
  180. });
  181. expect(result.behavior).toBe('allow');
  182. expect(info).toHaveBeenCalledWith(
  183. expect.objectContaining({
  184. session_id: 'mvs_observability',
  185. tool_name: 'bash',
  186. permission_mode: 'default',
  187. policy_owner: 'core',
  188. checker_registered: true,
  189. checker_behavior: 'allow',
  190. reason_type: 'subcommandResults',
  191. reason_code: 'subcommand_results',
  192. subcommand_results: [
  193. {
  194. command: 'rm /tmp/private-output.log',
  195. behavior: 'allow',
  196. reason_type: 'rmRewrite',
  197. reason_code: 'recoverable_delete_rewrite',
  198. },
  199. ],
  200. rewrite_applied: true,
  201. rule_count: 0,
  202. skip_auto_classifier: false,
  203. }),
  204. 'permission.checker.decision',
  205. );
  206. expect(info).toHaveBeenCalledWith(
  207. expect.objectContaining({
  208. session_id: 'mvs_observability',
  209. tool_name: 'bash',
  210. permission_mode: 'default',
  211. policy_owner: 'core',
  212. policy_behavior: 'allow',
  213. reason_type: 'subcommandResults',
  214. reason_code: 'subcommand_results',
  215. subcommand_results: [
  216. {
  217. command: 'rm /tmp/private-output.log',
  218. behavior: 'allow',
  219. reason_type: 'rmRewrite',
  220. reason_code: 'recoverable_delete_rewrite',
  221. },
  222. ],
  223. rewrite_applied: true,
  224. rule_count: 0,
  225. skip_auto_classifier: false,
  226. }),
  227. 'permission.core.decision',
  228. );
  229. } finally {
  230. info.mockRestore();
  231. cleanup(dataDir);
  232. }
  233. });
  234. it('logs the command and detail for a top-level Bash safety decision', async () => {
  235. const info = vi.spyOn(logger, 'info').mockImplementation(() => undefined);
  236. const { facade, dataDir } = freshFacade({ policyOwner: 'core' });
  237. try {
  238. const command = 'echo smoke > /tmp/mavis-permission-smoke.txt';
  239. const result = await facade.checkPermission({
  240. toolName: 'bash',
  241. sessionId: 'mvs_safety_observability',
  242. input: { command },
  243. });
  244. expect(result.behavior).toBe('allow');
  245. for (const event of ['permission.checker.decision', 'permission.core.decision']) {
  246. expect(info).toHaveBeenCalledWith(
  247. expect.objectContaining({
  248. session_id: 'mvs_safety_observability',
  249. tool_name: 'bash',
  250. command,
  251. reason_type: 'safetyCheck',
  252. reason_code: 'safety_check',
  253. reason_category: 'authorizedWriteRedirect',
  254. reason_detail: 'Authorized write target in temp/workspace path.',
  255. }),
  256. event,
  257. );
  258. }
  259. } finally {
  260. info.mockRestore();
  261. cleanup(dataDir);
  262. }
  263. });
  264. it('logs the safety category and detail that caused a Bash deny', async () => {
  265. const info = vi.spyOn(logger, 'info').mockImplementation(() => undefined);
  266. const { facade, dataDir } = freshFacade({ policyOwner: 'core' });
  267. try {
  268. const command = 'shred /tmp/definitely-not-created.txt';
  269. const result = await facade.checkPermission({
  270. toolName: 'bash',
  271. sessionId: 'mvs_deny_observability',
  272. input: { command },
  273. });
  274. expect(result.behavior).toBe('deny');
  275. expect(info).toHaveBeenCalledWith(
  276. expect.objectContaining({
  277. session_id: 'mvs_deny_observability',
  278. checker_behavior: 'deny',
  279. subcommand_results: [
  280. expect.objectContaining({
  281. command,
  282. behavior: 'deny',
  283. reason_type: 'safetyCheck',
  284. reason_code: 'safety_check',
  285. reason_category: 'irrecoverable-delete',
  286. reason_detail: expect.stringContaining('shred (secure delete, irrecoverable)'),
  287. }),
  288. ],
  289. }),
  290. 'permission.checker.decision',
  291. );
  292. } finally {
  293. info.mockRestore();
  294. cleanup(dataDir);
  295. }
  296. });
  297. it('logs why a persisted rule allowed the tool without exposing its content', async () => {
  298. const info = vi.spyOn(logger, 'info').mockImplementation(() => undefined);
  299. const { facade, ruleStore, dataDir } = freshFacade({ policyOwner: 'core' });
  300. try {
  301. await ruleStore.applyUpdate({
  302. type: 'addRules',
  303. source: 'session',
  304. destination: 'mvs_rule_observability',
  305. behavior: 'allow',
  306. rules: [{ tool_name: 'write', rule_content: '/tmp/private-output.log' }],
  307. });
  308. const result = await facade.checkPermission({
  309. toolName: 'write',
  310. sessionId: 'mvs_rule_observability',
  311. input: { path: '/tmp/private-output.log', content: 'private content' },
  312. });
  313. expect(result.behavior).toBe('allow');
  314. expect(info).toHaveBeenCalledWith(
  315. expect.objectContaining({
  316. session_id: 'mvs_rule_observability',
  317. tool_name: 'write',
  318. policy_owner: 'core',
  319. policy_behavior: 'allow',
  320. reason_type: 'rule',
  321. reason_code: 'persisted_rule',
  322. rule_source: 'session',
  323. rule_behavior: 'allow',
  324. rule_tool_name: 'write',
  325. rule_has_content: true,
  326. }),
  327. 'permission.core.decision',
  328. );
  329. expect(JSON.stringify(info.mock.calls)).not.toContain('private-output.log');
  330. expect(JSON.stringify(info.mock.calls)).not.toContain('private content');
  331. } finally {
  332. info.mockRestore();
  333. cleanup(dataDir);
  334. }
  335. });
  336. it('logs the final verdict after the ask gate without command or path data', async () => {
  337. const info = vi.spyOn(logger, 'info').mockImplementation(() => undefined);
  338. const { facade, dataDir } = freshFacade({
  339. policyOwner: 'core',
  340. permissionMode: 'bypassPermissions',
  341. });
  342. try {
  343. const result = await facade.checkPermission({
  344. toolName: 'read',
  345. sessionId: 'mvs_observability',
  346. input: { path: '/Users/someone/.ssh/id_rsa' },
  347. });
  348. expect(result.behavior).toBe('allow');
  349. expect(info).toHaveBeenCalledWith(
  350. {
  351. session_id: 'mvs_observability',
  352. tool_name: 'read',
  353. permission_mode: 'bypassPermissions',
  354. policy_owner: 'core',
  355. raw_behavior: 'ask',
  356. final_behavior: 'allow',
  357. ask_gate_applied: true,
  358. rewrite_applied: false,
  359. execution_plan_present: true,
  360. transform_count: 0,
  361. raw_rule_count: 1,
  362. },
  363. 'permission.decision',
  364. );
  365. expect(JSON.stringify(info.mock.calls)).not.toContain('id_rsa');
  366. } finally {
  367. info.mockRestore();
  368. cleanup(dataDir);
  369. }
  370. });
  371. it.each(['engine', 'core'] as const)(
  372. 'preserves the public decision contract with the %s policy owner',
  373. async (policyOwner) => {
  374. const { facade, dataDir } = freshFacade({ policyOwner });
  375. try {
  376. const result = await facade.checkPermission({
  377. toolName: 'bash',
  378. input: { command: 'rm /tmp/output.log' },
  379. });
  380. expect(result).toMatchObject({
  381. behavior: 'allow',
  382. rewrittenInput: { command: expect.stringContaining('mavis-trash') },
  383. });
  384. } finally {
  385. cleanup(dataDir);
  386. }
  387. },
  388. );
  389. it('uses Plugin Hook rules, dontAsk mode, and added directories in the effective check', async () => {
  390. const workspaceDir = mkdtempSync(path.join(tmpdir(), 'aa-facade-workspace-'));
  391. const sharedDir = mkdtempSync(path.join(tmpdir(), 'aa-facade-shared-'));
  392. const sharedFile = path.join(sharedDir, 'shared.txt');
  393. writeFileSync(sharedFile, 'shared', 'utf8');
  394. const { facade, pluginHookPermissionStore, dataDir } = freshFacade({ workspaceDir });
  395. try {
  396. await pluginHookPermissionStore.applyAtomic({
  397. sessionId: 'session-1',
  398. cwd: workspaceDir,
  399. bypassAvailable: false,
  400. updates: [
  401. { type: 'setMode', mode: 'dontAsk', destination: 'session' },
  402. {
  403. type: 'addDirectories',
  404. directories: [sharedDir],
  405. destination: 'session',
  406. },
  407. ],
  408. });
  409. await expect(
  410. facade.checkPermission({
  411. toolName: 'bash',
  412. input: { command: 'npm publish' },
  413. agentName: 'mavis',
  414. sessionId: 'session-1',
  415. }),
  416. ).resolves.toMatchObject({ behavior: 'deny', reason: expect.stringMatching(/dontAsk/) });
  417. await expect(
  418. facade.checkPermission({
  419. toolName: 'read',
  420. input: { path: sharedFile },
  421. agentName: 'mavis',
  422. sessionId: 'session-1',
  423. }),
  424. ).resolves.toMatchObject({ behavior: 'allow' });
  425. await pluginHookPermissionStore.applyAtomic({
  426. sessionId: 'session-1',
  427. cwd: workspaceDir,
  428. bypassAvailable: false,
  429. updates: [
  430. {
  431. type: 'addRules',
  432. behavior: 'allow',
  433. rules: [{ toolName: 'bash' }],
  434. destination: 'session',
  435. },
  436. ],
  437. });
  438. await expect(
  439. facade.checkPermission({
  440. toolName: 'bash',
  441. input: { command: 'npm publish' },
  442. agentName: 'mavis',
  443. sessionId: 'session-1',
  444. }),
  445. ).resolves.toMatchObject({ behavior: 'allow' });
  446. } finally {
  447. cleanup(dataDir);
  448. cleanup(workspaceDir);
  449. cleanup(sharedDir);
  450. }
  451. });
  452. describe('POSIX host trash boundary', () => {
  453. it('hard-denies rm when the canonical POSIX trash script is unavailable', async () => {
  454. const { facade, dataDir } = freshFacade({
  455. platform: 'darwin',
  456. seedPosixTrash: false,
  457. });
  458. try {
  459. const result = await facade.checkPermission({
  460. toolName: 'bash',
  461. input: { command: 'rm ./old.txt' },
  462. });
  463. expect(result).toMatchObject({
  464. behavior: 'deny',
  465. denySource: 'safety-immune',
  466. });
  467. // Fail-closed is intentional, but the denial has to be actionable:
  468. // name the script and the concrete recovery steps.
  469. expect(result.reason).toMatch(/recoverable deletion is unavailable/i);
  470. expect(result.reason).toContain('Runtime script:');
  471. expect(result.reason).toMatch(/how to restore it/i);
  472. } finally {
  473. cleanup(dataDir);
  474. }
  475. });
  476. it('routes an eligible rm through the textual rewrite in off mode', async () => {
  477. const { facade, dataDir } = freshFacade({
  478. permissionMode: 'off',
  479. platform: 'darwin',
  480. workspaceDir: '/workspace',
  481. });
  482. try {
  483. const result = await facade.checkPermission({
  484. toolName: 'bash',
  485. agentName: 'mavis',
  486. input: { command: 'rm ./old.txt', timeout: 9 },
  487. });
  488. expect(result.behavior).toBe('allow');
  489. expect(result.rewrittenInput?.command).toContain('mavis-trash -- ./old.txt');
  490. // The plan still DESCRIBES a recoverable delete (telemetry only — no
  491. // consumer executes it), but there is no host sentinel: the delete now
  492. // runs in-cage, reaching mavis-trash through the PATH shim.
  493. expect(result.executionPlan?.transforms).toEqual([
  494. { type: 'recoverable-delete', targets: ['/workspace/old.txt'] },
  495. ]);
  496. expect(readWindowsTrashExecution(result.rewrittenInput)).toBeUndefined();
  497. } finally {
  498. cleanup(dataDir);
  499. }
  500. });
  501. it('keeps non-delete commands on the off-mode short circuit', async () => {
  502. const { facade, dataDir } = freshFacade({ permissionMode: 'off', platform: 'linux' });
  503. try {
  504. const result = await facade.checkPermission({
  505. toolName: 'bash',
  506. input: { command: 'ls -la' },
  507. });
  508. expect(result.behavior).toBe('allow');
  509. expect(result.reason).toMatch(/permission mode is off/i);
  510. expect(result.rewrittenInput).toBeUndefined();
  511. } finally {
  512. cleanup(dataDir);
  513. }
  514. });
  515. it('does not reshape a compound rm when the sandbox is enabled', async () => {
  516. const { facade, dataDir } = freshFacade({
  517. platform: 'darwin',
  518. workspaceDir: '/workspace',
  519. sandbox: sandboxConfig(true),
  520. });
  521. try {
  522. const result = await facade.checkPermission({
  523. toolName: 'bash',
  524. agentName: 'mavis',
  525. input: { command: 'echo ok && rm ./old.txt' },
  526. });
  527. // The sandbox is an authorization layer enforced in the kernel; it must
  528. // not reshape the permission verdict for deletes. Compare with the
  529. // sandbox-disabled case below: the outcome is identical.
  530. expect(result.behavior).toBe('allow');
  531. expect(result.rewrittenInput?.command).toContain('mavis-trash -- ./old.txt');
  532. expect(readWindowsTrashExecution(result.rewrittenInput)).toBeUndefined();
  533. } finally {
  534. cleanup(dataDir);
  535. }
  536. });
  537. it('keeps compound rm on the textual rewrite when the sandbox is disabled', async () => {
  538. const { facade, dataDir } = freshFacade({
  539. platform: 'linux',
  540. workspaceDir: '/workspace',
  541. sandbox: sandboxConfig(false),
  542. });
  543. try {
  544. const result = await facade.checkPermission({
  545. toolName: 'bash',
  546. agentName: 'mavis',
  547. input: { command: 'echo ok && rm ./old.txt' },
  548. });
  549. expect(result.behavior).toBe('allow');
  550. expect(result.rewrittenInput?.command).toContain('mavis-trash -- ./old.txt');
  551. expect(readWindowsTrashExecution(result.rewrittenInput)).toBeUndefined();
  552. } finally {
  553. cleanup(dataDir);
  554. }
  555. });
  556. });
  557. describe('Windows delete boundary', () => {
  558. it.each(['default', 'bypassPermissions', 'off'] as const)(
  559. 'hard-denies the incident wrapper command in %s mode before execution',
  560. async (permissionMode) => {
  561. for (const descriptorRedirect of ['2>&1', '1>&2', '*>&1']) {
  562. const { facade, dataDir } = freshFacade({ permissionMode, platform: 'win32' });
  563. try {
  564. const r = await facade.checkPermission({
  565. toolName: 'bash',
  566. input: {
  567. command: String.raw`cmd /c "rmdir /S /Q \"X:\minimax workspace\md2wechat-skill\"" ${descriptorRedirect}; if (Test-Path 'X:\minimax workspace\md2wechat-skill') { Write-Host "STILL_EXISTS" } else { Write-Host "DELETED" }`,
  568. },
  569. });
  570. expect(r.behavior).toBe('deny');
  571. expect(r.denySource).toBe('safety-immune');
  572. expect(r.reason).toMatch(/windows|delete|永久|删除/i);
  573. expect(r.reason).toContain('Deletion intent detected');
  574. expect(r.reason).toContain('Do not bypass this denial');
  575. expect(r.reason).toContain('trusted mavis-trash launcher');
  576. expect(r.reason).not.toContain('must be removed manually');
  577. } finally {
  578. cleanup(dataDir);
  579. }
  580. }
  581. },
  582. );
  583. it('hard-denies a chained PowerShell delete alias before the off-mode short circuit', async () => {
  584. const workspaceDir = String.raw`C:\Users\16379\project`;
  585. const { facade, dataDir } = freshFacade({
  586. permissionMode: 'off',
  587. platform: 'win32',
  588. workspaceDir,
  589. });
  590. try {
  591. seedWindowsTrashRuntime(dataDir);
  592. const r = await facade.checkPermission({
  593. toolName: 'bash',
  594. agentName: 'mavis',
  595. input: {
  596. command: String.raw`echo ok && powershell.exe -NoProfile -Command "ri -Recurse C:\Users\16379\project\mock"`,
  597. },
  598. });
  599. expect(r.behavior).toBe('deny');
  600. expect(r.denySource).toBe('safety-immune');
  601. } finally {
  602. cleanup(dataDir);
  603. }
  604. });
  605. it.each([
  606. String.raw`del /f /q C:\Users\16379\project\old.txt`,
  607. String.raw`erase C:\Users\16379\project\stale.log`,
  608. String.raw`rmdir /s /q C:\Users\16379\project\cache`,
  609. String.raw`rd /s C:\Users\16379\project\build`,
  610. String.raw`Remove-Item -Recurse -Force C:\Users\16379\project\output`,
  611. String.raw`ri C:\Users\16379\project\old.txt`,
  612. ])(
  613. 'rewrites the proven top-level Windows native delete subset in off mode: %s',
  614. async (command) => {
  615. const workspaceDir = String.raw`C:\Users\16379\project`;
  616. const { facade, dataDir } = freshFacade({
  617. permissionMode: 'off',
  618. platform: 'win32',
  619. shellFamily:
  620. command.startsWith('Remove-Item') || command.startsWith('ri') ? 'powershell' : 'cmd',
  621. workspaceDir,
  622. });
  623. try {
  624. seedWindowsTrashRuntime(dataDir);
  625. const r = await facade.checkPermission({
  626. toolName: 'bash',
  627. agentName: 'mavis',
  628. input: { command },
  629. });
  630. expect(r.behavior).toBe('allow');
  631. expect(r.rewrittenInput?.command).toBe('mavis-trash --');
  632. expect(JSON.stringify(r.rewrittenInput)).not.toContain(command);
  633. expect(readWindowsTrashExecution(r.rewrittenInput)?.targets.length).toBeGreaterThan(0);
  634. } finally {
  635. cleanup(dataDir);
  636. }
  637. },
  638. );
  639. it.each([
  640. 'del /f /q C:\\',
  641. String.raw`rmdir /s /q C:\Windows\Temp`,
  642. String.raw`rmdir /s /q "C:\Program Files\Adobe"`,
  643. String.raw`rmdir /s /q "C:\Program Files (x86)\Legacy"`,
  644. ])(
  645. 'does not let a root workspace bypass protected Windows path safety: %s',
  646. async (command) => {
  647. const { facade, dataDir } = freshFacade({
  648. permissionMode: 'off',
  649. platform: 'win32',
  650. shellFamily: 'cmd',
  651. workspaceDir: 'C:\\',
  652. });
  653. try {
  654. seedWindowsTrashRuntime(dataDir);
  655. const result = await facade.checkPermission({
  656. toolName: 'bash',
  657. agentName: 'mavis',
  658. input: { command },
  659. });
  660. expect(result.behavior).toBe('deny');
  661. expect(result.denySource).toBe('safety-immune');
  662. expect(result.rewrittenInput).toBeUndefined();
  663. } finally {
  664. cleanup(dataDir);
  665. }
  666. },
  667. );
  668. it('fails closed for a proven native delete when the Windows trash runtime is unavailable', async () => {
  669. const workspaceDir = String.raw`C:\Users\16379\project`;
  670. const { facade, dataDir } = freshFacade({
  671. permissionMode: 'off',
  672. platform: 'win32',
  673. shellFamily: 'cmd',
  674. workspaceDir,
  675. });
  676. try {
  677. const r = await facade.checkPermission({
  678. toolName: 'bash',
  679. agentName: 'mavis',
  680. input: { command: String.raw`del C:\Users\16379\project\old.txt` },
  681. });
  682. expect(r.behavior).toBe('deny');
  683. expect(r.reason).toMatch(/mavis-trash|trash.*unavailable|安全删除/i);
  684. expect(r.reason).toContain('Deletion intent detected');
  685. expect(r.reason).toContain('The target was not deleted');
  686. expect(r.reason).toContain('Do not fall back to any permanent delete command');
  687. expect(r.reason).toContain('Re-check mavis-trash availability before retrying');
  688. expect(r.reason).toContain('use only the trusted local-runtime launcher');
  689. expect(r.reason).toContain('If mavis-trash remains unavailable');
  690. expect(r.rewrittenInput).toBeUndefined();
  691. } finally {
  692. cleanup(dataDir);
  693. }
  694. });
  695. it.each([
  696. String.raw`del C:\Users\16379\project\*.tmp`,
  697. String.raw`Remove-Item -Path C:\Users\16379\project\old.txt`,
  698. String.raw`Remove-Item Env:\TEMP`,
  699. String.raw`del C:\Users\16379\project\old.txt && echo done`,
  700. String.raw`cmd /c "del C:\Users\16379\project\old.txt"`,
  701. ])(
  702. 'keeps unsupported Windows native delete syntax safety-immune denied: %s',
  703. async (command) => {
  704. const workspaceDir = String.raw`C:\Users\16379\project`;
  705. const { facade, dataDir } = freshFacade({
  706. permissionMode: 'off',
  707. platform: 'win32',
  708. workspaceDir,
  709. });
  710. try {
  711. seedWindowsTrashRuntime(dataDir);
  712. const r = await facade.checkPermission({
  713. toolName: 'bash',
  714. agentName: 'mavis',
  715. input: { command },
  716. });
  717. expect(r.behavior).toBe('deny');
  718. expect(r.denySource).toBe('safety-immune');
  719. expect(r.rewrittenInput).toBeUndefined();
  720. } finally {
  721. cleanup(dataDir);
  722. }
  723. },
  724. );
  725. it('does not fall back to permanent rm when the Windows trash launcher is unavailable', async () => {
  726. const { facade, dataDir } = freshFacade({
  727. permissionMode: 'bypassPermissions',
  728. platform: 'win32',
  729. });
  730. try {
  731. const r = await facade.checkPermission({
  732. toolName: 'bash',
  733. input: { command: String.raw`rm -rf C:\Users\16379\project\mock` },
  734. });
  735. expect(r.behavior).toBe('deny');
  736. expect(r.reason).toMatch(/mavis-trash|trash.*unavailable|安全删除/i);
  737. } finally {
  738. cleanup(dataDir);
  739. }
  740. });
  741. it('rewrites an in-workspace rm to mavis-trash even when permission mode is off', async () => {
  742. const workspaceDir = String.raw`C:\Users\16379\project`;
  743. const { facade, dataDir } = freshFacade({
  744. permissionMode: 'off',
  745. platform: 'win32',
  746. workspaceDir,
  747. });
  748. try {
  749. seedWindowsTrashRuntime(dataDir);
  750. const r = await facade.checkPermission({
  751. toolName: 'bash',
  752. agentName: 'mavis',
  753. input: { command: String.raw`rm -rf C:\Users\16379\project\mock` },
  754. });
  755. expect(r.behavior).toBe('allow');
  756. expect(r.rewrittenInput?.command).toMatch(/mavis-trash/);
  757. expect(r.rewrittenInput?.command).toContain(String.raw`C:\Users\16379\project\mock`);
  758. expect(r.executionPlan?.transforms).toEqual([
  759. {
  760. type: 'recoverable-delete',
  761. targets: [String.raw`C:\Users\16379\project\mock`],
  762. },
  763. ]);
  764. const bareTrash = await facade.checkPermission({
  765. toolName: 'bash',
  766. agentName: 'mavis',
  767. input: { command: String.raw`mavis-trash -rf C:\Users\16379\project\mock` },
  768. });
  769. expect(bareTrash.behavior).toBe('deny');
  770. expect(bareTrash.reason).toContain('bare or non-canonical mavis-trash is untrusted');
  771. expect(bareTrash.reason).toContain('The target was not deleted');
  772. expect(bareTrash.reason).toContain('one top-level rm command');
  773. expect(bareTrash.reason).toContain(
  774. path.win32.join(dataDir, 'bin', 'mavis-trash.cmd'),
  775. );
  776. } finally {
  777. cleanup(dataDir);
  778. }
  779. });
  780. it('allows the canonical absolute Windows trash launcher used by rm rewrite', async () => {
  781. const workspaceDir = String.raw`C:\Users\16379\project`;
  782. const { facade, dataDir } = freshFacade({
  783. permissionMode: 'off',
  784. platform: 'win32',
  785. workspaceDir,
  786. });
  787. try {
  788. seedWindowsTrashRuntime(dataDir);
  789. const launcherPath = path.join(dataDir, 'bin', 'mavis-trash.cmd');
  790. const r = await facade.checkPermission({
  791. toolName: 'bash',
  792. agentName: 'mavis',
  793. input: {
  794. command: `"${launcherPath}" -rf ${String.raw`C:\Users\16379\project\mock`}`,
  795. },
  796. });
  797. expect(r.behavior).toBe('allow');
  798. expect(r.reason).not.toMatch(/wrapped or compound|cannot be safely rewritten/i);
  799. } finally {
  800. cleanup(dataDir);
  801. }
  802. });
  803. it('requires a healthy canonical absolute Windows trash launcher', async () => {
  804. const workspaceDir = String.raw`C:\Users\16379\project`;
  805. const { facade, dataDir } = freshFacade({
  806. permissionMode: 'off',
  807. platform: 'win32',
  808. workspaceDir,
  809. });
  810. try {
  811. const launcherPath = path.join(dataDir, 'bin', 'mavis-trash.cmd');
  812. const r = await facade.checkPermission({
  813. toolName: 'bash',
  814. agentName: 'mavis',
  815. input: {
  816. command: `"${launcherPath}" -rf ${String.raw`C:\Users\16379\project\mock`}`,
  817. },
  818. });
  819. expect(r.behavior).toBe('deny');
  820. expect(r.reason).toMatch(/mavis-trash|trash.*unavailable|安全删除/i);
  821. } finally {
  822. cleanup(dataDir);
  823. }
  824. });
  825. it('does not trust an arbitrary same-named Windows trash launcher', async () => {
  826. const workspaceDir = String.raw`C:\Users\16379\project`;
  827. const { facade, dataDir } = freshFacade({
  828. permissionMode: 'off',
  829. platform: 'win32',
  830. workspaceDir,
  831. });
  832. try {
  833. seedWindowsTrashRuntime(dataDir);
  834. const r = await facade.checkPermission({
  835. toolName: 'bash',
  836. agentName: 'mavis',
  837. input: {
  838. command: String.raw`C:\Users\16379\Downloads\mavis-trash.cmd -rf C:\Users\16379\project\mock`,
  839. },
  840. });
  841. expect(r.behavior).toBe('deny');
  842. expect(r.reason).toContain('bare or non-canonical mavis-trash is untrusted');
  843. expect(r.reason).toContain(path.win32.join(dataDir, 'bin', 'mavis-trash.cmd'));
  844. } finally {
  845. cleanup(dataDir);
  846. }
  847. });
  848. it('does not trust a bare mavis-trash.cmd resolved from the current directory', async () => {
  849. const workspaceDir = String.raw`C:\Users\16379\project`;
  850. const { facade, dataDir } = freshFacade({
  851. permissionMode: 'off',
  852. platform: 'win32',
  853. workspaceDir,
  854. });
  855. try {
  856. seedWindowsTrashRuntime(dataDir);
  857. const r = await facade.checkPermission({
  858. toolName: 'bash',
  859. agentName: 'mavis',
  860. input: { command: String.raw`mavis-trash.cmd -rf C:\Users\16379\project\mock` },
  861. });
  862. expect(r.behavior).toBe('deny');
  863. expect(r.reason).toContain('bare or non-canonical mavis-trash is untrusted');
  864. expect(r.reason).toContain(path.win32.join(dataDir, 'bin', 'mavis-trash.cmd'));
  865. } finally {
  866. cleanup(dataDir);
  867. }
  868. });
  869. it.each([
  870. String.raw`cmd /c "mavis-trash -- C:\Users\16379\project\mock"`,
  871. String.raw`powershell.exe -NoProfile -Command "mavis-trash -- C:\Users\16379\project\mock"`,
  872. String.raw`cmd /c "mavis-trash -rf .\mock"`,
  873. ])('does not trust bare mavis-trash after wrapper expansion: %s', async (command) => {
  874. const workspaceDir = String.raw`C:\Users\16379\project`;
  875. const { facade, dataDir } = freshFacade({
  876. permissionMode: 'off',
  877. platform: 'win32',
  878. workspaceDir,
  879. });
  880. try {
  881. seedWindowsTrashRuntime(dataDir);
  882. const r = await facade.checkPermission({
  883. toolName: 'bash',
  884. agentName: 'mavis',
  885. input: { command },
  886. });
  887. expect(r.behavior).toBe('deny');
  888. expect(r.reason).toContain('bare or non-canonical mavis-trash is untrusted');
  889. expect(r.reason).toContain(path.win32.join(dataDir, 'bin', 'mavis-trash.cmd'));
  890. } finally {
  891. cleanup(dataDir);
  892. }
  893. });
  894. it('explains how to retry a direct compound mavis-trash invocation safely', async () => {
  895. const workspaceDir = String.raw`C:\Users\admin\project`;
  896. const { facade, dataDir } = freshFacade({
  897. permissionMode: 'off',
  898. platform: 'win32',
  899. workspaceDir,
  900. });
  901. try {
  902. seedWindowsTrashRuntime(dataDir);
  903. const r = await facade.checkPermission({
  904. toolName: 'bash',
  905. agentName: 'mavis',
  906. input: {
  907. command:
  908. 'mavis-trash "C:\\Users\\admin\\nonexistent-test-file-12345.txt" 2>&1; Write-Output "---exit: $LASTEXITCODE---"',
  909. },
  910. });
  911. expect(r.behavior).toBe('deny');
  912. expect(r.denySource).toBe('safety-immune');
  913. expect(r.reason).toContain('bare or non-canonical mavis-trash is untrusted');
  914. expect(r.reason).toContain('PATH/CWD may select a different executable');
  915. expect(r.reason).toContain('The target was not deleted');
  916. expect(r.reason).toContain('one top-level rm command');
  917. expect(r.reason).toContain(path.win32.join(dataDir, 'bin', 'mavis-trash.cmd'));
  918. expect(r.reason).toContain('Do not bypass this with a permanent delete command');
  919. expect(r.reason.length).toBeLessThan(500);
  920. expect(r.reason).not.toContain('wrapped or compound Windows delete command');
  921. expect(r.rewrittenInput).toBeUndefined();
  922. } finally {
  923. cleanup(dataDir);
  924. }
  925. });
  926. it('allows a wrapped canonical absolute Windows trash launcher', async () => {
  927. const workspaceDir = String.raw`C:\Users\16379\project`;
  928. const { facade, dataDir } = freshFacade({
  929. permissionMode: 'off',
  930. platform: 'win32',
  931. workspaceDir,
  932. });
  933. try {
  934. seedWindowsTrashRuntime(dataDir);
  935. const launcherPath = path.join(dataDir, 'bin', 'mavis-trash.cmd');
  936. const r = await facade.checkPermission({
  937. toolName: 'bash',
  938. agentName: 'mavis',
  939. input: {
  940. command: `cmd /c "\"${launcherPath}\" -- ${String.raw`C:\Users\16379\project\mock`}"`,
  941. },
  942. });
  943. expect(r.behavior).toBe('allow');
  944. } finally {
  945. cleanup(dataDir);
  946. }
  947. });
  948. it('does not let a canonical launcher authorize a following bare trash command', async () => {
  949. const workspaceDir = String.raw`C:\Users\16379\project`;
  950. const { facade, dataDir } = freshFacade({
  951. permissionMode: 'off',
  952. platform: 'win32',
  953. workspaceDir,
  954. });
  955. try {
  956. seedWindowsTrashRuntime(dataDir);
  957. const launcherPath = path.join(dataDir, 'bin', 'mavis-trash.cmd');
  958. const r = await facade.checkPermission({
  959. toolName: 'bash',
  960. agentName: 'mavis',
  961. input: {
  962. command: `"${launcherPath}" -- ${String.raw`C:\Users\16379\project\a`} && mavis-trash.cmd -- ${String.raw`C:\Users\16379\project\b`}`,
  963. },
  964. });
  965. expect(r.behavior).toBe('deny');
  966. expect(r.reason).toContain('bare or non-canonical mavis-trash is untrusted');
  967. expect(r.reason).toContain(path.win32.join(dataDir, 'bin', 'mavis-trash.cmd'));
  968. } finally {
  969. cleanup(dataDir);
  970. }
  971. });
  972. // P1 (verifier gpt-5.5 audit, 2026-08-01): a canonical launcher in
  973. // segment 1 must not vouch for a permanent-delete verb in segment N.
  974. // `unlink` / `shred` / `del` / `rmdir` / `Remove-Item` all bypass the
  975. // rm-rewrite pipeline entirely, so each delete-like segment has to
  976. // be audited independently.
  977. it.each([
  978. String.raw`unlink .\b`,
  979. String.raw`shred -u .\b`,
  980. String.raw`del .\b`,
  981. String.raw`rmdir /s /q .\b`,
  982. String.raw`Remove-Item -Recurse .\b`,
  983. String.raw`ri -Recurse .\b`,
  984. ])(
  985. 'does not let a canonical launcher authorize a following non-trash delete segment: %s',
  986. async (tail) => {
  987. const workspaceDir = String.raw`C:\Users\16379\project`;
  988. const { facade, dataDir } = freshFacade({
  989. permissionMode: 'off',
  990. platform: 'win32',
  991. workspaceDir,
  992. });
  993. try {
  994. seedWindowsTrashRuntime(dataDir);
  995. const launcherPath = path.join(dataDir, 'bin', 'mavis-trash.cmd');
  996. const r = await facade.checkPermission({
  997. toolName: 'bash',
  998. agentName: 'mavis',
  999. input: {
  1000. command: `"${launcherPath}" -- ${String.raw`C:\Users\16379\project\a`} && ${tail}`,
  1001. },
  1002. });
  1003. expect(r.behavior).toBe('deny');
  1004. } finally {
  1005. cleanup(dataDir);
  1006. }
  1007. },
  1008. );
  1009. it('hard-denies a wrapped rm that cannot be safely rewritten', async () => {
  1010. const workspaceDir = String.raw`C:\Users\16379\project`;
  1011. const { facade, dataDir } = freshFacade({
  1012. permissionMode: 'off',
  1013. platform: 'win32',
  1014. workspaceDir,
  1015. });
  1016. try {
  1017. seedWindowsTrashRuntime(dataDir);
  1018. const r = await facade.checkPermission({
  1019. toolName: 'bash',
  1020. agentName: 'mavis',
  1021. input: { command: String.raw`cmd /c "rm -rf C:\Users\16379\project\mock"` },
  1022. });
  1023. expect(r.behavior).toBe('deny');
  1024. expect(r.reason).toMatch(/wrapped|rewrite|permanent delete/i);
  1025. expect(r.reason).toContain('Deletion intent detected');
  1026. expect(r.reason).toContain('Do not bypass this denial');
  1027. expect(r.reason).toContain('trusted mavis-trash launcher');
  1028. expect(r.reason).not.toContain('must be removed manually');
  1029. } finally {
  1030. cleanup(dataDir);
  1031. }
  1032. });
  1033. it.each([String.raw`move .\source .\renamed`, String.raw`mv .\source .\renamed`])(
  1034. 'allows an in-workspace Windows move in off mode: %s',
  1035. async (command) => {
  1036. const workspaceDir = String.raw`C:\Users\16379\project`;
  1037. const { facade, dataDir } = freshFacade({
  1038. permissionMode: 'off',
  1039. platform: 'win32',
  1040. workspaceDir,
  1041. });
  1042. try {
  1043. const r = await facade.checkPermission({
  1044. toolName: 'bash',
  1045. agentName: 'mavis',
  1046. input: { command },
  1047. });
  1048. expect(r.behavior).toBe('allow');
  1049. expect(r.reason).toMatch(/permission mode is off/i);
  1050. } finally {
  1051. cleanup(dataDir);
  1052. }
  1053. },
  1054. );
  1055. it.each([
  1056. String.raw`powershell.exe -NoProfile -Command "ri -Recurse C:\Users\16379\project\mock"`,
  1057. String.raw`powershell.exe -NoProfile -Command "remove -r C:\Users\16379\project\mock"`,
  1058. ])(
  1059. 'hard-denies a PowerShell delete alias before the off-mode short circuit: %s',
  1060. async (command) => {
  1061. const workspaceDir = String.raw`C:\Users\16379\project`;
  1062. const { facade, dataDir } = freshFacade({
  1063. permissionMode: 'off',
  1064. platform: 'win32',
  1065. workspaceDir,
  1066. });
  1067. try {
  1068. seedWindowsTrashRuntime(dataDir);
  1069. const r = await facade.checkPermission({
  1070. toolName: 'bash',
  1071. agentName: 'mavis',
  1072. input: { command },
  1073. });
  1074. expect(r.behavior).toBe('deny');
  1075. expect(r.denySource).toBe('safety-immune');
  1076. } finally {
  1077. cleanup(dataDir);
  1078. }
  1079. },
  1080. );
  1081. it('hard-denies protected Windows paths before the off-mode short circuit', async () => {
  1082. const workspaceDir = String.raw`C:\Users\16379\project`;
  1083. const { facade, dataDir } = freshFacade({
  1084. permissionMode: 'off',
  1085. platform: 'win32',
  1086. workspaceDir,
  1087. });
  1088. try {
  1089. seedWindowsTrashRuntime(dataDir);
  1090. const launcherPath = path.join(dataDir, 'bin', 'mavis-trash.cmd');
  1091. const r = await facade.checkPermission({
  1092. toolName: 'bash',
  1093. agentName: 'mavis',
  1094. input: { command: `"${launcherPath}" -rf "C:\\Program Files\\Adobe"` },
  1095. });
  1096. expect(r.behavior).toBe('deny');
  1097. expect(r.reason).toMatch(/protected Windows path/i);
  1098. } finally {
  1099. cleanup(dataDir);
  1100. }
  1101. });
  1102. it('hard-denies a protected Windows redirection target before the off-mode short circuit', async () => {
  1103. const workspaceDir = String.raw`C:\Users\16379\project`;
  1104. const { facade, dataDir } = freshFacade({
  1105. permissionMode: 'off',
  1106. platform: 'win32',
  1107. workspaceDir,
  1108. });
  1109. try {
  1110. const r = await facade.checkPermission({
  1111. toolName: 'bash',
  1112. agentName: 'mavis',
  1113. input: { command: String.raw`echo ok > C:\Windows\Temp\blocked.txt` },
  1114. });
  1115. expect(r).toMatchObject({ behavior: 'deny', denySource: 'safety-immune' });
  1116. expect(r.reason).toMatch(/protected Windows path/i);
  1117. } finally {
  1118. cleanup(dataDir);
  1119. }
  1120. });
  1121. it('hard-denies a quoted protected Windows redirection target', async () => {
  1122. const workspaceDir = String.raw`C:\Users\16379\project`;
  1123. const { facade, dataDir } = freshFacade({
  1124. permissionMode: 'off',
  1125. platform: 'win32',
  1126. workspaceDir,
  1127. });
  1128. try {
  1129. const r = await facade.checkPermission({
  1130. toolName: 'bash',
  1131. agentName: 'mavis',
  1132. input: { command: String.raw`echo ok >> "C:\Program Files\Example\blocked.txt"` },
  1133. });
  1134. expect(r).toMatchObject({ behavior: 'deny', denySource: 'safety-immune' });
  1135. expect(r.reason).toMatch(/protected Windows path/i);
  1136. } finally {
  1137. cleanup(dataDir);
  1138. }
  1139. });
  1140. it('hard-denies a PowerShell Set-Content write into a protected Windows path', async () => {
  1141. const workspaceDir = String.raw`C:\Users\16379\project`;
  1142. const { facade, dataDir } = freshFacade({
  1143. permissionMode: 'off',
  1144. platform: 'win32',
  1145. workspaceDir,
  1146. });
  1147. try {
  1148. const r = await facade.checkPermission({
  1149. toolName: 'bash',
  1150. agentName: 'mavis',
  1151. input: {
  1152. command: String.raw`powershell.exe -NoProfile -Command "Set-Content -Path C:\Windows\Temp\blocked.txt -Value blocked"`,
  1153. },
  1154. });
  1155. expect(r).toMatchObject({ behavior: 'deny', denySource: 'safety-immune' });
  1156. expect(r.reason).toMatch(/protected Windows path/i);
  1157. } finally {
  1158. cleanup(dataDir);
  1159. }
  1160. });
  1161. it.each([
  1162. String.raw`powershell.exe -NoProfile -Command "Add-Content -Path C:\Windows\Temp\blocked.txt -Value blocked"`,
  1163. String.raw`powershell.exe -NoProfile -Command "Out-File -FilePath C:\Program Files\Example\blocked.txt -InputObject blocked"`,
  1164. String.raw`powershell.exe -NoProfile -Command "New-Item -ItemType File -Path C:\Windows\Temp\blocked.txt"`,
  1165. String.raw`powershell.exe -NoProfile -Command "Set-Content -Path $env:SystemRoot\Temp\blocked.txt -Value blocked"`,
  1166. ])(
  1167. 'hard-denies other common PowerShell writes into a protected Windows path: %s',
  1168. async (command) => {
  1169. const workspaceDir = String.raw`C:\Users\16379\project`;
  1170. const { facade, dataDir } = freshFacade({
  1171. permissionMode: 'off',
  1172. platform: 'win32',
  1173. workspaceDir,
  1174. });
  1175. try {
  1176. const r = await facade.checkPermission({
  1177. toolName: 'bash',
  1178. agentName: 'mavis',
  1179. input: { command },
  1180. });
  1181. expect(r).toMatchObject({ behavior: 'deny', denySource: 'safety-immune' });
  1182. expect(r.reason).toMatch(/protected Windows path/i);
  1183. } finally {
  1184. cleanup(dataDir);
  1185. }
  1186. },
  1187. );
  1188. // P1 (Codex Review gpt-5.5, 2026-08-01): the symbolic-path regex only
  1189. // matched `$env:SystemRoot`, so PowerShell's braced env form
  1190. // `${env:SystemRoot}` slipped through. `${env:ProgramFiles(x86)}` is
  1191. // especially load-bearing here because the unbraced form
  1192. // `$env:ProgramFiles(x86)` is a PowerShell syntax error — the braced
  1193. // form is the ONLY way to reference that variable, so if we do not
  1194. // recognize it we have zero coverage for `Program Files (x86)`
  1195. // targeting through env vars.
  1196. //
  1197. // Note: `${...}` in a JS template literal is variable interpolation,
  1198. // so we cannot use `String.raw` here — plain single-quoted strings
  1199. // pass the literal `${env:...}` through unchanged.
  1200. it.each([
  1201. 'powershell.exe -NoProfile -Command "Set-Content -Path ${env:SystemRoot}\\Temp\\blocked.txt -Value blocked"',
  1202. 'powershell.exe -NoProfile -Command "Set-Content -Path ${env:windir}\\Temp\\blocked.txt -Value blocked"',
  1203. 'powershell.exe -NoProfile -Command "Set-Content -Path ${env:ProgramFiles}\\Example\\blocked.txt -Value blocked"',
  1204. 'powershell.exe -NoProfile -Command "Set-Content -Path ${env:ProgramFiles(x86)}\\Example\\blocked.txt -Value blocked"',
  1205. 'powershell.exe -NoProfile -Command "Set-Content -Path ${env:CommonProgramFiles(x86)}\\Example\\blocked.txt -Value blocked"',
  1206. 'powershell.exe -NoProfile -Command "Set-Content -Path ${env:SystemDrive}\\Windows\\Temp\\blocked.txt -Value blocked"',
  1207. ])(
  1208. 'hard-denies PowerShell braced env var writes to a protected Windows path: %s',
  1209. async (command) => {
  1210. const workspaceDir = String.raw`C:\Users\16379\project`;
  1211. const { facade, dataDir } = freshFacade({
  1212. permissionMode: 'off',
  1213. platform: 'win32',
  1214. workspaceDir,
  1215. });
  1216. try {
  1217. const r = await facade.checkPermission({
  1218. toolName: 'bash',
  1219. agentName: 'mavis',
  1220. input: { command },
  1221. });
  1222. expect(r).toMatchObject({ behavior: 'deny', denySource: 'safety-immune' });
  1223. expect(r.reason).toMatch(/protected Windows path/i);
  1224. } finally {
  1225. cleanup(dataDir);
  1226. }
  1227. },
  1228. );
  1229. // P1 (Codex Review gpt-5.5, 2026-08-01): redirect scanning only
  1230. // unwrapped the outermost command, so a wrapper-payload `>` on a
  1231. // later `&&` segment was invisible. Ensure the safety net now sees
  1232. // redirects buried inside chained wrappers regardless of whether the
  1233. // outer surface itself is a write command.
  1234. it.each([
  1235. String.raw`echo ok && cmd /c "echo x > C:\Windows\Temp\pwn.txt"`,
  1236. String.raw`echo ok && cmd /c "echo x >> C:\Windows\Temp\pwn.txt"`,
  1237. String.raw`echo ok && powershell -NoProfile -Command "'x' > C:\Windows\Temp\pwn.txt"`,
  1238. 'echo ok && cmd /c "echo x > ${env:SystemRoot}\\Temp\\pwn.txt"',
  1239. ])(
  1240. 'hard-denies a redirect to a protected Windows path buried in a chained wrapper: %s',
  1241. async (command) => {
  1242. const workspaceDir = String.raw`C:\Users\16379\project`;
  1243. const { facade, dataDir } = freshFacade({
  1244. permissionMode: 'off',
  1245. platform: 'win32',
  1246. workspaceDir,
  1247. });
  1248. try {
  1249. const r = await facade.checkPermission({
  1250. toolName: 'bash',
  1251. agentName: 'mavis',
  1252. input: { command },
  1253. });
  1254. expect(r).toMatchObject({ behavior: 'deny', denySource: 'safety-immune' });
  1255. expect(r.reason).toMatch(/protected Windows path/i);
  1256. } finally {
  1257. cleanup(dataDir);
  1258. }
  1259. },
  1260. );
  1261. it.each([
  1262. String.raw`copy .\fixture.txt %ProgramFiles%\blocked.txt`,
  1263. String.raw`copy .\fixture.txt C:Windows\Temp\blocked.txt`,
  1264. String.raw`copy .\fixture.txt C:..\Windows\Temp\blocked.txt`,
  1265. String.raw`powershell.exe -NoProfile -Command "Set-Content -Path C:..\Windows\Temp\blocked.txt -Value blocked"`,
  1266. ])(
  1267. 'hard-denies a protected Windows target expressed without a literal absolute path: %s',
  1268. async (command) => {
  1269. const workspaceDir = String.raw`C:\Users\16379\project`;
  1270. const { facade, dataDir } = freshFacade({
  1271. permissionMode: 'off',
  1272. platform: 'win32',
  1273. workspaceDir,
  1274. });
  1275. try {
  1276. const r = await facade.checkPermission({
  1277. toolName: 'bash',
  1278. agentName: 'mavis',
  1279. input: { command },
  1280. });
  1281. expect(r).toMatchObject({ behavior: 'deny', denySource: 'safety-immune' });
  1282. expect(r.reason).toMatch(/protected Windows path/i);
  1283. } finally {
  1284. cleanup(dataDir);
  1285. }
  1286. },
  1287. );
  1288. it('hard-denies recursive Windows writes when no explicit workspace is available', async () => {
  1289. const { facade, dataDir } = freshFacade({ permissionMode: 'off', platform: 'win32' });
  1290. try {
  1291. const r = await facade.checkPermission({
  1292. toolName: 'bash',
  1293. agentName: 'mavis',
  1294. input: { command: String.raw`cp -r .\source .\build` },
  1295. });
  1296. expect(r).toMatchObject({ behavior: 'deny', denySource: 'safety-immune' });
  1297. expect(r.reason).toMatch(/workspace.*unavailable|cannot be verified/i);
  1298. } finally {
  1299. cleanup(dataDir);
  1300. }
  1301. });
  1302. it.each([
  1303. String.raw`copy C:\Users\16379\project\fixture.txt C:\Windows\System32\fixture.txt`,
  1304. String.raw`cp C:\Users\16379\project\fixture.txt C:\Program Files\Example\fixture.txt`,
  1305. ])(
  1306. 'hard-denies a protected Windows write target after an absolute source in off mode: %s',
  1307. async (command) => {
  1308. const workspaceDir = String.raw`C:\Users\16379\project`;
  1309. const { facade, dataDir } = freshFacade({
  1310. permissionMode: 'off',
  1311. platform: 'win32',
  1312. workspaceDir,
  1313. });
  1314. try {
  1315. const r = await facade.checkPermission({
  1316. toolName: 'bash',
  1317. agentName: 'mavis',
  1318. input: { command },
  1319. });
  1320. expect(r.behavior).toBe('deny');
  1321. expect(r.denySource).toBe('safety-immune');
  1322. expect(r.reason).toMatch(/protected Windows path/i);
  1323. } finally {
  1324. cleanup(dataDir);
  1325. }
  1326. },
  1327. );
  1328. });
  1329. describe('mode normalization', () => {
  1330. it('does not apply the Windows permanent-delete preflight on non-Windows hosts', async () => {
  1331. const { facade, dataDir } = freshFacade({ permissionMode: 'off', platform: 'darwin' });
  1332. try {
  1333. const r = await facade.checkPermission({
  1334. toolName: 'bash',
  1335. input: { command: 'rmdir /s /q ./scratch' },
  1336. });
  1337. expect(r.behavior).toBe('allow');
  1338. expect(r.reason).toMatch(/permission mode is off/i);
  1339. } finally {
  1340. cleanup(dataDir);
  1341. }
  1342. });
  1343. it('off mode still applies the catastrophic rm safety boundary', async () => {
  1344. const { facade, dataDir } = freshFacade({ permissionMode: 'off', platform: 'darwin' });
  1345. try {
  1346. const r = await facade.checkPermission({
  1347. toolName: 'bash',
  1348. input: { command: 'rm -rf /' },
  1349. });
  1350. expect(r.behavior).toBe('deny');
  1351. expect(r.reason).toMatch(/catastrophic|root|unrecoverable/i);
  1352. } finally {
  1353. cleanup(dataDir);
  1354. }
  1355. });
  1356. it('acceptEdits is normalized to default — engine still asks for unrelated bash', async () => {
  1357. const { facade, dataDir } = freshFacade({ permissionMode: 'acceptEdits' });
  1358. try {
  1359. const r = await facade.checkPermission({
  1360. toolName: 'bash',
  1361. input: { command: 'npm publish' },
  1362. });
  1363. // acceptEdits seeds edit/write/apply_patch, NOT bash — so bash must
  1364. // still ask under default mode.
  1365. expect(r.behavior).toBe('ask');
  1366. } finally {
  1367. cleanup(dataDir);
  1368. }
  1369. });
  1370. });
  1371. describe('mode snapshot (race-safety)', () => {
  1372. // P1 regression: checkPermission used to read configGetter() twice —
  1373. // once at the wrapper, once inside checkPermissionRaw. Between the two
  1374. // `await` boundaries, `PUT /config { permissionMode: ... }` from the
  1375. // daemon could flip the persisted mode, and the raw pipeline's mode
  1376. // would then disagree with the ask-gate's mode. The dangerous direction
  1377. // is "user tightens bypass → default mid-call": raw runs in default
  1378. // and returns ASK for a credential read, but the gate still sees the
  1379. // stale bypass snapshot and downgrades it to ALLOW. The fix snapshots
  1380. // the mode ONCE at the public entrypoint and threads it through both
  1381. // halves of the pipeline.
  1382. it('user flipping bypass → default mid-await does NOT silently allow ASK', async () => {
  1383. const dataDir = mkdtempSync(path.join(tmpdir(), 'aa-facade-race-'));
  1384. try {
  1385. // Start in bypassPermissions.
  1386. const config: LocalRuntimeConfig = {
  1387. dataDir,
  1388. permissionMode: 'bypassPermissions',
  1389. } as LocalRuntimeConfig;
  1390. const ruleStore = new LocalPermissionRuleStore(() => dataDir);
  1391. const deps: LocalPermissionFacadeDeps = {
  1392. ruleStore,
  1393. configGetter: () => config,
  1394. // Simulate the user flipping back to `default` while the
  1395. // raw pipeline is awaiting working-directory resolution.
  1396. // Without the snapshot fix, the wrapper had already captured
  1397. // 'bypassPermissions' and the raw pipeline would re-read here
  1398. // and see 'default' — two different modes in one call.
  1399. getSessionById: async () => {
  1400. config.permissionMode = 'default';
  1401. return undefined;
  1402. },
  1403. getLocalAgent: async () => undefined,
  1404. };
  1405. const facade = new LocalPermissionFacade(deps);
  1406. const r = await facade.checkPermission({
  1407. toolName: 'read',
  1408. input: { path: '/Users/someone/.ssh/id_rsa' },
  1409. });
  1410. // With the snapshot: BOTH halves see bypassPermissions, so the
  1411. // user-visible product semantics ("Always allow = no card") apply
  1412. // consistently. The verdict is `allow` (gate downgrade) — the
  1413. // attribute we pin is that it's NOT a half-broken state where
  1414. // the raw pipeline returned an engine ASK (because it saw the
  1415. // post-flip 'default') AND the gate then downgrade-allowed it
  1416. // using the pre-flip 'bypassPermissions' snapshot. We assert
  1417. // the reason carries the bypass marker, which is only possible
  1418. // if the gate had a consistent bypass snapshot AND raw returned
  1419. // some ASK that the gate downgraded.
  1420. expect(r.behavior).toBe('allow');
  1421. expect(r.reason).toMatch(/bypassPermissions|始终允许/);
  1422. } finally {
  1423. cleanup(dataDir);
  1424. }
  1425. });
  1426. it('user flipping default → bypass mid-await does NOT pollute gate with stale default', async () => {
  1427. const dataDir = mkdtempSync(path.join(tmpdir(), 'aa-facade-race-'));
  1428. try {
  1429. const config: LocalRuntimeConfig = {
  1430. dataDir,
  1431. permissionMode: 'default',
  1432. } as LocalRuntimeConfig;
  1433. const ruleStore = new LocalPermissionRuleStore(() => dataDir);
  1434. const deps: LocalPermissionFacadeDeps = {
  1435. ruleStore,
  1436. configGetter: () => config,
  1437. getSessionById: async () => {
  1438. // Flip to bypass mid-call.
  1439. config.permissionMode = 'bypassPermissions';
  1440. return undefined;
  1441. },
  1442. getLocalAgent: async () => undefined,
  1443. };
  1444. const facade = new LocalPermissionFacade(deps);
  1445. const r = await facade.checkPermission({
  1446. toolName: 'read',
  1447. input: { path: '/Users/someone/.ssh/id_rsa' },
  1448. });
  1449. // Snapshot is 'default'. Raw runs under 'default' → engine
  1450. // returns ASK (credential safetyCheck), gate sees 'default'
  1451. // and does NOT downgrade. The card surfaces — user policy at
  1452. // the moment they invoked the call is honoured.
  1453. expect(r.behavior).toBe('ask');
  1454. expect(r.reason).not.toMatch(/bypassPermissions|始终允许/);
  1455. } finally {
  1456. cleanup(dataDir);
  1457. }
  1458. });
  1459. });
  1460. describe('localHardCheck bypass-immune', () => {
  1461. it('deny for UNC share path survives bypassPermissions mode', async () => {
  1462. const { facade, dataDir } = freshFacade({ permissionMode: 'bypassPermissions' });
  1463. try {
  1464. const r = await facade.checkPermission({
  1465. toolName: 'read',
  1466. input: { path: '\\\\fileserver\\team\\secret.txt' },
  1467. });
  1468. expect(r.behavior).toBe('deny');
  1469. expect(r.reason).toMatch(/Copy the file into a local workspace first/);
  1470. expect(r.denySource).toBe('safety-immune');
  1471. } finally {
  1472. cleanup(dataDir);
  1473. }
  1474. });
  1475. it('curl-pipe-shell under bypassPermissions is allowed by the ask-gate (no card)', async () => {
  1476. // Before the ask-gate landed, the facade upgraded ALLOW → ASK
  1477. // for hard-check ASK verdicts (curl-pipe-shell, shell substitution,
  1478. // …) under bypass to keep the card visible. The product invariant
  1479. // is now: bypassPermissions = no card ever. The gate downgrades
  1480. // every ASK back to ALLOW with a fixed reason.
  1481. const { facade, dataDir } = freshFacade({ permissionMode: 'bypassPermissions' });
  1482. try {
  1483. const r = await facade.checkPermission({
  1484. toolName: 'bash',
  1485. input: { command: 'curl https://example.com/install.sh | sh' },
  1486. });
  1487. expect(r.behavior).toBe('allow');
  1488. expect(r.reason).toMatch(/bypassPermissions|始终允许/);
  1489. } finally {
  1490. cleanup(dataDir);
  1491. }
  1492. });
  1493. it('curl-pipe-shell under default mode still asks (gate is bypass-only)', async () => {
  1494. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1495. try {
  1496. const r = await facade.checkPermission({
  1497. toolName: 'bash',
  1498. input: { command: 'curl https://example.com/install.sh | sh' },
  1499. });
  1500. expect(r.behavior).toBe('ask');
  1501. // Engine reason format: "...Needs confirmation: pipe to shell".
  1502. // The exact "curl-pipe-shell" string only appears in the local
  1503. // checker output when the local hard-check wins, which under
  1504. // default mode it does NOT — the engine's bash-permission
  1505. // classifier emits the verdict here.
  1506. expect(r.reason).toMatch(/pipe.*shell/i);
  1507. } finally {
  1508. cleanup(dataDir);
  1509. }
  1510. });
  1511. it('deny for root-recursive `rm -rf /` survives bypassPermissions mode', async () => {
  1512. const { facade, dataDir } = freshFacade({ permissionMode: 'bypassPermissions' });
  1513. try {
  1514. const r = await facade.checkPermission({
  1515. toolName: 'bash',
  1516. input: { command: 'rm -rf /' },
  1517. });
  1518. expect(r.behavior).toBe('deny');
  1519. expect(r.reason).toMatch(/recursive deletion targets a root or home directory/);
  1520. expect(r.reason).toMatch(/unrecoverable/);
  1521. expect(r.denySource).toBe('safety-immune');
  1522. } finally {
  1523. cleanup(dataDir);
  1524. }
  1525. });
  1526. });
  1527. describe('denySource attribution (deny verdicts carry their origin)', () => {
  1528. it('HARD final-deny (shred, irrecoverable) is tagged safety', async () => {
  1529. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1530. try {
  1531. const r = await facade.checkPermission({
  1532. toolName: 'bash',
  1533. input: { command: 'shred -u secret.txt' },
  1534. });
  1535. expect(r.behavior).toBe('deny');
  1536. expect(r.denySource).toBe('safety');
  1537. } finally {
  1538. cleanup(dataDir);
  1539. }
  1540. });
  1541. it('user-configured deny rule is tagged rule', async () => {
  1542. const { facade, ruleStore, dataDir } = freshFacade({ permissionMode: 'default' });
  1543. try {
  1544. await ruleStore.applyUpdate({
  1545. type: 'addRules',
  1546. source: 'global',
  1547. destination: 'global',
  1548. behavior: 'deny',
  1549. rules: [{ tool_name: 'bash', rule_content: 'npm publish' }],
  1550. });
  1551. const r = await facade.checkPermission({
  1552. toolName: 'bash',
  1553. input: { command: 'npm publish' },
  1554. });
  1555. expect(r.behavior).toBe('deny');
  1556. expect(r.denySource).toBe('rule');
  1557. } finally {
  1558. cleanup(dataDir);
  1559. }
  1560. });
  1561. it('non-bash deny rule (direct rule reason, not subcommandResults) is tagged rule', async () => {
  1562. const { facade, ruleStore, dataDir } = freshFacade({ permissionMode: 'default' });
  1563. try {
  1564. await ruleStore.applyUpdate({
  1565. type: 'addRules',
  1566. source: 'session',
  1567. destination: 'session-x',
  1568. behavior: 'deny',
  1569. rules: [{ tool_name: 'write' }],
  1570. });
  1571. const r = await facade.checkPermission({
  1572. toolName: 'write',
  1573. input: { file_path: '/tmp/out.txt', content: 'x' },
  1574. sessionId: 'session-x',
  1575. });
  1576. expect(r.behavior).toBe('deny');
  1577. expect(r.denySource).toBe('rule');
  1578. } finally {
  1579. cleanup(dataDir);
  1580. }
  1581. });
  1582. });
  1583. describe('localHardCheck policy deny (sensitive credential paths)', () => {
  1584. // v1 routed credential reads to the LLM gate / user, not a flat deny.
  1585. // Facade must preserve this so "Always allow" can still read ~/.ssh and
  1586. // default mode still gives the user (or auto classifier) the option
  1587. // to authorize.
  1588. it('sensitive credential path under bypassPermissions → allow (gate downgrades ask)', async () => {
  1589. const { facade, dataDir } = freshFacade({ permissionMode: 'bypassPermissions' });
  1590. try {
  1591. const r = await facade.checkPermission({
  1592. toolName: 'read',
  1593. input: { path: '/Users/someone/.ssh/id_rsa' },
  1594. });
  1595. // Under bypass, the policy-deny short-circuit is skipped so the
  1596. // engine runs. The engine then asks (credential safetyCheck) and
  1597. // the gate downgrades that ask to allow with a fixed reason.
  1598. // The product contract is: bypassPermissions = no card ever,
  1599. // including for credential paths.
  1600. expect(r.behavior).toBe('allow');
  1601. expect(r.reason).toMatch(/bypassPermissions|始终允许/);
  1602. } finally {
  1603. cleanup(dataDir);
  1604. }
  1605. });
  1606. it('sensitive credential path under default mode → ask (not deny)', async () => {
  1607. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1608. try {
  1609. const r = await facade.checkPermission({
  1610. toolName: 'read',
  1611. input: { path: '/Users/someone/.ssh/id_rsa' },
  1612. });
  1613. // engine + facade both route credential reads to ask. Either
  1614. // route is acceptable; what we pin is "not deny" and that the
  1615. // reason explains it's a credential/private-key concern.
  1616. expect(r.behavior).toBe('ask');
  1617. expect(r.reason).toMatch(/credential|private[- ]key|sensitive/i);
  1618. } finally {
  1619. cleanup(dataDir);
  1620. }
  1621. });
  1622. });
  1623. describe('sandbox self-paths (dataDir auto-allow)', () => {
  1624. // Reads of mavis's own runtime data (skills, sessions, agent configs)
  1625. // are not "external filesystem access" — they're the agent operating
  1626. // on its own application directory. The facade injects `cfg.dataDir`
  1627. // and `~/.minimax` into `sandboxAllowPaths`; fs-permission's
  1628. // step-5 sandbox branch then allows reads and writes of those paths
  1629. // without an ask card.
  1630. it('default mode: read of a SKILL.md inside dataDir auto-allows (no card)', async () => {
  1631. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1632. try {
  1633. const r = await facade.checkPermission({
  1634. toolName: 'read',
  1635. input: { path: path.join(dataDir, 'skills', 'gif', 'SKILL.md') },
  1636. });
  1637. expect(r.behavior).toBe('allow');
  1638. } finally {
  1639. cleanup(dataDir);
  1640. }
  1641. });
  1642. it('auto mode: read of a SKILL.md inside dataDir auto-allows without cloud call', async () => {
  1643. const calls: Array<unknown> = [];
  1644. const gw: CloudGatewayClient = {
  1645. async classify(req): Promise<CloudClassifyVerdict> {
  1646. calls.push(req);
  1647. return { kind: 'allow', reasonLocalized: 'ok' };
  1648. },
  1649. };
  1650. const { facade, dataDir } = freshFacade({ permissionMode: 'auto', cloudGateway: gw });
  1651. try {
  1652. const r = await facade.checkPermission({
  1653. toolName: 'read',
  1654. input: { path: path.join(dataDir, 'skills', 'gif', 'SKILL.md') },
  1655. });
  1656. // sandbox allow short-circuits BEFORE the cloud-gateway branch:
  1657. // we want the SKILL.md read to be free without paying a network
  1658. // round-trip per call.
  1659. expect(r.behavior).toBe('allow');
  1660. expect(calls.length).toBe(0);
  1661. } finally {
  1662. cleanup(dataDir);
  1663. }
  1664. });
  1665. it('write to a path inside dataDir still ASKs (sandbox is read-only)', async () => {
  1666. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1667. try {
  1668. const r = await facade.checkPermission({
  1669. toolName: 'write',
  1670. input: { path: path.join(dataDir, 'skills', 'generated', 'SKILL.md') },
  1671. });
  1672. // Writes to dataDir go through normal review. The sandbox
  1673. // auto-allow is scoped to READ-ONLY tools because fs-permission's
  1674. // credential / .env / sensitive-git-file safeguards run BEFORE
  1675. // sandbox-allow on the read side, but NOT on the write side —
  1676. // auto-allowing writes would let an agent silently create
  1677. // `<dataDir>/.aws/credentials` etc. in default/auto mode.
  1678. expect(r.behavior).toBe('ask');
  1679. } finally {
  1680. cleanup(dataDir);
  1681. }
  1682. });
  1683. it('write to a credential path inside dataDir still ASKs (defence-in-depth)', async () => {
  1684. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1685. try {
  1686. const r = await facade.checkPermission({
  1687. toolName: 'write',
  1688. input: { path: path.join(dataDir, '.aws', 'credentials') },
  1689. });
  1690. // Even if a future refactor accidentally re-introduces a
  1691. // dataDir write allow, this case must keep prompting.
  1692. expect(r.behavior).toBe('ask');
  1693. } finally {
  1694. cleanup(dataDir);
  1695. }
  1696. });
  1697. it('glob inside dataDir auto-allows (read-only sibling of read)', async () => {
  1698. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1699. try {
  1700. const r = await facade.checkPermission({
  1701. toolName: 'glob',
  1702. input: { path: dataDir, pattern: 'skills/*/SKILL.md' },
  1703. });
  1704. // glob/grep/list share the read-only tool set with `read`; they
  1705. // should auto-allow on self-paths for the same reason.
  1706. expect(r.behavior).toBe('allow');
  1707. } finally {
  1708. cleanup(dataDir);
  1709. }
  1710. });
  1711. it('sensitive file under dataDir still ASKs (credential check runs first)', async () => {
  1712. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1713. try {
  1714. const r = await facade.checkPermission({
  1715. toolName: 'read',
  1716. input: { path: path.join(dataDir, '.aws', 'credentials') },
  1717. });
  1718. // sandboxAllowPaths sits BEHIND the credential-file check in
  1719. // fs-permission.ts:831. A stray credentials file under dataDir
  1720. // must still go through user / classifier review — sandbox
  1721. // does NOT widen the secret-read attack surface.
  1722. expect(r.behavior).toBe('ask');
  1723. expect(r.reason).toMatch(/credential|private[- ]key|sensitive/i);
  1724. } finally {
  1725. cleanup(dataDir);
  1726. }
  1727. });
  1728. it('read outside dataDir + outside workspace still ASKs (sandbox is targeted)', async () => {
  1729. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1730. try {
  1731. const r = await facade.checkPermission({
  1732. toolName: 'read',
  1733. input: { path: '/Users/someone/some-random-project/notes.md' },
  1734. });
  1735. // The sandbox allow is for mavis's own dataDir only. A random
  1736. // external path still requires the normal ask flow.
  1737. expect(r.behavior).toBe('ask');
  1738. expect(r.hookAutoApprovalEligible).toBe(true);
  1739. } finally {
  1740. cleanup(dataDir);
  1741. }
  1742. });
  1743. it('does not mark a credential safety prompt as Hook-auto-approvable', async () => {
  1744. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1745. try {
  1746. const r = await facade.checkPermission({
  1747. toolName: 'read',
  1748. input: { path: '/Users/someone/.ssh/id_rsa' },
  1749. });
  1750. expect(r.behavior).toBe('ask');
  1751. expect(r.hookAutoApprovalEligible).toBeUndefined();
  1752. } finally {
  1753. cleanup(dataDir);
  1754. }
  1755. });
  1756. });
  1757. describe('turn-scoped trusted exact writes', () => {
  1758. it('allows only the supplied exact Plan target without persisting a rule', async () => {
  1759. const { facade, ruleStore, dataDir } = freshFacade({ permissionMode: 'default' });
  1760. const planPath = path.join(dataDir, 'v2', 'sessions', 'session-a', 'artifacts', 'plan.md');
  1761. try {
  1762. await expect(
  1763. facade.checkPermission({
  1764. toolName: 'write',
  1765. input: { path: planPath, content: '# Plan' },
  1766. sessionId: 'session-a',
  1767. trustedExactWritePaths: [planPath],
  1768. }),
  1769. ).resolves.toMatchObject({ behavior: 'allow' });
  1770. await expect(
  1771. facade.checkPermission({
  1772. toolName: 'write',
  1773. input: { path: `${planPath}.bak`, content: '# Escape' },
  1774. sessionId: 'session-a',
  1775. trustedExactWritePaths: [planPath],
  1776. }),
  1777. ).resolves.toMatchObject({ behavior: 'ask' });
  1778. await expect(ruleStore.listRules({ sessionId: 'session-a' })).resolves.toEqual([]);
  1779. } finally {
  1780. cleanup(dataDir);
  1781. }
  1782. });
  1783. });
  1784. describe('localeHint', () => {
  1785. it('returns zh reason when inline user messages are Chinese', async () => {
  1786. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1787. try {
  1788. const r = await facade.checkPermission({
  1789. toolName: 'bash',
  1790. input: { command: 'npm publish' },
  1791. latestUserMessages: [
  1792. { role: 'user', msg_content: '请帮我把这个包发布到 npm registry。' },
  1793. ] as never,
  1794. });
  1795. expect(r.behavior).toBe('ask');
  1796. // zh formatDecisionReason uses CJK punctuation / characters.
  1797. expect(/[一-鿿]/.test(r.reason)).toBe(true);
  1798. } finally {
  1799. cleanup(dataDir);
  1800. }
  1801. });
  1802. it('returns en reason when inline messages are English', async () => {
  1803. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1804. try {
  1805. const r = await facade.checkPermission({
  1806. toolName: 'bash',
  1807. input: { command: 'npm publish' },
  1808. latestUserMessages: [
  1809. { role: 'user', msg_content: 'Please publish this package to npm.' },
  1810. ] as never,
  1811. });
  1812. expect(r.behavior).toBe('ask');
  1813. expect(/[一-鿿]/.test(r.reason)).toBe(false);
  1814. } finally {
  1815. cleanup(dataDir);
  1816. }
  1817. });
  1818. it('falls back to en for unknown locale (empty inline)', async () => {
  1819. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1820. try {
  1821. const r = await facade.checkPermission({
  1822. toolName: 'bash',
  1823. input: { command: 'npm publish' },
  1824. latestUserMessages: [],
  1825. });
  1826. expect(r.behavior).toBe('ask');
  1827. expect(/[一-鿿]/.test(r.reason)).toBe(false);
  1828. } finally {
  1829. cleanup(dataDir);
  1830. }
  1831. });
  1832. });
  1833. describe('rewrittenInput (rm → mavis-trash)', () => {
  1834. it('preserves rewrittenInput and exposes the complete production execution plan', async () => {
  1835. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1836. try {
  1837. const r = await facade.checkPermission({
  1838. toolName: 'bash',
  1839. input: { command: 'rm -rf ./tmp-build', timeout: 9 },
  1840. });
  1841. // The rm → mavis-trash rewrite is engine-side and exposed via
  1842. // rewrittenInput regardless of behavior. We just pin its existence
  1843. // through the facade so a future change that swallows the field
  1844. // surfaces as a failing test.
  1845. expect(r.rewrittenInput).toBeDefined();
  1846. expect(r.executionPlan).toMatchObject({
  1847. originalInput: { command: 'rm -rf ./tmp-build', timeout: 9 },
  1848. effectiveInput: { command: expect.stringContaining('mavis-trash'), timeout: 9 },
  1849. transforms: [{ type: 'recoverable-delete' }],
  1850. });
  1851. } finally {
  1852. cleanup(dataDir);
  1853. }
  1854. });
  1855. it('exposes an empty-transform plan for a non-destructive call', async () => {
  1856. const { facade, dataDir } = freshFacade({ permissionMode: 'default' });
  1857. try {
  1858. const r = await facade.checkPermission({
  1859. toolName: 'bash',
  1860. input: { command: 'git status', timeout: 9 },
  1861. });
  1862. expect(r.executionPlan).toMatchObject({
  1863. originalInput: { command: 'git status', timeout: 9 },
  1864. effectiveInput: { command: 'git status', timeout: 9 },
  1865. transforms: [],
  1866. });
  1867. } finally {
  1868. cleanup(dataDir);
  1869. }
  1870. });
  1871. it('resolves tilde targets with the same home context used by the permission checker', async () => {
  1872. const { facade, dataDir } = freshFacade({
  1873. permissionMode: 'default',
  1874. workspaceDir: '/workspace',
  1875. });
  1876. try {
  1877. const target = path.join(homedir(), 'Desktop', 'permission-plan-output.log');
  1878. const r = await facade.checkPermission({
  1879. toolName: 'bash',
  1880. input: { command: 'rm ~/Desktop/permission-plan-output.log' },
  1881. });
  1882. expect(r.executionPlan).toMatchObject({
  1883. intents: [
  1884. {
  1885. kind: 'filesystem',
  1886. action: 'delete',
  1887. paths: [{ raw: '~/Desktop/permission-plan-output.log', resolved: target }],
  1888. },
  1889. ],
  1890. transforms: [{ type: 'recoverable-delete', targets: [target] }],
  1891. });
  1892. } finally {
  1893. cleanup(dataDir);
  1894. }
  1895. });
  1896. });
  1897. describe('cloud gateway (auto mode)', () => {
  1898. // We exercise the cloud-gateway branch by forcing shouldUseCloudClassify
  1899. // via an injected gateway and a managed-runtime fixture. Since
  1900. // shouldUseCloudClassify() reads runtime host state and we cannot easily
  1901. // enable it from a unit test without poking module internals, we instead
  1902. // verify the facade fall-through path (skipAutoClassifier OR no managed
  1903. // runtime → ask without calling the gateway).
  1904. it('auto mode without managed-runtime token falls through to ask without calling gateway', async () => {
  1905. const calls: CloudClassifyRequest[] = [];
  1906. const gw: CloudGatewayClient = {
  1907. async classify(req): Promise<CloudClassifyVerdict> {
  1908. calls.push(req);
  1909. return { kind: 'allow', reasonLocalized: 'ok' };
  1910. },
  1911. };
  1912. const { facade, dataDir } = freshFacade({ permissionMode: 'auto', cloudGateway: gw });
  1913. try {
  1914. const r = await facade.checkPermission({
  1915. toolName: 'bash',
  1916. input: { command: 'npm publish' },
  1917. });
  1918. // No managed token in unit test → shouldUseCloudClassify() = false
  1919. // → gateway not called.
  1920. expect(calls.length).toBe(0);
  1921. expect(r.behavior).toBe('ask');
  1922. } finally {
  1923. cleanup(dataDir);
  1924. }
  1925. });
  1926. });
  1927. describe('acceptEdits seeding', () => {
  1928. it('syncAcceptEditsSeed adds 3 global allow rules; idempotent', async () => {
  1929. const { facade, ruleStore, dataDir } = freshFacade({ permissionMode: 'acceptEdits' });
  1930. try {
  1931. await facade.syncAcceptEditsSeed();
  1932. const after = await ruleStore.listRules({});
  1933. const seeded = after.filter(
  1934. (r) =>
  1935. r.source === 'global' &&
  1936. r.ruleBehavior === 'allow' &&
  1937. ['edit', 'write', 'apply_patch'].includes(r.ruleValue.toolName) &&
  1938. !r.ruleValue.ruleContent,
  1939. );
  1940. expect(seeded.length).toBe(3);
  1941. // Re-running must not duplicate.
  1942. await facade.syncAcceptEditsSeed();
  1943. const after2 = await ruleStore.listRules({});
  1944. const seeded2 = after2.filter(
  1945. (r) =>
  1946. r.source === 'global' &&
  1947. r.ruleBehavior === 'allow' &&
  1948. ['edit', 'write', 'apply_patch'].includes(r.ruleValue.toolName) &&
  1949. !r.ruleValue.ruleContent,
  1950. );
  1951. expect(seeded2.length).toBe(3);
  1952. } finally {
  1953. cleanup(dataDir);
  1954. }
  1955. });
  1956. it('does not seed when persisted mode is not acceptEdits', async () => {
  1957. const { facade, ruleStore, dataDir } = freshFacade({ permissionMode: 'default' });
  1958. try {
  1959. await facade.syncAcceptEditsSeed();
  1960. const after = await ruleStore.listRules({});
  1961. const seeded = after.filter((r) => r.source === 'global' && r.ruleBehavior === 'allow');
  1962. expect(seeded.length).toBe(0);
  1963. } finally {
  1964. cleanup(dataDir);
  1965. }
  1966. });
  1967. });
  1968. });