Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

dream(security): #3384 add PATH/search-path family to validateEnv() denylist (evaluated, ACCEPT-scoped) (#3385)

rUv1e7a33a768c2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 209700d639..2db381503d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -88,6 +88,26 @@ jobs:
# codex at all; this makes the linked package actually runnable.)
run: npm run build --workspace=@claude-flow/security
+ - name: Build local @claude-flow/cli-core and overlay onto the installed package
+ # dream-cycle 2026-09-21: unlike @claude-flow/security above,
+ # package-lock.json resolves @claude-flow/cli-core from the
+ # published npm registry tarball (not an npm workspace `link`),
+ # even though its version (3.7.0-alpha.5) matches the local
+ # v3/@claude-flow/cli-core source exactly. `node scripts/ci-test-ratchet.mjs`
+ # below runs vitest from repo root, so v3/@claude-flow/cli's tests
+ # resolve `@claude-flow/cli-core` by walking up to the root's
+ # node_modules — the stale published dist/, not local source edits.
+ # This surfaced when validate-input-env.test.ts's new assertions
+ # (PR #3385) passed locally but failed in CI against the untouched
+ # published denylist. Building the local source and overlaying its
+ # dist/ onto the installed package (same version, so this is not a
+ # version bump) makes CI test the actual PR diff instead of a
+ # stale registry snapshot, without touching package-lock.json.
+ run: |
+ npm run build --prefix v3/@claude-flow/cli-core
+ rm -rf node_modules/@claude-flow/cli-core/dist
+ cp -r v3/@claude-flow/cli-core/dist node_modules/@claude-flow/cli-core/dist
+
- name: Run all tests
# #3030: the historical suite has known debt, but new failing files
# are release-blocking. The committed file-level baseline may only
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.md
index 548bb16327..a10e3e94d6 100644
--- a/docs/dream-cycle/LEDGER.md
+++ b/docs/dream-cycle/LEDGER.md
@@ -192,3 +192,7 @@ as a first-class, high-priority candidate, not a background note.
| 2026-09-10 | performance | `mmrRerank()` eagerly re-tokenized every remaining candidate's content on every MMR outer-loop pass (O(N×limit) `tokenize()` calls) — a pattern that predates and survived PR #3169's embedding-cosine wiring unchanged, even though the cosine branch made that tokenization mostly discarded work in the now-common all-embedded case; made lazy and cached per-candidate | #3265 | #3266 | yes | ACCEPT | `tokenize()` calls 400→0 (N=30/limit=20 corpus, stash-isolated: fails against real baseline, passes against candidate); wall-clock 5.88x faster (0.6745ms→0.1148ms mean), independently reproduced at 5.96x by an adversarial critic; selection output byte-identical to baseline across all-embedded/none/mixed/lambda-extreme scenarios; 473/474 full-suite both ways (1 pre-existing unrelated failure), `tsc` clean | 78c074ef... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232 merges), awaiting fresh CI as of 2026-09-14 |
| 2026-09-11 | security | `hive-mind_consensus` accepted votes from any caller-supplied `voterId` with no check against `state.workers` (a single caller could cross any strategy's quorum by voting under fabricated identities — a Sybil attack on consensus); fail-closed roster-membership check added. **Update (ruvnet review):** REJECTed the initial scoped fix on the caveat the adversarial critic had already disclosed (`hive-mind_join`/`leave` fully unauthenticated — the roster itself could be Sybil'd) plus a required-CI cold-install failure (`@claude-flow/security` missing a `prepare` script, so root `npm ci` never built its dist/). Both addressed same-session: `join`/`leave`/`vote` now capability-bound to a `hiveToken` minted by `hive-mind_init` (32-byte random, constant-time comparison, fail-closed — zero state change for denied calls, verified via a fresh state.json reload simulating restart; a same-machine-only token reader lets the CLI's own subcommands keep working without exposing the token over any MCP response); `@claude-flow/security`'s `package.json` gained a `prepare: npm run build` so root `npm ci` builds it automatically for every consumer, not just this CI job | #3290 | #3291 | yes | ACCEPT-scoped (post-review) | stash-isolated 2/3 fail baseline (forged votes silently accepted) → 3/3 pass candidate; full `@claude-flow/cli` suite failures 46→28 after the CI fix (remainder pre-existing/unrelated); adversarial critic CONFIRMED-WITH-CAVEATS pre-review, both caveats closed post-review | 55d67b4a... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232/#3266 merges), awaiting fresh CI as of 2026-09-14 |
| 2026-09-12 | intelligence | `LocalReasoningBank.findSimilar()` overwrote every returned pattern's `confidence` (learned reliability) with the per-query cosine similarity score instead of the already-declared `PatternMatch.similarity` field, inverting `distillLearning()`'s "only distill from high-confidence matches" gate (it tested query-similarity, not reliability) and forcing `findSimilarPatterns()`'s public API into an unsafe cast that made `confidence`/`similarity` always identical; `findSimilar()` now preserves real `confidence` and returns `similarity` separately, with the one affected consumer (`memory-bridge.ts`'s search-ranking score) migrated accordingly | #3301 | #3302 | yes | ACCEPT | 4 new discriminating tests, baseline-fails/candidate-passes via stash isolation; full suite 90-vs-91-failed-files identical except the new test file; `tsc --noEmit` byte-identical (463 errors both ways); independent adversarial critique CONFIRMED, no blocking caveats | cb60b43b... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232/#3266/#3291 merges), awaiting fresh CI as of 2026-09-14 |
+
+**Note (2026-09-21):** #3302 confirmed **MERGED** 2026-09-15 via `pull_request_read` (authoritative) — `search_pull_requests`'s `merged` field is stale/unreliable (it reported `merged:false` with a populated `merged_at` for this same PR; do not trust it for merge-state checks, use `pull_request_read`/`get`). **New no-run gap, confirmed via `git ls-remote --heads origin "dream/*"`**: 2026-09-13 and 2026-09-14 have no branch, issue, or PR — same verification standard as the documented 08-20..08-23 gap, root cause still undiagnosed. 2026-09-15 through 2026-09-20 all ran (real branches confirmed): #3329/#3330 (perf, MoE load-balance), #3338/#3339 (security, hive-mind capability-token round 2), #3349/#3350 (intelligence, ModelRouter prior-decay env override), #3351/#3352 (memory, AgentDBAdapter upsert-orphan fix), #3356/#3357 (swarm, topology mirror-edge fix), #3377/#3378 (performance, UnifiedSwarmCoordinator busy-poll→event-driven, ~487x measured) — not transcribed row-by-row here per the established "ledger rows only reach `main` via PR merge" convention; all currently open/draft, none stale (<14d old as of tonight).
+
+| 2026-09-21 | security | `validateEnv()`'s loader-hijack denylist blocked LD_PRELOAD/NODE_OPTIONS-class vars but not PATH itself or the equivalent interpreter/VCS search-path family (CWE-427) — flagged grade-A by 09-20's security scan; added PATH/PYTHONPATH/PERL5LIB/RUBYLIB/GIT_EXTERNAL_DIFF/GIT_SSH_COMMAND/BASH_ENV/IFS to the denylist. Adversarial critique found the lookup was case-sensitive (`path`/`Path` bypassed it on case-insensitive Windows) — fixed same session via `.toUpperCase()` case-folding, also hardening the original 9 names | #3384 | #3385 | yes | ACCEPT-scoped | 13 new discriminating tests (32/32 total); baseline-fails/candidate-passes via stash isolation, independently reproduced twice by the critic; full suite failed-file set byte-identical (36 pre-existing environmental failures); `tsc --noEmit` 14 pre-existing errors, unchanged; independent adversarial critique CONFIRMED-WITH-CAVEATS → caveat closed same session | 03142288... | 09-15..09-20 (6 nights) all open/draft, none stale; 08-24..09-11 backlog (10 PRs) still unmerged since the 09-14/09-15 batch that cleared 09-03/09-05/09-07/09-12 |
diff --git a/docs/dream-cycle/dream-gist-2026-09-21.md b/docs/dream-cycle/dream-gist-2026-09-21.md
new file mode 100644
index 0000000000..8f31688d0d
--- /dev/null
+++ b/docs/dream-cycle/dream-gist-2026-09-21.md
@@ -0,0 +1,101 @@
+# Security SOTA Report — 2026-09-21
+
+TL;DR: `validateEnv()`'s loader-hijack denylist (`v3/@claude-flow/cli-core/src/mcp-tools/validate-input.ts`) blocked `LD_PRELOAD`/`NODE_OPTIONS`-class vars but not `PATH` itself or the equivalent interpreter/VCS search-path family — a CWE-427 gap flagged grade-A by last night's (2026-09-20) security scan. Added `PATH`, `PYTHONPATH`, `PERL5LIB`, `RUBYLIB`, `GIT_EXTERNAL_DIFF`, `GIT_SSH_COMMAND`, `BASH_ENV`, `IFS` to the denylist, closing the only currently MCP-reachable exposure (`terminal_create`/`terminal_execute`). An independent adversarial critic then found the lookup itself was case-sensitive (`path`/`Path` bypass it, harmless on POSIX but a real bypass on Windows) — fixed same session by case-folding the comparison, which incidentally also hardens the original 9 names.
+
+## What's New in 2026
+
+| Finding | Source | Grade |
+|---|---|---|
+| CVE-2026-2256 (ModelScope `ms-agent`): a shell-command **denylist** regex was bypassable → full RCE — direct evidence for denylist-fragility, same anti-pattern class | GHSA-4gc2-344q-r2rw, CERT/CC VU#431821 | A |
+| CVE-2026-21852 (Claude Code, patched v2.0.65, within 12mo): an untrusted repo's config could set an env-style setting (`ANTHROPIC_BASE_URL`) with no allow/deny gate to exfiltrate API keys — same-vintage precedent for under-gated env settings in an AI coding agent | GHSA-jh7p-qr78-84p7 | A |
+| CVE-2026-56074 (PraisonAI): `os.environ.copy()` full-inheritance into a subprocess + approval-cache bypass → ambient API-key exfiltration | GHSA-ffp3-3562-8cv3 | B |
+| OpenAI's hosted-sandbox docs explicitly reject caller-set `PATH`/`CODEX_*`/`OPENAI_API_KEY` as "runtime-reserved" names — direct vendor precedent for denylisting `PATH` by name | developers.openai.com (fetched) | A |
+| MCP reference SDK's client→server stdio spawn uses a real allowlist (`DEFAULT_INHERITED_ENV_VARS`) — but deliberately *keeps* `PATH` in it (excludes only secret-shaped vars); solves the mirror-image problem (protecting a server from a trusted client's secrets), not a tool's own shell-out | modelcontextprotocol.io SDK source (fetched) | A |
+| No MCP-specific advisory or scanner rule (checked mcp-scan-family write-ups) names subprocess env/PATH injection as a known MCP antipattern — a real tooling gap, not evidence the risk is unfounded | dev.to survey (2026) | C |
+
+## Ruflo Current Capability
+
+`terminal_create` validates caller `env` via `validateEnv()` and stores it as `session.env`; `terminal_execute` runs `execSync(command, { env: { ...process.env, ...session.env } })` — `session.env` is spread *after* `process.env`, so an un-denied key silently overrides the real value for every subsequent command in that persisted session (`.claude-flow/terminals/store.json`). The doc comment already named "command resolution" as in-scope for this denylist; `PATH` was simply never added. Full `v3/` sweep (deep-researcher) found exactly one other caller-controlled env merge with **no** validation at all — `rvfa-runner.ts`'s `spawnAsync` (CLI-only `.rvfa` appliance path, not MCP-reachable today) — deferred as a follow-up, out of scope tonight. `ruflo/src/ruvocal/mcp-bridge`'s full-env-inheritance credential leak (ADR-166 finding V4) is a different mechanism, already tracked separately.
+
+## Competitor Comparison
+
+| Framework/Project | Env-sanitization for shell/code-exec | Grade | Source |
+|---|---|---|---|
+| LangChain/LangGraph `ShellTool`/`ShellToolMiddleware` | None — docs state env is inherited from parent unless explicitly overridden | A | reference.langchain.com |
+| AutoGen `LocalCommandLineCodeExecutor` | None found in code despite a docstring claiming a sanitizer; filtering only via opt-in Docker/ACA executor | B | github.com/microsoft/autogen #8239 |
+| CrewAI `CodeInterpreterTool` | Docker-sandboxed by default (isolation, not filtering); E2B/sandbox tools use opt-in allowlist `envs` param | B | crewAI-tools source; docs.crewai.com |
+| OpenAI Agents SDK / Code Interpreter | Sandboxing (ephemeral VM/container), not env filtering — nothing shared to sanitize | A | developers.openai.com |
+| MCP reference SDK (stdio spawn) | Real allowlist, but solves the opposite direction (protect server from client secrets); explicitly keeps `PATH` | A | modelcontextprotocol.io |
+| Ruflo's own `SafeExecutor` (`@claude-flow/security`) | None — `env: config.env ?? process.env`, same unfiltered-inheritance pattern as the unmitigated competitors | A | safe-executor.ts:174 (direct read) |
+
+**Synthesis**: a two-tier industry pattern, not independent oversight. Tier 1 (LangChain, AutoGen's default path, ruflo's own `SafeExecutor`) inherits the full parent env unfiltered by default; Tier 2 (OpenAI, CrewAI's Docker-first path) sidesteps the problem via process/container isolation instead. Every framework surveyed *also* ships a zero-setup local/"unsafe" path where env filtering is essentially absent — a genuine, still-open gap. The MCP SDK's allowlist is the closest transferable precedent: it deliberately keeps `PATH`, because **blocking `PATH` outright is different from stripping it from the process**. Tonight's fix rejects a caller's attempt to *override* `PATH`/family via `terminal_create`'s `env` field; a caller who omits it still gets the real `process.env.PATH` unmodified.
+
+## Hypothesis
+
+> Given `validateEnv()`'s `DENYLISTED_ENV_NAMES` omitting `PATH` and the wider uncontrolled-search-path family, allowing a `terminal_create` caller to inject an overriding value for any of them into every subsequent `terminal_execute` call in that session, when these 8 names are added to the denylist, then `validateEnv()` should reject any caller-supplied env object containing one of them exactly as it already does for the existing 9 loader-hijack names, closing the CWE-427 gap at the only MCP-reachable call site, subject to: (1) no existing caller/test currently sets these names through `env` (regression safety); (2) the real process's own PATH continues to flow through unmodified for callers who don't override it; (3) all existing `@claude-flow/cli` tests remain green; (4) fully deterministic, $0 evaluation cost.
+
+Frozen before evaluation; not modified after seeing results.
+
+## Evaluation
+
+**evaluated: accepted.** Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls. Extended existing file `v3/@claude-flow/cli/__tests__/validate-input-env.test.ts` (+8 parametrized cases, reusing its established pattern).
+
+Baseline vs. candidate, isolated via `git stash` of just the source file: exactly the 8 new-name tests fail against baseline (8 failed/19 passed) and pass against candidate; re-verified independently by an adversarial critic (which itself reproduced the stash/rebuild/test cycle twice). After the critic's case-fold caveat was fixed, 5 more discriminating tests were added (`path`/`Path`/`PaTh`/`node_options`/`Node_Options`) and isolated the same way: fail without `.toUpperCase()`, pass with it. Final: **32/32 passing**. Full `@claude-flow/cli` suite run both ways: **failed-file set byte-identical** (36 files, pre-existing unbuilt-monorepo-sibling-package environmental failures — same class documented since #3221/#3243/#3302) — zero new failures introduced. `tsc --noEmit`: 14 pre-existing errors, none touching the changed files.
+
+## Reward Hack Check
+
+No standalone reward-hack CLI reachable this session (`npx ruvector harness --help`: status/route/flywheel/darwin only). Manual checklist, independently re-verified by the adversarial critic: no existing test weakened (diff is purely additive, 0 deletions); no gold/expected data touched (none exists on this path — repo-wide search found only unrelated plugin fixtures); no cherry-picking (denylist Set and test array independently confirmed 1:1, same order); no seed manipulation (deterministic Set-membership logic, no randomness); zero cost.
+
+## Security Review
+
+Not a new attack surface: pure input-validation narrowing on an already-validated API boundary (`terminal_create`'s `env` parameter), fail-closed (the whole call is rejected, not silently stripped). Mechanism independently verified: `terminal-tools.ts:198`'s `{ ...process.env, ...session.env }` merge means a denied/omitted key leaves the real process env untouched — this fix blocks *overriding* PATH/family, not the process's own PATH. Full `v3/` sweep found no other MCP-tool-registry call site with this exposure. One real caveat (case-sensitivity, detailed above) found and fixed same session; one informational note (ADR-165 had already documented `PYTHONPATH` as denylisted before this fix — a pre-existing doc/code drift this change incidentally closes, not something it caused).
+
+## Darwin Results
+
+Skipped — binary denylist-membership fix (a name is either blocked or not), not a continuous parameter with a fitness gradient for Darwin's real interface (`npx ruvector harness darwin --help`, `@metaharness/darwin` confirmed available) to search over. Same skip class as #3110/#3160/#3184/#3221/#3243/#3266/#3302/#3330/#3378.
+
+## Flywheel Evidence
+
+No `.claude-flow/flywheel/` state or signed `@metaharness/flywheel` bundle exists in this repo (confirmed via direct check + `npx ruvector harness flywheel --help`). Evidence retained as: the 8 new discriminating tests, this gist, the linked issue, the stash-isolated baseline/candidate comparison (independently reproduced by the adversarial critic), and the full research trail — consistent with every accepted night since 2026-08-18.
+
+## SOTA Proof & Witness
+
+| Field | Value |
+|---|---|
+| Session commit | `a4f219935ff4035421bc01157a5a1abc74529ad2` |
+| Gist SHA-256 (pre-witness content) | `b331b4d2d0efab6526d4f08d0b12a7bd797be999c3a17e70630738d484221fe6` |
+| Witness stamp | `031422884fc93022085007c7c075a9815ab590ada08aa319150ae091b8a802fb` |
+
+Verifier procedure: fetch this gist, strip the witness table's three filled values back to `PENDING`, SHA-256 it, concatenate with the session commit above, SHA-256 again — result must equal the witness stamp.
+
+## Scan Findings: intelligence
+
+**New, highest-priority carry-forward**: `ewc-consolidation.ts`'s `updateFisherFromConfidences()` (wired into the live SONA→`distillLearning()` path, `intelligence.ts:413`) runs its Fisher-matrix EMA **backwards** vs. the other two EMA sites in the same file: old Fisher gets weight `0.01`, the current batch gets `0.99` — every distill pass wipes ~99% of accumulated importance instead of slowly accumulating it, defeating EWC++'s anti-forgetting purpose. 1-line fix; existing tests miss it because they only call from a freshly-zeroed Fisher. Recommend as next `intelligence` DEEP night's lead candidate. Also flagged: MoE `computeLoadBalanceLoss()` mixes a cumulative fraction with a single-sample probability (observability-only, no consumer today); `ReasoningBank.retrieve()`'s MMR redundant `maxSimilarity` recompute (open since 2026-09-20, unfixed).
+
+## Scan Findings: swarm
+
+Two carried-over findings re-confirmed via fresh code read: `hive-mind_consensus` ignores `state.consensusStrategy` (still reads only the narrower per-call `strategy` param); `byzantine.ts`'s `requiredVotes=2f+1` (an absolute count) is never rescaled against the achievable weight sum post-clamp — concrete repro: n=4,f=1→requiredVotes=3, all 4 vote approve at weight 0.5→approvingWeight=2<3→**rejected despite unanimous approval**, while `approvalRate` self-reports 100%. **New**: `UnifiedSwarmCoordinator.recoverAgent()` self-stamps `lastHeartbeat=now` on every "recovery," the same antipattern already fixed once in `AgentPool` (#3242/#3243) but reappearing independently in the coordinator that actually drives task assignment — a dead agent cycles degrade→fake-recover→look-healthy→degrade forever with no cap, silently routing tasks to a corpse. Recommend a future `swarm`/`hive-mind` DEEP night fix all three together (all touch vote/health-state resolution).
+
+## Competitors Reviewed
+
+LangChain/LangGraph, AutoGen/Microsoft Agent Framework, CrewAI, OpenAI Agents SDK (mandated floor); MCP reference SDK + spec (more specific, directly relevant comparison); CWE-427/CERT/CC/GHSA advisories (CVE-2026-2256, CVE-2026-21852, CVE-2026-56074).
+
+## Additional candidates scored (STEP 3.2)
+
+`0.25·fit + 0.20·testability + 0.20·measurability + 0.15·production_value + 0.10·novelty + 0.10·reviewability`:
+
+1. **[4.60, selected] `validateEnv()` PATH-family denylist** (this candidate).
+2. **[4.30] EWC Fisher EMA inversion** (intelligence scan) — off-surface tonight (DEEP=security), deferred per rotation convention.
+3. **[4.25] `byzantine.ts` unreachable-accept threshold** (swarm scan) — deferred, off-surface.
+4. **[4.10] `recoverAgent()` heartbeat self-stamp** (swarm scan) — deferred, off-surface.
+5. **[3.15] `rvfa-runner.ts` unvalidated env merge** (security, same surface) — lower score: not MCP-reachable today, CLI-only local trust boundary.
+
+Highest score matched tonight's DEEP surface naturally; no override needed.
+
+## Recommended Next Steps
+
+1. Merge tonight's linked draft PR (human review required).
+2. **`intelligence` DEEP night: fix EWC Fisher EMA inversion** — 1-line, live on every distill cycle, plausibly higher-impact than tonight's fix.
+3. **`swarm`/`hive-mind` DEEP night: fix hive-mind consensus-strategy dispatch + byzantine weight-threshold rescaling + `recoverAgent` heartbeat self-stamp together** — all three touch vote/health-state resolution.
+4. Route `rvfa-runner.ts`'s env merge through the now-patched `validateEnv()` (lower urgency, CLI-only surface).
+5. Consider migrating `terminal-tools.ts` off raw `execSync` onto `@claude-flow/security`'s `SafeExecutor` (no-shell) as a deeper follow-up — noted by tonight's architecture review, not attempted tonight (larger, separate architectural question).
diff --git a/v3/@claude-flow/cli-core/src/mcp-tools/validate-input.ts b/v3/@claude-flow/cli-core/src/mcp-tools/validate-input.ts
index 82be281348..fba5e8e9ac 100644
--- a/v3/@claude-flow/cli-core/src/mcp-tools/validate-input.ts
+++ b/v3/@claude-flow/cli-core/src/mcp-tools/validate-input.ts
@@ -138,6 +138,14 @@ export function validateText(value: unknown, label: string, maxLen = 10_000): Va
* session. Setting LD_PRELOAD or NODE_OPTIONS via that path is functionally
* equivalent to remote code execution, so the env input needs an allowlist
* shape and a denylist on these specific names.
+ *
+ * dream-cycle 2026-09-21 (CWE-427, Uncontrolled Search Path Element): the
+ * original list covered loader/runtime hijack but not command-resolution
+ * hijack via PATH itself, or the equivalent interpreter/VCS search-path
+ * vars. This rejects a caller-supplied *override* of these names — the
+ * real process's own PATH etc. still flows through untouched for callers
+ * who don't set them (see terminal-tools.ts's `{ ...process.env,
+ * ...session.env }` merge order).
*/
const DENYLISTED_ENV_NAMES = new Set([
'LD_PRELOAD',
@@ -149,6 +157,14 @@ const DENYLISTED_ENV_NAMES = new Set([
'DYLD_FORCE_FLAT_NAMESPACE',
'NODE_OPTIONS',
'NODE_PATH',
+ 'PATH',
+ 'PYTHONPATH',
+ 'PERL5LIB',
+ 'RUBYLIB',
+ 'GIT_EXTERNAL_DIFF',
+ 'GIT_SSH_COMMAND',
+ 'BASH_ENV',
+ 'IFS',
]);
const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
@@ -176,7 +192,13 @@ export function validateEnv(value: unknown, label = 'env'): EnvValidationResult
if (!ENV_NAME_RE.test(name)) {
return { valid: false, sanitized: {}, error: `${label} key "${name}" is not a valid POSIX env name` };
}
- if (DENYLISTED_ENV_NAMES.has(name)) {
+ // Case-fold the lookup: Windows env vars are case-insensitive at the OS
+ // level, so `path`/`Path`/`PATH` are the same variable to a child
+ // process even though they're distinct object keys here. Every entry in
+ // DENYLISTED_ENV_NAMES is uppercase, so this also catches the existing
+ // loader-hijack names, not just the search-path family (adversarial
+ // critique, dream-cycle 2026-09-21).
+ if (DENYLISTED_ENV_NAMES.has(name.toUpperCase())) {
return { valid: false, sanitized: {}, error: `${label} key "${name}" is denylisted (loader/runtime hijack)` };
}
if (typeof rawVal !== 'string') {
diff --git a/v3/@claude-flow/cli/__tests__/terminal-execute-env-revalidation.test.ts b/v3/@claude-flow/cli/__tests__/terminal-execute-env-revalidation.test.ts
new file mode 100644
index 0000000000..06496f5abf
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/terminal-execute-env-revalidation.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Regression test for the post-review fix to PR #3385 (dream-cycle
+ * 2026-09-21): terminal_execute() used to trust session.env from the
+ * on-disk store unconditionally, so a session persisted before a
+ * validateEnv() denylist update (or a store.json edited/restored out of
+ * band) could carry a now-denylisted env var forever, bypassing the
+ * denylist for every execute on that pre-existing session. execute now
+ * re-validates session.env and drops it to {} if it fails current
+ * validation, rather than merging it unchecked.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { terminalTools } from '../src/mcp-tools/terminal-tools.js';
+
+const terminalExecuteTool = terminalTools.find(t => t.name === 'terminal_execute')!;
+
+function getStoreFile(workdir: string): string {
+ return join(workdir, '.claude-flow', 'terminals', 'store.json');
+}
+
+function plantSession(workdir: string, id: string, env: Record<string, string>) {
+ const dir = join(workdir, '.claude-flow', 'terminals');
+ mkdirSync(dir, { recursive: true });
+ const store = {
+ version: '3.0.0',
+ sessions: {
+ [id]: {
+ id,
+ name: 'planted-legacy-session',
+ status: 'active',
+ createdAt: new Date().toISOString(),
+ lastActivity: new Date().toISOString(),
+ workingDir: workdir,
+ history: [],
+ env,
+ },
+ },
+ };
+ // Plaintext: matches the legacy on-disk shape produced when
+ // CLAUDE_FLOW_ENCRYPT_AT_REST is unset (the default).
+ writeFileSync(getStoreFile(workdir), JSON.stringify(store, null, 2));
+}
+
+describe('terminal_execute re-validates persisted session.env (post-review fix)', () => {
+ let workdir: string;
+ let cwdSpy: ReturnType<typeof vi.spyOn> | null = null;
+
+ beforeEach(() => {
+ workdir = mkdtempSync(join(tmpdir(), 'term-env-revalidate-'));
+ cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(workdir);
+ });
+
+ afterEach(() => {
+ cwdSpy?.mockRestore();
+ rmSync(workdir, { recursive: true, force: true });
+ });
+
+ it('drops a persisted PATH override that would fail today\'s validateEnv(), instead of merging it unchecked', async () => {
+ const id = 'term-legacy-1';
+ // Simulates a session that was persisted before PATH was added to the
+ // denylist (or a hand-edited store.json) -- something that could not
+ // be created via terminal_create today, but already exists on disk.
+ plantSession(workdir, id, { PATH: '/tmp/definitely-not-the-real-path-injected' });
+
+ const result = await terminalExecuteTool.handler({
+ sessionId: id,
+ command: process.platform === 'win32' ? 'echo %PATH%' : 'echo "$PATH"',
+ } as Record<string, unknown>);
+
+ expect(result.success).toBe(true);
+ // The malicious override must not have reached the child process --
+ // real PATH entries (e.g. /usr/bin or /bin) must still be present,
+ // and the injected sentinel value must not appear standalone.
+ expect(result.output).not.toContain('/tmp/definitely-not-the-real-path-injected');
+ });
+
+ it('still merges a persisted env that passes current validation', async () => {
+ const id = 'term-legacy-2';
+ plantSession(workdir, id, { MY_CUSTOM_VAR: 'still-works' });
+
+ const result = await terminalExecuteTool.handler({
+ sessionId: id,
+ command: process.platform === 'win32' ? 'echo %MY_CUSTOM_VAR%' : 'echo "$MY_CUSTOM_VAR"',
+ } as Record<string, unknown>);
+
+ expect(result.success).toBe(true);
+ expect(result.output).toContain('still-works');
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/validate-input-env.test.ts b/v3/@claude-flow/cli/__tests__/validate-input-env.test.ts
index 0e097c0b4e..d2e2c71e28 100644
--- a/v3/@claude-flow/cli/__tests__/validate-input-env.test.ts
+++ b/v3/@claude-flow/cli/__tests__/validate-input-env.test.ts
@@ -41,6 +41,18 @@ describe('validateEnv (audit_1776853149979)', () => {
'DYLD_FORCE_FLAT_NAMESPACE',
'NODE_OPTIONS',
'NODE_PATH',
+ // dream-cycle 2026-09-21 (CWE-427, Uncontrolled Search Path Element):
+ // PATH itself and the equivalent interpreter/VCS search-path vars were
+ // missing — a caller could override PATH for every subsequent command
+ // in the terminal session.
+ 'PATH',
+ 'PYTHONPATH',
+ 'PERL5LIB',
+ 'RUBYLIB',
+ 'GIT_EXTERNAL_DIFF',
+ 'GIT_SSH_COMMAND',
+ 'BASH_ENV',
+ 'IFS',
];
for (const name of denylisted) {
@@ -52,6 +64,22 @@ describe('validateEnv (audit_1776853149979)', () => {
expect(r.sanitized).toEqual({});
});
}
+
+ // dream-cycle 2026-09-21 (adversarial critique caveat): Windows env vars
+ // are case-insensitive, so `path`/`Path` must be denylisted the same as
+ // `PATH` even though they're distinct object keys here.
+ describe('case-insensitive denylist match', () => {
+ const caseVariants = ['path', 'Path', 'PaTh', 'node_options', 'Node_Options'];
+
+ for (const name of caseVariants) {
+ it(`rejects ${name}`, () => {
+ const r = validateEnv({ [name]: '/tmp/whatever' });
+ expect(r.valid).toBe(false);
+ expect(r.error).toContain('denylisted');
+ expect(r.sanitized).toEqual({});
+ });
+ }
+ });
});
describe('shape validation', () => {
diff --git a/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts
index 04c882b42c..8c4f94dd3b 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts
@@ -188,6 +188,17 @@ export const terminalTools: MCPTool[] = [
let output: string;
let exitCode: number;
+ // dream-cycle 2026-09-21 (post-review): session.env was validated once
+ // at terminal_create time and trusted forever after via the on-disk
+ // store — a session persisted before a denylist update (or a store.json
+ // edited/restored out of band) could carry an env that the *current*
+ // validateEnv() would reject, silently bypassing the denylist for every
+ // execute on that pre-existing session. Re-validate at execution time
+ // too; drop (not fail the whole call) on now-invalid env so a stale
+ // session degrades to a clean environment rather than blocking.
+ const vSessionEnv = validateEnv(session.env, 'session.env');
+ const effectiveEnv = vSessionEnv.valid ? vSessionEnv.sanitized : {};
+
try {
output = execSync(command, {
cwd,
@@ -195,7 +206,7 @@ export const terminalTools: MCPTool[] = [
timeout,
maxBuffer: 5 * 1024 * 1024,
stdio: ['pipe', 'pipe', 'pipe'],
- env: { ...process.env, ...session.env },
+ env: { ...process.env, ...effectiveEnv },
});
exitCode = 0;
} catch (err: any) {