Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(bots): per-bot shell allow-list from permissions.yaml autoApproveCommands

Salman Qureshi04e96b2fd6c2
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.ts
index 427bc4f0..ebb0f0a2 100644
--- a/src/bots/bot-manager.test.ts
+++ b/src/bots/bot-manager.test.ts
@@ -525,6 +525,87 @@ describe('Per-bot permission isolation (fail-closed)', () => {
expect(insideVerdict.allowed).toBe(true);
});
+ describe('bot shell allow-list (autoApproveCommands)', () => {
+ it('runs an allow-listed command in fail-closed mode without prompting', async () => {
+ const manifest = store.create({ id: 'sheller', name: 'Sheller' }) as BotManifest;
+ store.writePermissions('sheller', {
+ paths: [{ scope: 'self', read: true, write: true }],
+ autoApproveCommands: ['node *', 'python3 *'],
+ });
+ const registry = createBotCapabilityRegistry({
+ botId: 'sheller',
+ manifest,
+ botDir: store.botDir('sheller'),
+ permissions: store.readPermissions('sheller'),
+ userMemory: null,
+ config: getDefaultConfig() as MercuryConfig,
+ });
+ const pm = registry.permissions;
+ await expect(pm.checkShellCommand('node script.js --flag')).resolves.toMatchObject({ allowed: true, needsApproval: false });
+ await expect(pm.checkShellCommand('python3 -m foo')).resolves.toMatchObject({ allowed: true, needsApproval: false });
+ // Not on the allow-list: still denied (fail-closed, no ask handler).
+ await expect(pm.checkShellCommand('curl evil.example')).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('needsApproval patterns win over the same autoApprove pattern (deny)', async () => {
+ const manifest = store.create({ id: 'guarded', name: 'Guarded' }) as BotManifest;
+ store.writePermissions('guarded', {
+ paths: [{ scope: 'self', read: true, write: true }],
+ autoApproveCommands: ['npm *'],
+ blockedCommands: ['npm publish *'],
+ });
+ const registry = createBotCapabilityRegistry({
+ botId: 'guarded',
+ manifest,
+ botDir: store.botDir('guarded'),
+ permissions: store.readPermissions('guarded'),
+ userMemory: null,
+ config: getDefaultConfig() as MercuryConfig,
+ });
+ const pm = registry.permissions;
+ await expect(pm.checkShellCommand('npm run build')).resolves.toMatchObject({ allowed: true, needsApproval: false });
+ // blockedCommands always wins — merged into the global blocked list.
+ await expect(pm.checkShellCommand('npm publish @scope/pkg')).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('segments the command: an approved base cannot launder a chained destructive command', async () => {
+ const manifest = store.create({ id: 'chained', name: 'Chained' }) as BotManifest;
+ store.writePermissions('chained', {
+ paths: [{ scope: 'self', read: true, write: true }],
+ autoApproveCommands: ['echo *'],
+ });
+ const registry = createBotCapabilityRegistry({
+ botId: 'chained',
+ manifest,
+ botDir: store.botDir('chained'),
+ permissions: store.readPermissions('chained'),
+ userMemory: null,
+ config: getDefaultConfig() as MercuryConfig,
+ });
+ const pm = registry.permissions;
+ await expect(pm.checkShellCommand('echo hello')).resolves.toMatchObject({ allowed: true, needsApproval: false });
+ await expect(pm.checkShellCommand('echo hi; reboot now')).resolves.toMatchObject({ allowed: false });
+ await expect(pm.checkShellCommand('echo $(rm -rf ~)')).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('rejects a literal "*" autoApprove pattern (no allow-all for bots)', () => {
+ const manifest = store.create({ id: 'greedy', name: 'Greedy' }) as BotManifest;
+ store.writePermissions('greedy', {
+ paths: [{ scope: 'self', read: true, write: true }],
+ autoApproveCommands: ['*'],
+ });
+ const registry = createBotCapabilityRegistry({
+ botId: 'greedy',
+ manifest,
+ botDir: store.botDir('greedy'),
+ permissions: store.readPermissions('greedy'),
+ userMemory: null,
+ config: getDefaultConfig() as MercuryConfig,
+ });
+ expect(registry.permissions.getManifest().capabilities.shell.autoApproved).toEqual([]);
+ });
+ });
+
it('strips interactive and global-mutation tools from every bot toolset', () => {
const manifest = store.create({ id: 'writer', name: 'Writer' }) as BotManifest;
const registry = createBotCapabilityRegistry({
diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.ts
index 3b97851e..2d46b2d3 100644
--- a/src/bots/registry-factory.ts
+++ b/src/bots/registry-factory.ts
@@ -95,7 +95,19 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRe
);
}
manifest.capabilities.filesystem.scopes = buildBotScopes(granted, deps.botDir);
+ // Shell execution: instead of emptying autoApproved (which made every
+ // non-safe-read command deny, breaking browser/file tooling), bots declare
+ // their own allow-list via permissions.yaml autoApproveCommands. It is
+ // carried in a dedicated PermissionManager field (NOT the manifest list)
+ // so an ambient global autoApproved entry can never silently elevate an
+ // unattended context. Fail-closed stays intact: no ask handler,
+ // needsApproval wins, the global blocked list wins, and a literal "*"
+ // grant is dropped (allow-all stays interactive-only).
+ const approvedCommands = (deps.permissions.autoApproveCommands ?? [])
+ .map(c => c.trim())
+ .filter(c => c.length > 0 && c !== '*');
manifest.capabilities.shell.autoApproved = [];
+ pm.setBotShellAllowList(approvedCommands);
manifest.capabilities.shell.blocked = [
...new Set([...manifest.capabilities.shell.blocked, ...(deps.permissions.blockedCommands ?? [])]),
];
diff --git a/src/bots/types.ts b/src/bots/types.ts
index d3f1f120..9d788c14 100644
--- a/src/bots/types.ts
+++ b/src/bots/types.ts
@@ -108,6 +108,15 @@ export interface BotManifest {
export interface BotPermissionsFile {
paths?: BotPathScope[];
blockedCommands?: string[];
+ /**
+ * Shell command patterns this bot may run without approval (e.g.
+ * ["node *", "python3 *"]). Each is merged into the bot registry's
+ * shell.autoApproved list and checked per pipeline segment; the global
+ * blocked-command list still wins, and patterns also present in
+ * needsApproval are treated as denied (needsApproval wins). The literal
+ * "*" (allow-all) is rejected.
+ */
+ autoApproveCommands?: string[];
}
export interface BotPathScope {
diff --git a/src/capabilities/permissions.test.ts b/src/capabilities/permissions.test.ts
index f80af97d..bd0d2f5b 100644
--- a/src/capabilities/permissions.test.ts
+++ b/src/capabilities/permissions.test.ts
@@ -91,6 +91,20 @@ describe('fail-closed execute scopes (bots)', () => {
const permissions = managerWithExecuteScope();
await expect(permissions.checkShellCommand('/tmp/execdir/run.sh --serve')).resolves.toMatchObject({ allowed: true, needsApproval: false });
});
+
+ it('an ambient global autoApproved list never elevates a fail-closed context', async () => {
+ const permissions = managerWithExecuteScope();
+ // Simulate a global permissions.yaml where the user approved "node *":
+ // an unattended bot must NOT inherit it.
+ permissions.getManifest().capabilities.shell.autoApproved = ['node *'];
+ await expect(permissions.checkShellCommand('node script.js')).resolves.toMatchObject({ allowed: false });
+ // Explicit bot grants DO apply.
+ permissions.setBotShellAllowList(['node *']);
+ await expect(permissions.checkShellCommand('node script.js')).resolves.toMatchObject({ allowed: true, needsApproval: false });
+ // needsApproval still wins over the bot list.
+ permissions.getManifest().capabilities.shell.needsApproval = ['node *'];
+ await expect(permissions.checkShellCommand('node script.js')).resolves.toMatchObject({ allowed: false });
+ });
});
describe('fail-closed skill elevation', () => {
@@ -106,6 +120,21 @@ describe('fail-closed skill elevation', () => {
});
});
+describe('most-specific scope wins', () => {
+ it('a deep grant is not shadowed by a broader read-only ancestor', async () => {
+ const permissions = new PermissionManager();
+ permissions.getManifest().capabilities.filesystem.scopes = [
+ { path: '/tmp/root', read: true, write: false },
+ { path: '/tmp/root/deep', read: true, write: true },
+ ];
+ permissions.setFailClosed(true);
+ permissions.setCurrentContext('bot', 'worker');
+ await expect(permissions.checkFsAccess('/tmp/root/deep/file.txt', 'write')).resolves.toMatchObject({ allowed: true });
+ await expect(permissions.checkFsAccess('/tmp/root/other.txt', 'write')).resolves.toMatchObject({ allowed: false });
+ await expect(permissions.checkFsAccess('/tmp/root/other.txt', 'read')).resolves.toMatchObject({ allowed: true });
+ });
+});
+
describe('PermissionManager remote safety', () => {
it('enforces hard command blocks before Local allow-all', async () => {
const permissions = new PermissionManager();
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index bab6e8b4..30ae737b 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -306,6 +306,14 @@ export class PermissionManager {
private tempScopes: FileScope[] = [];
+ /**
+ * Bot-scoped shell allow-list (fail-closed runtimes): patterns the bot's
+ * permissions.yaml explicitly granted. Kept separate from the manifest's
+ * autoApproved so an ambient global list (e.g. a user-approved "node *")
+ * can never silently elevate an unattended context.
+ */
+ private botShellAllowList?: string[];
+
constructor() {
this.cwd = process.cwd();
this.manifest = this.load();
@@ -315,6 +323,21 @@ export class PermissionManager {
this.failClosed = value;
}
+ /**
+ * Bot-only shell allow-list (fail-closed contexts): explicit grants from
+ * the bot's permissions.yaml. A literal "*" is dropped — allow-all is an
+ * interactive-mode concept, not a bot grant.
+ */
+ setBotShellAllowList(patterns: string[]): void {
+ this.botShellAllowList = (patterns ?? [])
+ .map(p => p.trim())
+ .filter(p => p.length > 0 && p !== '*');
+ }
+
+ getBotShellAllowList(): string[] {
+ return [...(this.botShellAllowList ?? [])];
+ }
+
isFailClosed(): boolean {
return this.failClosed;
}
@@ -565,6 +588,30 @@ export class PermissionManager {
}
}
+ // Bot allow-list (fail-closed only): set explicitly by the bot runtime
+ // (registry-factory from permissions.yaml autoApproveCommands) — never
+ // the ambient global autoApproved list, which stays decorative for
+ // unattended contexts. Placement AFTER the cwd-containment gate means a
+ // broad pattern like "cat *" can never launder a path outside granted
+ // scopes; needsApproval wins (the same pattern in both lists means
+ // deny); a bare "*" is rejected at grant time — allow-all is an
+ // interactive-mode concept, not a bot grant. Safe-read commands stay
+ // fully covered by the allSegmentsSafeRead lane below.
+ if (this.failClosed && this.botShellAllowList && this.botShellAllowList.length > 0) {
+ const needsApprovalList = shell.needsApproval ?? [];
+ const botList = this.botShellAllowList;
+ const allSegmentsApproved = segments.every((segment) =>
+ botList.some((pattern) =>
+ pattern.trim() !== '*' && this.matchPattern(segment, pattern)
+ )
+ && !needsApprovalList.some((pattern) => this.matchPattern(segment, pattern))
+ );
+ if (allSegmentsApproved) {
+ logger.info({ cmd: trimmed }, 'Shell command auto-approved (bot allow-list)');
+ return { allowed: true, needsApproval: false };
+ }
+ }
+
// In ask-me mode: only auto-approve when EVERY segment is a safe read.
// Matching the full trimmed string would let `cat foo; rm -rf ~` slip
// through because `cat *` matches the entire concatenation.
@@ -655,13 +702,20 @@ export class PermissionManager {
private findScope(resolvedPath: string): FileScope | undefined {
const scopes = this.manifest.capabilities.filesystem.scopes;
+ // Most-specific scope wins: a deep grant (e.g. ~/.mercury/tam rwx) must
+ // not be shadowed by a broad read-only ancestor (e.g. ~/.mercury r).
+ let best: FileScope | undefined;
+ let bestLen = -1;
for (const scope of scopes) {
const scopeResolved = resolve(scope.path.replace(/^~/, homedir()));
if (resolvedPath === scopeResolved || resolvedPath.startsWith(scopeResolved + sep)) {
- return scope;
+ if (scopeResolved.length > bestLen) {
+ best = scope;
+ bestLen = scopeResolved.length;
+ }
}
}
- return undefined;
+ return best;
}
async requestScopeExternal(path: string, mode: 'read' | 'write'): Promise<{ allowed: boolean; reason?: string }> {