|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2026 Google LLC |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +import { type ParsedSandboxDenial } from '../../services/sandboxManager.js'; |
| 8 | +import type { ShellExecutionResult } from '../../services/shellExecutionService.js'; |
| 9 | + |
| 10 | +/** |
| 11 | + * Common POSIX-style sandbox denial detection. |
| 12 | + * Used by macOS and Linux sandbox managers. |
| 13 | + */ |
| 14 | +export function parsePosixSandboxDenials( |
| 15 | + result: ShellExecutionResult, |
| 16 | +): ParsedSandboxDenial | undefined { |
| 17 | + const output = result.output || ''; |
| 18 | + const errorOutput = result.error?.message; |
| 19 | + const combined = (output + ' ' + (errorOutput || '')).toLowerCase(); |
| 20 | + |
| 21 | + const isFileDenial = [ |
| 22 | + 'operation not permitted', |
| 23 | + 'vim:e303', |
| 24 | + 'should be read/write', |
| 25 | + 'sandbox_apply', |
| 26 | + 'sandbox: ', |
| 27 | + ].some((keyword) => combined.includes(keyword)); |
| 28 | + |
| 29 | + const isNetworkDenial = [ |
| 30 | + 'error connecting to', |
| 31 | + 'network is unreachable', |
| 32 | + 'could not resolve host', |
| 33 | + 'connection refused', |
| 34 | + 'no address associated with hostname', |
| 35 | + ].some((keyword) => combined.includes(keyword)); |
| 36 | + |
| 37 | + if (!isFileDenial && !isNetworkDenial) { |
| 38 | + return undefined; |
| 39 | + } |
| 40 | + |
| 41 | + const filePaths = new Set<string>(); |
| 42 | + |
| 43 | + // Extract denied paths (POSIX absolute paths) |
| 44 | + const regex = |
| 45 | + /(?:^|\s)['"]?(\/[\w.-/]+)['"]?:\s*[Oo]peration not permitted/gi; |
| 46 | + let match; |
| 47 | + while ((match = regex.exec(output)) !== null) { |
| 48 | + filePaths.add(match[1]); |
| 49 | + } |
| 50 | + if (errorOutput) { |
| 51 | + while ((match = regex.exec(errorOutput)) !== null) { |
| 52 | + filePaths.add(match[1]); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // Fallback heuristic: look for any absolute path in the output if it was a file denial |
| 57 | + if (isFileDenial && filePaths.size === 0) { |
| 58 | + const fallbackRegex = |
| 59 | + /(?:^|[\s"'[\]])(\/[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)+)(?:$|[\s"'[\]:])/gi; |
| 60 | + let m; |
| 61 | + while ((m = fallbackRegex.exec(output)) !== null) { |
| 62 | + const p = m[1]; |
| 63 | + if (p && !p.startsWith('/bin/') && !p.startsWith('/usr/bin/')) { |
| 64 | + filePaths.add(p); |
| 65 | + } |
| 66 | + } |
| 67 | + if (errorOutput) { |
| 68 | + while ((m = fallbackRegex.exec(errorOutput)) !== null) { |
| 69 | + const p = m[1]; |
| 70 | + if (p && !p.startsWith('/bin/') && !p.startsWith('/usr/bin/')) { |
| 71 | + filePaths.add(p); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return { |
| 78 | + network: isNetworkDenial || undefined, |
| 79 | + filePaths: filePaths.size > 0 ? Array.from(filePaths) : undefined, |
| 80 | + }; |
| 81 | +} |
0 commit comments