Skip to content

feat(config): single-command bash whitelist + env-var leak guard - #618

Merged
edenreich merged 32 commits into
mainfrom
feat/bash-whitelist-append-env-vars
Jun 8, 2026
Merged

edenreich merged 32 commits into
mainfrom
feat/bash-whitelist-append-env-vars

Conversation

@edenreich

@edenreich edenreich commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This branch began as a hardening of what the Bash tool auto-approves and grew into a broader pass over agent safety, headless secure-by-default behaviour, and a batch of chat-TUI / diff-viewer UX improvements. The sections below cover everything that ships in this PR.

Note: the bash auto-approval vocabulary was reworked within this branch from the old whitelist model into a per-mode allowed-list. The descriptions below reflect the final shipped state (tools.bash.mode.<mode>.allow, INFER_TOOLS_BASH_ALLOW_APPEND) — the earlier INFER_TOOLS_BASH_WHITELIST_COMMANDS* names no longer exist.


1. Bash auto-approval: per-mode allowed-list (default-deny)

Reworks bash auto-approval into a single, config-driven, per-mode allowed-list. A command auto-runs only if it matches the allowed-list for the active agent mode; anything unmatched is denied — an approval prompt in chat, a hard reject with an actionable hint in headless agent mode. There is no separate deny list.

  • Per-mode config — tools.bash.mode.{all,plan,standard,auto}.allow. mode.all is the every-mode baseline, unioned with the active mode's own list (bashAllowFor). mode.auto defaults to the .* sentinel (unrestricted); mode.plan / mode.standard add nothing and reduce to the read-only baseline.
  • Full-command matching — entries match \A(?:entry)\z, so a bare token like gh allows only gh (never gh issue list); entries opt into arguments explicitly (gh issue.*). The single .* sentinel means unrestricted and skips the clean-command guard.
  • Single matcher — IsBashCommandAllowed(command, mode) is shared by the Bash tool gate, the approval policy, and agent auto-approval. Mode flows in via domain.WithAgentMode context + AgentMode.AllowedlistKey().
  • Clean-command guard (every non-.* mode) rejects, before matching:
    • command substitution ($(…), backticks, <()/>()),
    • multi-command chains / pipelines (top-level |, &&, ||, ;, &, newline — operators inside quotes don't count, so jq '… | …' stays a single command). This closes the echo x | xargs rm prefix hole.
    • a surviving file-write redirect (>/>>; benign 2>&1 / >/dev/null are stripped first),
    • dangerous find actions (-exec/-delete/…),
    • the env-var leak guard: a printing/publishing command (echo/printf/gh issue|pr create|comment|edit) may not expand $VAR, so echo $AWS_SECRET_ACCESS_KEY is blocked while ls $DIR stays allowed (a single-quoted or escaped $ is literal).
  • Hardened defaults — the raw gh api GET wildcard is dropped; the baseline now enumerates explicit non-destructive gh subcommands (issue|pr|repo|release|run|workflow list|view|…, gh search, and read-only gh project list|view|item-list|field-list). gh project writes (item-add/item-edit), git push, and git commit are not in the defaults and fall through to approval. A raw-gh api need is opt-in per repo.
  • Append-only override — --tools-bash-allow-append / INFER_TOOLS_BASH_ALLOW_APPEND (comma/newline list, env wins over flag) merges onto mode.all.allow after config load, so CI can add a few safe commands (e.g. git commit / git push) without rewriting config or shipping .*.
  • Model feedback — each guard rejection returns an actionable hint (BashCommandRejectionHint), and the effective per-mode allow-list is injected into the system prompt (buildBashAllowInfo), rebuilt each turn so a chat mode toggle re-injects it. The model is told not to retry a denied command but to stop and ask, or use an allowed alternative.

2. Headless secure-by-default (approval_behaviour)

Headless infer agent previously defaulted to auto mode (.*), so CI, heartbeat, and any run without --require-approval could execute any command unattended. This makes the restricted path the default.

  • New tools.safety.approval_behaviour (prompt | ipc | block, default prompt) decides how a needed approval is delivered, alongside the existing require_approval which decides whether. config.ResolveApprovalDelivery(behaviour, brokerAttached, isChat) is the single resolver; Config.Validate rejects unknown values.
  • The headless executor now runs in standard mode and routes approval-requiring tools per behaviour: IPC when a broker is attached (--require-approval, e.g. the channel manager), otherwise blocked with a reason. No more .* default — full autonomy is now an explicit opt-in.
  • Chat honours block (rejects without prompting); prompt / ipc still prompt.
  • Auto-accept safety prompt — prompts.agent.system_prompt_auto carries a destructive-action policy (confirm/avoid irreversible ops: delete, force-push, drop, rm -rf, publish) for auto-accept mode, wired via getSystemPromptForMode; falls back to system_prompt when blank.
  • Controlled-autonomy CI profile: approval_behaviour: block + tools.write.require_approval: false + a curated bash allow-list / the append override.

3. BlockingTools agent state for undeliverable approval

A new StateBlockingTools handles the case where a tool needs approval but no approver is reachable (approval_behaviour=block, or =ipc with no broker).

  • Entered from EvaluatingTools when approval is required and undeliverable for all gated tools in the batch.
  • Walks the batch in order: non-gated tools (read-only, allow-listed Bash) still execute; gated tools are rejected with an actionable reason telling the model not to retry but to explain what it needs. Results are appended in conversation order, mirroring the ApprovingTools contract.
  • Emits a terminal tool-progress event so the live streaming overlay clears instead of lingering, then transitions to PostToolExecution.

4. Tool-execution stop routed through the event loop (fix)

The executeTools goroutine transitioned to StateStopped directly, but ExecutingTools → Stopped was never registered and the goroutine emitted no event, so processEvents never woke to observe the terminal state — the loop hung until session cancel (reachable via a rejected tool result or a successful RequestPlanApproval).

  • executeTools now only emits ToolsCompletedEvent{Stop}; the ExecutingTools state owns the transition (Stop → Stopped). Registers ExecutingTools → Stopped as the single needed from-state.
  • Completing now explicitly consumes CompletionRequestedEvent rather than finalizing on any event.
  • State journey is now debuggable: the transition chokepoint log is bumped to Info (file-only) and a Debug dispatching event line carries event + state + request_id.

5. Tool approval UX: diff preview

When approval is required for file-mutating tools (Edit / MultiEdit / Write), the approval box now renders a colored, syntax-aware diff preview (file path + old/new content, plus a "replace all occurrences" note for replace_all) instead of the compact one-liner. The preview is height-capped (≈ half the terminal, bounded 6–30 lines) with a dim "… N more lines (full diff shown after approval)" hint when truncated. All other tools keep the compact Name(arg=value, …) summary.

6. Agent skills enabled by default

AgentSkillsConfig.Enabled now defaults to true, so skills are discovered and injected into the system prompt out of the box. CLI help text, tests, and the seeded config.yaml are updated accordingly.


Chat-TUI / diff-viewer / git-staging UX

  • Patch line selection + hunk split — in the diff viewer you can select a line range within a hunk and stage/unstage only those lines (default: space/v to anchor a selection, navigate, apply with the stage/unstage keys), and split a multi-change hunk into independent blocks (s) so each can be staged separately. The hint text reflects whether a selection is active.
  • Stage all / unstage all — stage every change at once (default A → git add -A, incl. untracked & deletions) or unstage everything (default U → git reset -q HEAD), from anywhere in the panel.
  • Staged-file hint — the footer hides the discard option when a staged file is selected, since discard only applies to unstaged changes.
  • Removed file-type emoji icons from the diff renderer; file paths render plain.
  • Clipboard status flashes — copy/paste now show brief auto-dismissing status messages ("Copied to clipboard", "Text pasted from clipboard", "Image pasted from clipboard") that preserve any active loading spinner.
  • Image placeholder fix — attachments are labeled [Image 1] instead of [Image #1], so the # is no longer parsed as a Markdown heading.
  • Unified /model command — /model <name> permanently switches the active model (replaces /switch), while /model <name> <prompt…> runs a single message with that model and restores the session model afterward. /switch is deprecated.
  • Autocomplete no longer auto-executes — Tab always completes the suggestion (fills input + trailing space, never submits); Enter submits the current input. Prevents accidental command execution on selection.
  • Theme-aware editor background — the embedded vim/pty editor launches with set background=dark|light (and syntax enable) matched to the active TUI theme, so editor colors aren't washed out.
  • Bash streaming output coalescing — the Bash tool now buffers streamed output and flushes at most every ~50 ms or per ~64 KB, so high-volume commands (large git diff, logs) no longer flood the TUI with per-line update cycles. Captured output is unaffected.

Internal cleanup

  • Removed 21 never-used chat/agent event types and their orphaned publish sites (4 of which were broadcast to the Go→Swift bridge with no Go consumer and dropped as "ambiguous", which also removes per-transition log noise to the floating window). State-transition observability is retained via the adjacent logger.Debug. (internal-only refactor — no docs ticket.)
  • Lowercased remaining logging statements for consistency; check the scanner error after agent output; consistent named imports for third-party libraries.

Breaking changes / migration

  • tools.bash.whitelist.commands is removed. Configure tools.bash.mode.<mode>.allow instead. The INFER_TOOLS_BASH_WHITELIST_COMMANDS[_APPEND] env vars and --tools-bash-whitelist-commands* flags are gone; use INFER_TOOLS_BASH_ALLOW_APPEND / --tools-bash-allow-append (append onto the mode.all baseline).
  • Headless infer agent no longer auto-approves everything. It runs in standard mode; off-list / mutating actions are blocked in CI/heartbeat and sent for IPC approval under a channel manager. Restore full autonomy explicitly via a curated allow-list, the append override, or mode.auto/.*.
  • Compound/piped commands and echo $VAR no longer auto-approve — they now require approval. Re-add specific safe commands via the append override.
  • Agent skills are now on by default (agent.skills.enabled: true).

Verification

go test ./..., golangci-lint run, gofmt, and markdownlint all pass. Seeded config files were regenerated (go run . init --overwrite) with user-curated files (agents.yaml, etc.) restored.

Docs follow-up (inference-gateway/docs)

Filed: inference-gateway/docs#194 — covers the per-mode bash allowed-list (tools.bash.mode.<mode>.allow) + INFER_TOOLS_BASH_ALLOW_APPEND, tools.safety.approval_behaviour and the controlled-autonomy CI profile, agent skills now default-on, the unified /model command, and the new diff-viewer keybindings (patch line selection, hunk split, stage/unstage all). It also flags the stale "whitelist" wording still present in cli.md and github-action.md. Internal refactors (dead-event removal, stop-routing fix) need no docs ticket.

Add INFER_TOOLS_BASH_WHITELIST_COMMANDS_APPEND and
INFER_TOOLS_BASH_WHITELIST_PATTERNS_APPEND. Unlike the existing
INFER_TOOLS_BASH_WHITELIST_COMMANDS / _PATTERNS vars (which replace the
resolved list), the _APPEND siblings merge onto the fully-resolved
default/config/replace list, so callers can add per-repo entries
without clobbering the built-in default.

Applied after ReadInConfig so the merge sees the final base. The CLI
default stays the single source of truth for the whitelist; consumers
(infer-action, the org reusable workflow) are pass-throughs that only
forward these vars.

Also extract the shared comma/newline list parsing into
parseDelimitedList, removing the duplicated loop across the five INFER_*
list env vars and keeping initConfig under the gocyclo ceiling.
@edenreich
edenreich requested a review from a team as a code owner June 6, 2026 22:21
… dir

config.DefaultLogsPath is relative (".infer/logs"), so every test that
calls initConfig() (which calls logger.Init) created a real
cmd/.infer/logs/ directory in the working tree. Add a package TestMain
that points INFER_LOGGING_DIR at a throwaway temp dir for the run, so
the logger writes there instead. No test asserts on logging.dir, and
the tests that clear INFER_* env vars already chdir into their own
temp dir, so the override is safe and self-cleaning.
@edenreich
edenreich force-pushed the feat/bash-whitelist-append-env-vars branch from 9241cb5 to f382e4a Compare June 6, 2026 22:21
@edenreich edenreich changed the title feat(config): append env vars for bash whitelist feat(config): flags + append env vars for the bash whitelist Jun 6, 2026
Expose the four bash-whitelist env vars as persistent flags:
--tools-bash-whitelist-commands / --tools-bash-whitelist-patterns and
their -append siblings. For each list the replace source overrides the
resolved value and the append source merges onto it; the env var takes
precedence over the matching flag, consistent with the documented
flags < env layering.

Consolidate all whitelist resolution into applyBashWhitelistOverrides
(run after ReadInConfig so appends see config-file values), replacing
the inline env-only blocks in initConfig.
@edenreich
edenreich force-pushed the feat/bash-whitelist-append-env-vars branch from 392c5f1 to 629edf5 Compare June 6, 2026 22:29
edenreich added 2 commits June 7, 2026 01:30
Tighten what the Bash tool auto-approves so it cannot exfiltrate secrets or smuggle an arbitrary tail:

- Only a single command is auto-approved; any top-level operator (|, &&, ||, ;, &) falls through to approval (operators inside quotes still count as one command). Closes the "echo x | xargs rm" prefix hole.
- $VAR may be used in commands, but expanding one in a command that prints (echo/printf) or publishes (gh issue/pr create|comment|edit) is rejected, so the agent cannot echo or post an environment variable's value.
- git push is never auto-approved by the default list.
- Command substitution, file-write redirects and dangerous find actions stay blocked; each rejection now returns an actionable hint to the model.

Behavior change: commands that previously auto-approved (compound/piped commands, echo $VAR) now require approval. CI callers can re-add specific safe commands via INFER_TOOLS_BASH_WHITELIST_COMMANDS_APPEND.
@edenreich
edenreich force-pushed the feat/bash-whitelist-append-env-vars branch from 62a7a3d to b8a0fc4 Compare June 7, 2026 00:49
Comment thread cmd/root_test.go Resolved
Comment thread cmd/root_test.go Resolved
@edenreich edenreich changed the title feat(config): flags + append env vars for the bash whitelist feat(config): single-command bash whitelist + env-var leak guard Jun 7, 2026
Comment thread cmd/root_test.go Resolved
Comment thread cmd/root_test.go Resolved
Comment thread cmd/root_test.go Resolved
edenreich added 13 commits June 7, 2026 02:53
Co-authored-by: Eden Reich <[email protected]>
Rework PR #618's bash auto-approval into a single config-driven, per-mode
allowed-list. A bash command auto-runs only if it matches the allowed-list
for the active agent mode; anything unmatched is denied - an approval
prompt in chat, a hard reject with an actionable hint in headless agent
mode. There is no separate deny list.

- Config: tools.bash.mode.{all,plan,standard,auto}.allow. mode.all is the
  every-mode baseline, unioned with the active mode's own list
  (bashAllowFor). mode.auto defaults to ".*" (unrestricted) so headless
  `infer agent` commits and pushes without approval; mode.plan is empty.
- Matching is full-command (\A(?:entry)\z): a bare token matches only
  itself, entries opt into arguments via ( .*)?. The ".*" sentinel means
  unrestricted and skips the clean-command guard.
- Clean-command guard (every non-".*" mode) rejects command substitution,
  multi-command chains/pipelines, surviving file-write redirects, dangerous
  find actions, and env-var leaks (echo/printf/gh publish expanding $VAR).
- One matcher, IsBashCommandAllowed(command, mode), is shared by the Bash
  tool gate, the approval policy, and agent auto-approval. Mode flows via
  domain.WithAgentMode context + AgentMode.AllowedlistKey().
- The per-mode allowed-list is injected into the system prompt and rebuilt
  each turn so a chat mode toggle re-injects it.

Renames the bash auto-approval vocabulary from "whitelist" to "allowed"
across identifiers, messages, comments, and docs.

tools.bash.whitelist.commands is removed; configure
tools.bash.mode.<mode>.allow instead. The bespoke
INFER_TOOLS_BASH_WHITELIST_COMMANDS[_APPEND] env vars and
--tools-bash-whitelist-commands* flags are removed - the allowed-list is
config-file driven only.
- drop the raw `gh api` GET wildcard from defaults; the baseline now
  enumerates explicit non-destructive gh subcommands (incl. gh project
  reads), with gh api opt-in per repo.
- move read-only `gh project (list|view|item-list|field-list)` into the
  mode.all baseline; gh project writes (item-add/item-edit) are no longer
  auto-approved and fall through to approval.
- stop hardcoding the gh api regex in tests; allow-patterns come from
  DefaultConfig only.
- add `prompts.agent.system_prompt_auto`: a destructive-action policy for
  auto-accept mode (confirm/avoid irreversible ops), wired in
  getSystemPromptForMode.
- buildBashAllowInfo tells the model not to retry a denied command but to
  stop and ask the user or use an allowed alternative.
Headless `infer agent` previously defaulted to auto mode (`.*`), so CI,
heartbeat, and any run without --require-approval could execute ANY
command unattended. This makes the restricted path the default.

- add tools.safety.approval_behaviour (prompt|ipc|block, default prompt)
  deciding HOW a needed approval is delivered, alongside the existing
  require_approval which decides WHETHER. config.ResolveApprovalDelivery
  is the shared resolver; Config.Validate rejects unknown values.
- headless executor now runs in standard mode and routes approval-
  requiring tools per behaviour: IPC when a broker is attached
  (--require-approval, e.g. the channel manager), else blocked with a
  reason. No more `.*` default; full autonomy is now an explicit opt-in.
- chat honours block (rejects without prompting); prompt/ipc still prompt.
- docs, CLAUDE.md, and the seeded config document the field and the
  controlled-autonomy CI profile.
Delete 21 never-used event types and their fire-and-forget publish sites.
17 were defined but never constructed; 4 (ToolApprovedEvent, ToolRejectedEvent,
ToolApprovalClearedEvent, StateTransitionEvent) were broadcast to the Go->Swift
event bridge but had no Go consumer and were dropped by Swift's field-presence
dispatcher as "ambiguous", so removing them also stops per-transition log noise
to the floating window. State-transition observability is retained by the
adjacent logger.Debug call.

no docs ticket: internal-only refactor
The executeTools goroutine transitioned the state machine to StateStopped
directly, but ExecutingTools -> Stopped was never registered, so the
transition failed silently (the error was discarded). Even once registered it
was not enough: the goroutine emitted no event, and processEvents only checks
for a terminal state after handling an event, so it never woke to observe
Stopped and the loop hung until session cancel. Reachable in practice via a
rejected tool result or a successful RequestPlanApproval.

Route the stop through the loop like the success path: executeTools only emits
ToolsCompletedEvent{Stop}; the ExecutingTools state owns the transition (Stop
-> Stopped and emit nothing, so the loop exits on the terminal check;
otherwise -> PostToolExecution). Register ExecutingTools -> Stopped as the
single needed from-state (no global loop).

Also make the state journey debuggable: bump the transition chokepoint log
from Debug to Info (file-only by default, no TUI noise) and add a Debug
'dispatching event' line carrying event + state + request_id. And make
Completing explicitly consume CompletionRequestedEvent instead of finalizing
on any event.

no docs ticket: internal-only refactor
@edenreich
edenreich merged commit bea35ff into main Jun 8, 2026
@edenreich
edenreich deleted the feat/bash-whitelist-append-env-vars branch June 8, 2026 11:10
inference-gateway-releaser Bot pushed a commit that referenced this pull request Jun 8, 2026
## [0.121.0](v0.120.1...v0.121.0) (2026-06-08)

### 🚀 Features

* **config:** single-command bash whitelist + env-var leak guard ([#618](#618)) ([bea35ff](bea35ff))

### ♻️ Code Refactoring

* **logging:** turns all logging messages to start with lowercase ([fa73d31](fa73d31))

### 🧹 Maintenance

* **deps:** bump infer CLI v0.120.0 -> v0.120.1, infer-action v0.11.6 -> v0.11.7 ([#616](#616)) ([c9c6b1d](c9c6b1d))
* remove redundant comments ([e2303f2](e2303f2))
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.121.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Jun 8, 2026
claude Bot added a commit to inference-gateway/docs that referenced this pull request Jun 8, 2026
Update CLI docs for inference-gateway/cli#618:

- Replace the bash whitelist model with the per-mode allowed-list
  (tools.bash.mode.<mode>.allow): default-deny, full-command match,
  the .* sentinel, and the clean-command guard (command substitution,
  chains/pipelines, file-write redirects, find actions, env-var leaks).
- Harden the default gh allowed-list (read-only only; writes and raw
  gh api now require approval).
- Document tools.safety.approval_behaviour (prompt/ipc/block) and the
  whether-vs-how split with require_approval, headless secure-by-default,
  and the controlled-autonomy CI profile.
- Document INFER_TOOLS_BASH_ALLOW_APPEND / --tools-bash-allow-append and
  remove the old INFER_TOOLS_BASH_WHITELIST_COMMANDS* references.
- Reflect agent.skills.enabled default-on in cli.md and cli-skills.md.
- Add the unified /model command (/switch deprecated) and the new
  diff-viewer / git-staging keybindings.
- Rename remaining whitelist wording (incl. web_fetch allowed_domains)
  to the allowed-list model in cli.md and github-action.md.
edenreich pushed a commit to inference-gateway/docs that referenced this pull request Jun 8, 2026
Update CLI docs for inference-gateway/cli#618:

- Replace the bash whitelist model with the per-mode allowed-list
  (tools.bash.mode.<mode>.allow): default-deny, full-command match,
  the .* sentinel, and the clean-command guard (command substitution,
  chains/pipelines, file-write redirects, find actions, env-var leaks).
- Harden the default gh allowed-list (read-only only; writes and raw
  gh api now require approval).
- Document tools.safety.approval_behaviour (prompt/ipc/block) and the
  whether-vs-how split with require_approval, headless secure-by-default,
  and the controlled-autonomy CI profile.
- Document INFER_TOOLS_BASH_ALLOW_APPEND / --tools-bash-allow-append and
  remove the old INFER_TOOLS_BASH_WHITELIST_COMMANDS* references.
- Reflect agent.skills.enabled default-on in cli.md and cli-skills.md.
- Add the unified /model command (/switch deprecated) and the new
  diff-viewer / git-staging keybindings.
- Rename remaining whitelist wording (incl. web_fetch allowed_domains)
  to the allowed-list model in cli.md and github-action.md.

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant