Skip to content

fix(macos): align exec command parity - #50386

Merged
ngutman merged 2 commits into
mainfrom
fix/macos-exec-parity
Mar 19, 2026
Merged

ngutman merged 2 commits into
mainfrom
fix/macos-exec-parity

Conversation

@ngutman

@ngutman ngutman commented Mar 19, 2026

Copy link
Copy Markdown
Member

Summary

Describe the problem and fix in 2–5 bullets:

  • Problem: apps/macos drifted from the shared exec-command contract and wrapper-resolution behavior, so the macOS Swift suite failed on main.
  • Why it matters: the macOS app uses these paths for command validation, allowlist matching, and local CLI resolution; contract drift here weakens confidence in exec safety checks.
  • What changed: aligned the Swift env-wrapper and system-run validation behavior with the shared TypeScript contract, updated the stale Node-version expectation in CommandResolverTests, and replaced a flaky timestamp assertion with a stable file-identity assertion.
  • What did NOT change (scope boundary): no product UI changes, no new runtime features, and no changes to the TypeScript contract fixtures themselves.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #
  • Related #

User-visible / Behavior Changes

None.

Security Impact (required)

  • New permissions/capabilities? (Yes/No) No
  • Secrets/tokens handling changed? (Yes/No) No
  • New/changed network calls? (Yes/No) No
  • Command/tool execution surface changed? (Yes/No) Yes
  • Data access scope changed? (Yes/No) No
  • If any Yes, explain risk + mitigation:
    This changes how the macOS app classifies env wrappers and raw-command/display-command binding for exec approval paths. Risk is misclassifying wrappers or loosening validation. Mitigation: behavior was aligned to the existing shared TypeScript fixtures, and both the full macOS Swift suite and the shared TypeScript contract/parity tests pass after the change.

Repro + Verification

Environment

  • OS: macOS host
  • Runtime/container: Swift 6.2 package tests, Vitest via pnpm
  • Model/provider: N/A
  • Integration/channel (if any): N/A
  • Relevant config (redacted): none

Steps

  1. Run swift test in apps/macos on main before the fix.
  2. Observe failures in CommandResolverTests, ExecAllowlistTests, ExecSystemRunCommandValidatorTests, and a flaky ExecApprovalsStoreRefactorTests assertion.
  3. Apply the Swift parity fixes and rerun swift test in apps/macos.
  4. Run pnpm test -- src/infra/system-run-command.contract.test.ts src/infra/exec-approvals-parity.test.ts.

Expected

  • macOS Swift behavior matches the shared exec contract.
  • apps/macos test suite passes cleanly.
  • Shared TypeScript contract/parity tests remain green.

Actual

  • swift test in apps/macos passed: 420 tests in 106 suites.
  • The targeted TypeScript parity checks passed: 29 tests across 2 files.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios: full apps/macos swift test; shared TypeScript contract/parity tests for system-run and exec-approvals.
  • Edge cases checked: env with modifiers, shell-wrapper raw-command binding, Node minimum-version fallback path, and rewrite-vs-no-rewrite file-store behavior.
  • What you did not verify: manual interactive macOS app exec-approval UI flows.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? (Yes/No) Yes
  • Config/env changes? (Yes/No) No
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps:

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: revert commit 1ae64b67b2
  • Files/config to restore: the five changed macOS Swift/test files in this PR
  • Known bad symptoms reviewers should watch for: macOS exec approval requests showing mismatched command text, allowlist resolution unexpectedly treating env modifier chains as direct executables, or apps/macos test regressions in the exec-related suites.

Risks and Mitigations

List only real risks for this PR. Add/remove entries as needed. If none, write None.

  • Risk: Swift-side wrapper handling could diverge again from the shared contract.
    • Mitigation: this PR aligns behavior to the shared fixture-backed TypeScript tests and keeps the macOS suite green.
  • Risk: the no-rewrite assertion could stay flaky if it depended on filesystem timestamps.
    • Mitigation: the test now checks stable file identity instead of timestamp equality.

@aisle-research-bot

aisle-research-bot Bot commented Mar 19, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 1 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium PATH-based allowlist broadening via busybox/toybox shell applet unwrapping

1. 🟡 PATH-based allowlist broadening via busybox/toybox shell applet unwrapping

Property Value
Severity Medium
CWE CWE-426
Location apps/macos/Sources/OpenClaw/ExecCommandResolution.swift:148-227

Description

ExecCommandResolution.resolveAllowAlwaysPatterns() introduces unwrapShellMultiplexerInvocation() to treat busybox/toybox as wrappers and then drops the wrapper binary (argv[0]) and recurses on the applet token (e.g., sh).

This can cause persisted allowlist entries (created when a user selects Allow Always) to be generated for an executable resolved via PATH (e.g., /bin/sh or even a user-writable sh earlier in PATH), rather than for the actual invoked wrapper binary (busybox/toybox).

Impact:

  • Unexpected allowlist entry generation: approving busybox sh ... can persist an allowlist pattern for whatever sh resolves to in the host environment, not the busybox binary.
  • Potential authorization broadening: if a user approves an invocation like busybox sh script.sh (non--c form), the persisted allowlist may become /bin/sh, allowing future direct sh <script> executions (scripts are not parsed for subcommands) even though the original approved command executed busybox.
  • PATH confusion: because resolveExecutable() resolves bare names using env["PATH"], the chosen sh path can vary across environments or be influenced by a risky PATH ordering on the host.

Vulnerable code (key behavior):

if let shellMultiplexer = self.unwrapShellMultiplexerInvocation(command) {
    self.collectAllowAlwaysPatterns(command: shellMultiplexer, ...)
}
...
return Array(argv[appletIndex...]) // starts with applet like "sh", dropping busybox/toybox

Recommendation

Avoid generating allowlist patterns based on a PATH-resolved applet name when the actual invoked binary is busybox/toybox.

Safer options:

  1. Persist the wrapper’s resolved path (and do not drop it) when building allow-always patterns.
  2. If the intent is to allowlist the payload executed through busybox sh -c, add a dedicated parser for busybox/toybox shell applets that extracts the -c payload without resolving sh via PATH.
  3. If you must resolve an applet name, resolve it only via a trusted, fixed search path (e.g., CommandResolver.preferredPaths() restricted to system directories) and/or require it to resolve under an allowlisted set of directories.

Example mitigation sketch (preserve wrapper path for persistence):

​// Instead of returning ["sh", ...], keep the wrapper identity
​// and treat it as the allowlist target.
private static func unwrapShellMultiplexerInvocation(_ argv: [String]) -> (wrapperArgv: [String], applet: String)? {
    ...
    return (wrapperArgv: argv, applet: normalizedApplet)
}

​// In collectAllowAlwaysPatterns, when busybox/toybox is detected:
​// - add allowlist pattern for resolved busybox/toybox path
​// - optionally parse the applet-specific flags/payload to add additional patterns

Analyzed PR: #50386 at commit 5385e53

Last updated on: 2026-03-19T12:19:55Z

@openclaw-barnacle openclaw-barnacle Bot added app: macos App: macos size: S maintainer Maintainer-authored PR labels Mar 19, 2026
@greptile-apps

greptile-apps Bot commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR aligns the macOS Swift exec-command suite with the shared TypeScript contract by separating two previously conflated concerns: allowlist evaluation (which executable to match against in the allowlist, now preserving env wrappers with modifiers) and allow-always pattern recording (which executable to store after approval, now unwrapping through env modifiers to the effective inner binary). It also fixes a pre-existing bug where ExecEnvInvocationUnwrapper.unwrap returned a result for commands ending mid-option, hardens displayCommand to always use the full argv format, and replaces a flaky timestamp-based test assertion with a deterministic inode identity check.

Key changes:

  • ExecEnvInvocationUnwrapper gains unwrapWithMetadata/UnwrapResult to surface usesModifiers, and unwrapDispatchWrappersForResolution now stops at env wrappers that carry modifiers.
  • ExecSystemRunCommandValidator.resolve() now always returns formattedArgv as displayCommand and introduces a separate evaluationRawCommand (nil for shell wrappers when rawCommand is the full argv, not the shell payload).
  • ExecCommandResolution.resolveAllowAlwaysPatterns() drives the new allow-always pattern collection path, which correctly peels through env modifiers using collectAllowAlwaysPatterns, while resolveForAllowlist preserves env as the top-level executable.
  • Both ExecApprovalsSocket and MacNodeRuntime simplify their allowlist-persist loops to iterate the pre-computed allowAlwaysPatterns directly.
  • Two style-level observations worth tracking: (1) the depth < 3 guard in collectAllowAlwaysPatterns silently truncates patterns for deeply nested busybox+shell chains; (2) ExecEnvInvocationUnwrapper.unwrapWithMetadata detects inline-value env options via hardcoded strings while ExecSystemRunCommandValidator.unwrapEnvInvocationWithMetadata uses ExecEnvOptions.inlineValuePrefixes, leaving a maintenance gap if new options are added to the enum but not the hardcoded list.

Confidence Score: 4/5

  • Safe to merge — changes are well-targeted, backed by contract fixtures and a full Swift test suite, and the behavioral delta is intentional and documented.
  • The logic is complex (two interacting unwrap paths, a new recursive pattern-collection function, and a subtle split between displayCommand and evaluationRawCommand), but every changed code path has a corresponding new or updated test, the contract fixture suite is unchanged, and the PR description accurately matches the implementation. The two style observations (silent depth truncation and divergent option-set maintenance) are genuine but neither is a correctness bug for the current option set.
  • apps/macos/Sources/OpenClaw/ExecEnvInvocationUnwrapper.swift — the hardcoded inline-value prefix list should be kept in sync with ExecEnvOptions.inlineValuePrefixes. apps/macos/Sources/OpenClaw/ExecCommandResolution.swift — the depth-3 guard in collectAllowAlwaysPatterns silently drops patterns; worth a comment or trace log.

Comments Outside Diff (1)

  1. apps/macos/Sources/OpenClaw/ExecEnvInvocationUnwrapper.swift, line 70-84 (link)

    P2 Divergent option sets between parallel env-unwrap implementations

    ExecEnvInvocationUnwrapper.unwrapWithMetadata detects inline-value prefixes via hardcoded strings (-u, -c, -s, --unset=, --chdir=, etc.), while ExecSystemRunCommandValidator.unwrapEnvInvocationWithMetadata (used in the same exec pipeline) delegates to ExecEnvOptions.inlineValuePrefixes.

    If a new env option is added to ExecEnvOptions.inlineValuePrefixes but not to the hardcoded list here, collectAllowAlwaysPatterns would fail to recognise it as a modifier, potentially unwrapping through the modified env invocation and recording the wrong inner executable as the allow-always pattern. This divergence was pre-existing, but this PR adds a new hot code path (resolveAllowAlwaysPatterns) that relies on ExecEnvInvocationUnwrapper.unwrap() for modifier detection, making the risk more concrete.

    Consider having ExecEnvInvocationUnwrapper delegate to ExecEnvOptions.inlineValuePrefixes for these checks, or at minimum adding a shared constant/test that asserts both implementations recognise the same option set.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: apps/macos/Sources/OpenClaw/ExecEnvInvocationUnwrapper.swift
    Line: 70-84
    
    Comment:
    **Divergent option sets between parallel env-unwrap implementations**
    
    `ExecEnvInvocationUnwrapper.unwrapWithMetadata` detects inline-value prefixes via hardcoded strings (`-u`, `-c`, `-s`, `--unset=`, `--chdir=`, etc.), while `ExecSystemRunCommandValidator.unwrapEnvInvocationWithMetadata` (used in the same exec pipeline) delegates to `ExecEnvOptions.inlineValuePrefixes`.
    
    If a new env option is added to `ExecEnvOptions.inlineValuePrefixes` but not to the hardcoded list here, `collectAllowAlwaysPatterns` would fail to recognise it as a modifier, potentially unwrapping through the modified `env` invocation and recording the wrong inner executable as the allow-always pattern. This divergence was pre-existing, but this PR adds a new hot code path (`resolveAllowAlwaysPatterns`) that relies on `ExecEnvInvocationUnwrapper.unwrap()` for modifier detection, making the risk more concrete.
    
    Consider having `ExecEnvInvocationUnwrapper` delegate to `ExecEnvOptions.inlineValuePrefixes` for these checks, or at minimum adding a shared constant/test that asserts both implementations recognise the same option set.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: apps/macos/Sources/OpenClaw/ExecCommandResolution.swift
Line: 129-131

Comment:
**Silent pattern truncation at depth limit**

When `depth == 3`, `collectAllowAlwaysPatterns` returns without collecting any pattern and without any indication to the caller. A realistic chain that hits this limit: `busybox ash -c "busybox sh -c 'something'"` — busybox unwrap (0→1), shell detection + segment split (1→2), inner busybox unwrap (2→3), inner shell segment (blocked at 3).

The limit is a sound DoS guard, but silently dropping patterns means the allow-always store may be incomplete for deeply nested commands that are genuinely approved. Consider at minimum logging a debug trace when the guard fires so test failures or production mismatches are diagnosable. A `// depth guard: deliberate DoS protection` comment would also help future readers understand this isn't accidental.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: apps/macos/Sources/OpenClaw/ExecEnvInvocationUnwrapper.swift
Line: 70-84

Comment:
**Divergent option sets between parallel env-unwrap implementations**

`ExecEnvInvocationUnwrapper.unwrapWithMetadata` detects inline-value prefixes via hardcoded strings (`-u`, `-c`, `-s`, `--unset=`, `--chdir=`, etc.), while `ExecSystemRunCommandValidator.unwrapEnvInvocationWithMetadata` (used in the same exec pipeline) delegates to `ExecEnvOptions.inlineValuePrefixes`.

If a new env option is added to `ExecEnvOptions.inlineValuePrefixes` but not to the hardcoded list here, `collectAllowAlwaysPatterns` would fail to recognise it as a modifier, potentially unwrapping through the modified `env` invocation and recording the wrong inner executable as the allow-always pattern. This divergence was pre-existing, but this PR adds a new hot code path (`resolveAllowAlwaysPatterns`) that relies on `ExecEnvInvocationUnwrapper.unwrap()` for modifier detection, making the risk more concrete.

Consider having `ExecEnvInvocationUnwrapper` delegate to `ExecEnvOptions.inlineValuePrefixes` for these checks, or at minimum adding a shared constant/test that asserts both implementations recognise the same option set.

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: "fix(macos): address ..."

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1ae64b67b2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ngutman

ngutman commented Mar 19, 2026 •

Copy link
Copy Markdown
Member Author

@chatgpt-codex-connector @greptile-apps pushed follow-up fixes in 5385e533aa for the review comments above.

Verification rerun on the updated branch:

  • swift test in apps/macos: 423 tests passed
  • shared exec parity/allow-always tests: 95 tests passed

Please take another look at the latest commit when available.

Comment on lines +129 to +131
guard depth < 3, !command.isEmpty else {
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Silent pattern truncation at depth limit

When depth == 3, collectAllowAlwaysPatterns returns without collecting any pattern and without any indication to the caller. A realistic chain that hits this limit: busybox ash -c "busybox sh -c 'something'" — busybox unwrap (0→1), shell detection + segment split (1→2), inner busybox unwrap (2→3), inner shell segment (blocked at 3).

The limit is a sound DoS guard, but silently dropping patterns means the allow-always store may be incomplete for deeply nested commands that are genuinely approved. Consider at minimum logging a debug trace when the guard fires so test failures or production mismatches are diagnosable. A // depth guard: deliberate DoS protection comment would also help future readers understand this isn't accidental.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/macos/Sources/OpenClaw/ExecCommandResolution.swift
Line: 129-131

Comment:
**Silent pattern truncation at depth limit**

When `depth == 3`, `collectAllowAlwaysPatterns` returns without collecting any pattern and without any indication to the caller. A realistic chain that hits this limit: `busybox ash -c "busybox sh -c 'something'"` — busybox unwrap (0→1), shell detection + segment split (1→2), inner busybox unwrap (2→3), inner shell segment (blocked at 3).

The limit is a sound DoS guard, but silently dropping patterns means the allow-always store may be incomplete for deeply nested commands that are genuinely approved. Consider at minimum logging a debug trace when the guard fires so test failures or production mismatches are diagnosable. A `// depth guard: deliberate DoS protection` comment would also help future readers understand this isn't accidental.

How can I resolve this? If you propose a fix, please make it concise.

@ngutman
ngutman merged commit c4a4050 into main Mar 19, 2026
32 of 33 checks passed
@ngutman
ngutman deleted the fix/macos-exec-parity branch March 19, 2026 11:51

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5385e533aa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +133 to +137
if let token0 = command.first?.trimmingCharacters(in: .whitespacesAndNewlines),
ExecCommandToken.basenameLower(token0) == "env",
let envUnwrapped = ExecEnvInvocationUnwrapper.unwrap(command),
!envUnwrapped.isEmpty
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Persist the same pattern that allowlist matching resolves

resolveAllowAlwaysPatterns now unwraps env modifiers to the inner executable, but resolveForAllowlist still resolves the same argv to /usr/bin/env (see the new expectations in ExecAllowlistTests). After a user approves allow-always for /usr/bin/env FOO=bar /usr/bin/printf ok, this code stores /usr/bin/printf, and the next identical request still misses ExecAllowlistMatcher.matchAll because its resolution remains /usr/bin/env. That makes allow-always ineffective for env-modified commands, including shell payloads like sh -lc 'env FOO=bar ...'.

Useful? React with 👍 / 👎.

Comment on lines +129 to +130
guard depth < 3, !command.isEmpty else {
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reuse the shared wrapper-depth limit for allow-always parsing

collectAllowAlwaysPatterns stops recursing once depth == 3, but the rest of the exec pipeline accepts up to ExecEnvInvocationUnwrapper.maxWrapperDepth (4). Commands with an extra supported wrapper layer—e.g. nested env invocations before sh -lc ...—can still be approved and run once, yet allow-always records no pattern because this helper bails out before reaching the leaf executable. Users will keep getting prompted for the same command.

Useful? React with 👍 / 👎.

@ngutman ngutman mentioned this pull request Mar 19, 2026
6 of 20 tasks
veryoung pushed a commit to veryoung/openclaw that referenced this pull request Mar 20, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
yinuotxie pushed a commit to yinuotxie/openclaw that referenced this pull request Mar 20, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
fuller-stack-dev pushed a commit to fuller-stack-dev/openclaw that referenced this pull request Mar 20, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
fuller-stack-dev pushed a commit to fuller-stack-dev/openclaw that referenced this pull request Mar 20, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
frankekn pushed a commit to artwalker/openclaw that referenced this pull request Mar 23, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
Nachx639 pushed a commit to Nachx639/clawdbot that referenced this pull request Jun 17, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
lhfer pushed a commit to lhfer/openclaw that referenced this pull request Oct 11, 2026
* fix(macos): align exec command parity

* fix(macos): address exec review follow-ups
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: macos App: macos maintainer Maintainer-authored PR size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant