permission-core.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import { matchesMcpServerRuntimeName } from './mcp-runtime-name.js';
  2. import {
  3. getContentRulesForTool,
  4. hasWholeToolRule,
  5. isBypassMode,
  6. isInteractiveTool,
  7. type ToolPermissionContext,
  8. } from './context.js';
  9. import type {
  10. DecisionReason,
  11. PermissionBehavior,
  12. PermissionDecision,
  13. PermissionMode,
  14. PermissionRule,
  15. ToolCheckResult,
  16. } from './types.js';
  17. export type PermissionPolicyOwner = 'engine' | 'core';
  18. export interface PermissionCheckOptions {
  19. policyOwner?: PermissionPolicyOwner;
  20. onCheckerDecision?: (trace: PermissionCheckerDecisionTrace) => void;
  21. }
  22. /** Checker output exposed only for host-side observability; hosts own log filtering. */
  23. export interface PermissionCheckerDecisionTrace {
  24. checkerRegistered: boolean;
  25. checkerBehavior: ToolCheckResult['behavior'] | 'none' | 'error';
  26. reasonType?: ToolCheckResult['reason']['type'];
  27. /** Complete checker reason; the host decides which fields enter diagnostics. */
  28. reason?: DecisionReason;
  29. rewriteApplied: boolean;
  30. ruleCount: number;
  31. skipAutoClassifier: boolean;
  32. }
  33. export interface PermissionCoreDecisionInput {
  34. toolName: string;
  35. input: Record<string, unknown>;
  36. context: ToolPermissionContext;
  37. checkerRegistered: boolean;
  38. checkerResult?: ToolCheckResult;
  39. checkerError?: string;
  40. }
  41. export type PermissionAction = 'read' | 'write' | 'delete' | 'execute' | 'network';
  42. export type ShellFamily = 'posix' | 'cmd' | 'powershell' | 'unknown';
  43. export type PathValue = {
  44. /** Original path found in the command, preserving the user's input form. */
  45. raw: string;
  46. /** Path resolved in the current session's homeDir/workingDirectory context. */
  47. resolved?: string;
  48. /** Whether environment variables, globs, or other dynamic semantics may still affect the path. */
  49. dynamic: boolean;
  50. /** How to interpret the original path: expand ~ to home; keep relative paths relative. */
  51. resolution?: 'absolute' | 'relative' | 'home' | 'environment' | 'glob' | 'unknown';
  52. };
  53. export type CommandIntent =
  54. | {
  55. kind: 'filesystem';
  56. action: Extract<PermissionAction, 'read' | 'write' | 'delete'>;
  57. paths: PathValue[];
  58. recursive?: boolean;
  59. force?: boolean;
  60. shell: ShellFamily;
  61. }
  62. | {
  63. kind: 'execute';
  64. program?: string;
  65. argv: string[];
  66. shell: ShellFamily;
  67. dynamic: boolean;
  68. }
  69. | {
  70. kind: 'network';
  71. targets: string[];
  72. method?: string;
  73. shell: ShellFamily;
  74. dynamic: boolean;
  75. }
  76. | {
  77. kind: 'script';
  78. interpreter?: string;
  79. path?: PathValue;
  80. shell: ShellFamily;
  81. dynamic: boolean;
  82. }
  83. | { kind: 'opaque'; shell: ShellFamily; raw: string; reason: string };
  84. export type PermissionEvidence =
  85. | { kind: 'host-deny'; reason: string }
  86. | { kind: 'user-rule'; behavior: PermissionBehavior; ruleContent?: string }
  87. | { kind: 'path-capability'; action: PermissionAction; path: string; allowed: boolean }
  88. | { kind: 'built-in-allow'; reason: string }
  89. | { kind: 'classifier-eligible'; reason: string }
  90. | { kind: 'classifier-ineligible'; reason: string }
  91. | { kind: 'classifier-result'; behavior: PermissionBehavior; reason: string }
  92. | { kind: 'legacy-reason'; value: unknown }
  93. | { kind: 'legacy-deny'; reason: string };
  94. export type ExecutionTransform = { type: 'recoverable-delete'; targets: string[] };
  95. export type ExecutionPlan = {
  96. originalInput: Record<string, unknown>;
  97. effectiveInput: Record<string, unknown>;
  98. intents: CommandIntent[];
  99. transforms: ExecutionTransform[];
  100. };
  101. export type PermissionModeProfile = {
  102. /** Whether user interaction is available; fail closed in headless mode without an approval channel. */
  103. interaction: 'ask' | 'neverAsk' | 'headless-fail-closed';
  104. /** Whether to allow supplementary LLM/classifier decisions; does not affect host safety or explicit denies. */
  105. classifier: 'allowed' | 'forbidden';
  106. /** Whether permissions are a hard execution gate; off means the permission layer does not block execution. */
  107. enforcement: 'strict' | 'off';
  108. /** Whether the bypass evaluator may run; this does not bypass host safety. */
  109. bypass: 'allowed' | 'forbidden';
  110. };
  111. export type PermissionEvaluationInput = {
  112. toolName: string;
  113. input: Record<string, unknown>;
  114. evidence: PermissionEvidence[];
  115. executionPlan?: ExecutionPlan;
  116. mode: PermissionModeProfile;
  117. context: {
  118. workingDirectory: string;
  119. homeDir: string;
  120. dataDir: string;
  121. sessionId?: string;
  122. agentName?: string;
  123. };
  124. };
  125. export type PermissionApprovalRequest = {
  126. requestId: string;
  127. sessionId: string;
  128. agentName?: string;
  129. toolName: string;
  130. toolInput?: string;
  131. reason: string;
  132. ruleContents: string[];
  133. allowAlwaysSupported: boolean;
  134. };
  135. export type PermissionEvaluation =
  136. | { outcome: 'allow'; reason: string; executionPlan?: ExecutionPlan }
  137. | { outcome: 'ask'; request: PermissionApprovalRequest; executionPlan?: ExecutionPlan }
  138. | { outcome: 'deny'; reason: string };
  139. /**
  140. * Production policy reducer used when Core owns the final decision. Existing
  141. * tool checkers keep their local ToolCheckResult interface; this reducer owns
  142. * cross-rule, mode, interactive-tool, and checker-result precedence.
  143. */
  144. export function reducePermissionDecision(input: PermissionCoreDecisionInput): PermissionDecision {
  145. const { toolName, context, checkerResult } = input;
  146. const denyRule =
  147. hasWholeToolRule(context, toolName, 'deny') ?? findMcpServerRule(toolName, context, 'deny');
  148. if (denyRule) return { behavior: 'deny', reason: { type: 'rule', rule: denyRule } };
  149. // A tool/content checker deny is an explicit deny for this invocation. It
  150. // must win over broader whole-tool or MCP ask rules; otherwise adding a
  151. // blanket ask can weaken a command-specific hard block.
  152. if (checkerResult?.behavior === 'deny') {
  153. return { behavior: 'deny', reason: checkerResult.reason };
  154. }
  155. const askRule = hasWholeToolRule(context, toolName, 'ask');
  156. const sandboxBypassesAsk =
  157. toolName === 'bash' && context.sandboxEnabled && context.autoAllowBashIfSandboxed;
  158. if (askRule && !sandboxBypassesAsk) {
  159. return {
  160. behavior: 'ask',
  161. reason: { type: 'rule', rule: askRule },
  162. ruleContents: resolveRuleContents(toolName, input.input, checkerResult),
  163. ruleMatchers: resolveRuleMatchers(checkerResult),
  164. candidateScopes: resolveCandidateScopes(checkerResult),
  165. rewrittenInput: checkerResult?.rewrittenInput,
  166. };
  167. }
  168. const mcpAskRule = findMcpServerRule(toolName, context, 'ask');
  169. if (mcpAskRule) {
  170. return {
  171. behavior: 'ask',
  172. reason: { type: 'rule', rule: mcpAskRule },
  173. ruleContents: resolveRuleContents(toolName, input.input),
  174. };
  175. }
  176. if (input.checkerError) {
  177. return {
  178. behavior: 'ask',
  179. reason: { type: 'safetyCheck', description: `Tool checker error: ${input.checkerError}` },
  180. ruleContents: resolveRuleContents(toolName, input.input),
  181. };
  182. }
  183. if (isInteractiveTool(context, toolName)) {
  184. return {
  185. behavior: 'ask',
  186. reason: {
  187. type: 'safetyCheck',
  188. description: `Tool "${toolName}" requires user interaction`,
  189. },
  190. ruleContents: resolveRuleContents(toolName, input.input, checkerResult),
  191. ruleMatchers: resolveRuleMatchers(checkerResult),
  192. candidateScopes: resolveCandidateScopes(checkerResult),
  193. };
  194. }
  195. if (checkerResult?.behavior === 'ask' && checkerResult.bypassImmune) {
  196. return {
  197. behavior: 'ask',
  198. reason: checkerResult.reason,
  199. ruleContents: resolveRuleContents(toolName, input.input, checkerResult),
  200. ruleMatchers: resolveRuleMatchers(checkerResult),
  201. candidateScopes: resolveCandidateScopes(checkerResult),
  202. bypassImmune: true,
  203. skipAutoClassifier: checkerResult.skipAutoClassifier,
  204. };
  205. }
  206. const contentAskRule = matchesContentAskRule(toolName, input.input, context);
  207. if (contentAskRule) {
  208. return {
  209. behavior: 'ask',
  210. reason: { type: 'rule', rule: contentAskRule },
  211. ruleContents: resolveRuleContents(toolName, input.input, checkerResult),
  212. ruleMatchers: resolveRuleMatchers(checkerResult),
  213. candidateScopes: resolveCandidateScopes(checkerResult),
  214. rewrittenInput: checkerResult?.rewrittenInput,
  215. };
  216. }
  217. if (checkerResult?.behavior === 'ask' && !isBypassMode(context)) {
  218. return {
  219. behavior: 'ask',
  220. reason: checkerResult.reason,
  221. ruleContents: resolveRuleContents(toolName, input.input, checkerResult),
  222. ruleMatchers: resolveRuleMatchers(checkerResult),
  223. candidateScopes: resolveCandidateScopes(checkerResult),
  224. rewrittenInput: checkerResult.rewrittenInput,
  225. skipAutoClassifier: checkerResult.skipAutoClassifier,
  226. };
  227. }
  228. if (isBypassMode(context)) {
  229. return {
  230. behavior: 'allow',
  231. reason: { type: 'mode', mode: 'bypassPermissions' },
  232. rewrittenInput: checkerResult?.rewrittenInput,
  233. };
  234. }
  235. const allowRule =
  236. hasWholeToolRule(context, toolName, 'allow') ?? findMcpServerRule(toolName, context, 'allow');
  237. if (allowRule) {
  238. return {
  239. behavior: 'allow',
  240. reason: { type: 'rule', rule: allowRule },
  241. rewrittenInput: checkerResult?.rewrittenInput,
  242. };
  243. }
  244. if (checkerResult?.behavior === 'allow') {
  245. return {
  246. behavior: 'allow',
  247. reason: checkerResult.reason,
  248. rewrittenInput: checkerResult.rewrittenInput,
  249. };
  250. }
  251. if (!input.checkerRegistered) {
  252. return {
  253. behavior: 'allow',
  254. reason: {
  255. type: 'safetyCheck',
  256. description: `No permission checker registered for tool "${toolName}", allowing by default`,
  257. },
  258. };
  259. }
  260. return {
  261. behavior: 'ask',
  262. reason: {
  263. type: 'safetyCheck',
  264. description: `No permission rule matched for tool "${toolName}"`,
  265. },
  266. ruleContents: resolveRuleContents(toolName, input.input, checkerResult),
  267. ruleMatchers: resolveRuleMatchers(checkerResult),
  268. candidateScopes: resolveCandidateScopes(checkerResult),
  269. rewrittenInput: checkerResult?.rewrittenInput,
  270. };
  271. }
  272. /**
  273. * Fold an external classifier recommendation back through Core policy.
  274. * Classifiers only refine an ASK; they never override a decision that Core
  275. * already finalized as ALLOW or DENY.
  276. */
  277. export function reducePermissionClassifierDecision(
  278. decision: PermissionDecision,
  279. recommendation: Pick<PermissionDecision, 'behavior' | 'reason'>,
  280. ): PermissionDecision {
  281. if (decision.behavior !== 'ask') return decision;
  282. if (recommendation.behavior === 'deny') {
  283. return { behavior: 'deny', reason: recommendation.reason };
  284. }
  285. if (recommendation.behavior === 'allow') {
  286. return {
  287. behavior: 'allow',
  288. reason: recommendation.reason,
  289. rewrittenInput: decision.rewrittenInput,
  290. };
  291. }
  292. return { ...decision, reason: recommendation.reason };
  293. }
  294. function findMcpServerRule(
  295. toolName: string,
  296. context: ToolPermissionContext,
  297. behavior: PermissionBehavior,
  298. ): PermissionRule | undefined {
  299. if (!toolName.startsWith('mcp__')) return undefined;
  300. return context.rules.find(
  301. (rule) =>
  302. rule.ruleBehavior === behavior &&
  303. !rule.ruleValue.ruleContent &&
  304. matchesMcpServerRuntimeName(toolName, rule.ruleValue.toolName),
  305. );
  306. }
  307. function matchesContentAskRule(
  308. toolName: string,
  309. input: Record<string, unknown>,
  310. context: ToolPermissionContext,
  311. ): PermissionRule | undefined {
  312. const inputContent = extractToolInputContent(toolName, input);
  313. if (!inputContent) return undefined;
  314. return getContentRulesForTool(context, toolName, 'ask').find((rule) => {
  315. const ruleContent = rule.ruleValue.ruleContent;
  316. return Boolean(ruleContent && inputContent.includes(ruleContent));
  317. });
  318. }
  319. function extractToolInputContent(
  320. toolName: string,
  321. input: Record<string, unknown>,
  322. ): string | undefined {
  323. if (toolName === 'bash') return typeof input.command === 'string' ? input.command : undefined;
  324. if (['edit', 'write', 'read', 'glob'].includes(toolName)) {
  325. if (typeof input.filePath === 'string') return input.filePath;
  326. if (typeof input.path === 'string') return input.path;
  327. return typeof input.pattern === 'string' ? input.pattern : undefined;
  328. }
  329. if (typeof input.command === 'string') return input.command;
  330. return typeof input.url === 'string' ? input.url : undefined;
  331. }
  332. function resolveRuleContents(
  333. toolName: string,
  334. input: Record<string, unknown>,
  335. checkerResult?: ToolCheckResult,
  336. ): string[] | undefined {
  337. if (checkerResult?.ruleContents?.length) return checkerResult.ruleContents;
  338. const content = extractToolInputContent(toolName, input);
  339. return content ? [content] : undefined;
  340. }
  341. function resolveCandidateScopes(
  342. checkerResult?: ToolCheckResult,
  343. ): PermissionDecision['candidateScopes'] {
  344. if (!checkerResult?.ruleContents?.length) return undefined;
  345. return checkerResult.candidateScopes?.length ? checkerResult.candidateScopes : undefined;
  346. }
  347. function resolveRuleMatchers(checkerResult?: ToolCheckResult): PermissionDecision['ruleMatchers'] {
  348. if (!checkerResult?.ruleContents?.length) return undefined;
  349. return checkerResult.ruleMatchers?.length === checkerResult.ruleContents.length
  350. ? checkerResult.ruleMatchers
  351. : undefined;
  352. }
  353. export function reducePermissionEvaluation(input: PermissionEvaluationInput): PermissionEvaluation {
  354. const evidence = input.evidence;
  355. const hostDeny = evidence.find((item) => item.kind === 'host-deny');
  356. if (hostDeny?.kind === 'host-deny') return { outcome: 'deny', reason: hostDeny.reason };
  357. const explicitDeny = evidence.find(
  358. (item) => item.kind === 'user-rule' && item.behavior === 'deny',
  359. );
  360. if (explicitDeny?.kind === 'user-rule') {
  361. return { outcome: 'deny', reason: explicitDeny.ruleContent ?? 'explicit user deny' };
  362. }
  363. const legacyDeny = evidence.find((item) => item.kind === 'legacy-deny');
  364. if (legacyDeny?.kind === 'legacy-deny') return { outcome: 'deny', reason: legacyDeny.reason };
  365. const classifierDeny = evidence.find(
  366. (item) => item.kind === 'classifier-result' && item.behavior === 'deny',
  367. );
  368. if (classifierDeny?.kind === 'classifier-result') {
  369. return { outcome: 'deny', reason: classifierDeny.reason };
  370. }
  371. const classifierIneligible = evidence.find((item) => item.kind === 'classifier-ineligible');
  372. const immuneAsk = evidence.find((item) => item.kind === 'user-rule' && item.behavior === 'ask');
  373. const classifierAsk = evidence.find(
  374. (item) => item.kind === 'classifier-result' && item.behavior === 'ask',
  375. );
  376. const explicitAsk = immuneAsk ?? classifierAsk;
  377. const classifierAllow = evidence.some(
  378. (item) => item.kind === 'classifier-result' && item.behavior === 'allow',
  379. );
  380. if (
  381. input.mode.interaction === 'headless-fail-closed' &&
  382. (explicitAsk || classifierIneligible || (!classifierAllow && !hasAllow(evidence)))
  383. ) {
  384. return {
  385. outcome: 'deny',
  386. reason: 'permission requires user confirmation but no approval channel is available',
  387. };
  388. }
  389. if (
  390. explicitAsk ||
  391. classifierIneligible ||
  392. (input.mode.interaction !== 'neverAsk' && !classifierAllow && !hasAllow(evidence))
  393. ) {
  394. return {
  395. outcome: 'ask',
  396. request: buildApprovalRequest(
  397. input,
  398. explicitAsk?.kind === 'user-rule' ? explicitAsk.ruleContent : undefined,
  399. ),
  400. ...(input.executionPlan ? { executionPlan: input.executionPlan } : {}),
  401. };
  402. }
  403. const allow = evidence.find(
  404. (item) =>
  405. (item.kind === 'user-rule' && item.behavior === 'allow') ||
  406. item.kind === 'built-in-allow' ||
  407. (item.kind === 'classifier-result' && item.behavior === 'allow'),
  408. );
  409. if (allow) {
  410. return {
  411. outcome: 'allow',
  412. reason:
  413. allow.kind === 'user-rule' ||
  414. allow.kind === 'built-in-allow' ||
  415. allow.kind === 'classifier-result'
  416. ? allow.kind === 'user-rule'
  417. ? (allow.ruleContent ?? 'explicit user allow')
  418. : allow.reason
  419. : 'permission allowed',
  420. ...(input.executionPlan ? { executionPlan: input.executionPlan } : {}),
  421. };
  422. }
  423. if (input.mode.interaction === 'neverAsk' && input.mode.enforcement === 'strict') {
  424. return { outcome: 'deny', reason: 'permission interaction is disabled' };
  425. }
  426. return {
  427. outcome: 'ask',
  428. request: buildApprovalRequest(input),
  429. ...(input.executionPlan ? { executionPlan: input.executionPlan } : {}),
  430. };
  431. }
  432. function hasAllow(evidence: PermissionEvidence[]): boolean {
  433. return evidence.some(
  434. (item) =>
  435. (item.kind === 'user-rule' && item.behavior === 'allow') ||
  436. item.kind === 'built-in-allow' ||
  437. (item.kind === 'classifier-result' && item.behavior === 'allow'),
  438. );
  439. }
  440. function buildApprovalRequest(
  441. input: PermissionEvaluationInput,
  442. preferredRuleContent?: string,
  443. ): PermissionApprovalRequest {
  444. const ruleContents = input.evidence
  445. .filter(
  446. (item): item is Extract<PermissionEvidence, { kind: 'user-rule' }> =>
  447. item.kind === 'user-rule',
  448. )
  449. .map((item) => item.ruleContent)
  450. .filter((content): content is string => Boolean(content));
  451. if (preferredRuleContent && !ruleContents.includes(preferredRuleContent))
  452. ruleContents.unshift(preferredRuleContent);
  453. return {
  454. requestId: `${input.context.sessionId ?? 'session'}:${input.toolName}`,
  455. sessionId: input.context.sessionId ?? 'unknown',
  456. ...(input.context.agentName ? { agentName: input.context.agentName } : {}),
  457. toolName: input.toolName,
  458. toolInput: formatToolInput(input.input),
  459. reason: 'permission requires approval',
  460. ruleContents,
  461. allowAlwaysSupported: true,
  462. };
  463. }
  464. function formatToolInput(input: Record<string, unknown>): string | undefined {
  465. if (typeof input.command === 'string') return input.command;
  466. if (typeof input.filePath === 'string') return input.filePath;
  467. if (typeof input.file_path === 'string') return input.file_path;
  468. if (typeof input.path === 'string') return input.path;
  469. return undefined;
  470. }
  471. /** Compatibility hook for callers that still hold a legacy mode value. */
  472. export function permissionModeToProfile(mode: PermissionMode): PermissionModeProfile {
  473. if (mode === 'bypassPermissions') {
  474. return {
  475. interaction: 'neverAsk',
  476. classifier: 'forbidden',
  477. enforcement: 'strict',
  478. bypass: 'allowed',
  479. };
  480. }
  481. if (mode === 'off') {
  482. return {
  483. interaction: 'neverAsk',
  484. classifier: 'forbidden',
  485. enforcement: 'off',
  486. bypass: 'allowed',
  487. };
  488. }
  489. if (mode === 'auto') {
  490. return { interaction: 'ask', classifier: 'allowed', enforcement: 'strict', bypass: 'allowed' };
  491. }
  492. return {
  493. interaction: 'ask',
  494. classifier: 'forbidden',
  495. enforcement: 'strict',
  496. bypass: 'forbidden',
  497. };
  498. }