Skip to content

fix(config): escape terminal controls in config path reports - #184685

Closed
Alix-007 wants to merge 1 commit into
openclaw:mainfrom
Alix-007:fix/alix-config-terminal-paths-20261026
Closed

Alix-007 wants to merge 1 commit into
openclaw:mainfrom
Alix-007:fix/alix-config-terminal-paths-20261026

Conversation

@Alix-007

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: config validation, dry-run, and config-path confirmation reports can execute terminal controls or show forged status rows when the config filename contains those bytes.

User Impact

User impact: these config reports show escaped paths rather than terminal actions or forged report rows. JSON path fields and the shell-oriented config file output retain their original values. No settings, schema, permissions, migration or upgrade action changes.

Why This Change Was Made

Reuse the existing terminal-text sanitizer at the display owner. The existing config-path formatter owns this conversion; direct CLI report consumers use it instead of formatting the same paths separately. No input rejection, global display policy or new helper/state is introduced.

Evidence

  • Scenario: Config validation, invalid-config admission, dry-run, and shared config confirmations render config filenames safely while preserving raw JSON paths, shell path output and config bytes.

  • Entry: normal built openclaw.mjs config validate, config get, config set --dry-run, config file and setup --baseline; disputed owner ran unmocked: src/config/logging.ts formatConfigFilePath, adopted by config CLI validation/admission/dry-run and exercised by setup, unmocked

  • Same command on base 1b6eb7b and head d6c0205: node proof-config.mjs "$CHECKOUT" "$PHASE"

    • Before (base): RED valid config path: controls=3, forgedRow=true, escapedNewline=false; dry-run config path: controls=3, forgedRow=true, escapedNewline=false; shared config confirmation: controls=3, forgedRow=true, escapedNewline=false; missing config path: controls=3, forgedRow=true, escapedNewline=false; invalid config path: controls=3, forgedRow=true, escapedNewline=true; invalid config admission path: controls=3, forgedRow=true, escapedNewline=true
    • After (head): GREEN valid config path: controls=0, forgedRow=false, escapedNewline=true; dry-run config path: controls=0, forgedRow=false, escapedNewline=true; shared config confirmation: controls=0, forgedRow=false, escapedNewline=true; missing config path: controls=0, forgedRow=false, escapedNewline=true; invalid config path: controls=0, forgedRow=false, escapedNewline=true; invalid config admission path: controls=0, forgedRow=false, escapedNewline=true
  • Readback (subprocess,disk): Capture real validation/dry-run/admission/confirmation rows; parse JSON raw path fields; compare raw config file command output; compare actual valid and invalid config file hashes; assert the missing file was not created; run the ordinary-path command control.

  • Proof harness: proof-common.mjs sha256=8a6d2e48b1b076878e98641b0791f7fb064f44bbff9522fe43d1d34c6ffb007f; proof-config.mjs sha256=61dab8fac902e899f38df95b0d426c51baecbf1f80b9890800e5e416921f7c74

  • Control: Authoritative captured control counts: base [3,3,3,3,3,3], head [0,0,0,0,0,0]. Unicode preserved. Ordinary-path positive controls pass. Config byte changes=0; the missing config file stays absent; both valid and invalid file hashes remain identical; shell raw-path and JSON controls pass. No syscall/write-operation counting is claimed.

  • Other callers checked: Existing config-path formatter, valid/missing/invalid validation reports, invalid-config admission, set/patch/unset dry-run, config/backup log formatting and setup formatter consumers inspected. Raw config file output is explicitly a shell contract and stays raw.

  • Tests: pnpm test src/cli/config-cli.test.ts --maxWorkers=1 => 65 passed; exit 0 (measured cost: 33.42s measured wall time including native wrapper/worker preparation. 65 CLI cases pass after the final admission-path, assertion and test-registration changes; the separate unchanged formatter file passes 4 cases in the original 134.78s combined wrapper run. The existing warning-output test and new validation-report cases use the existing output-test registration to avoid growing the over-cap main test file; original assertions remain. Baseline unit regressions ran before this mechanical relocation; final consumer tests run after it. The native wrapper compiles the selected owner graph; this preparation dominates the >30s run. No sleep, timeout increase, retry allowance, weaker assertion or test-only production seam added. CI seconds: NOT_RUN before PR creation.)

  • Not tested: Linux isolated local config reports only. No running Gateway or owner-file mismatch RPC, packaged install, native Windows/macOS or released-version upgrade claim. Existing ordinary backup-existence regression is retained; no real backup filename with controls is claimed. No config writer, validation/admission policy or migration behavior changes.

  • Product head: d6c0205dfe60bd7531538403b8a863335c003980; baseline: 1b6eb7bf2e7f7cb31ce9ee71c6f1d778f7ee6ce0. Node26.12.1/pnpm12.15.0, Linux, clean normal CLI builds on both revisions.

  • 8 files; production +11/−9 LOC; tests +113/−22 LOC. Existing owner and sanitizer reused; no new state or production test seam.

  • Focused types, typed lint, formatting and whitespace pass. Independent complete-patch P0–P3 source review uses the user-approved subagent fallback; no official autoreview-helper success is claimed.

  • Regression controls also fail on the original base for the raw-control/forged-row reason. Existing ordinary path, ownership/refusal and JSON contracts remain covered.

  • Existing-solutions/competition: the shared terminal-core sanitizer already solves the transformation. Maintainer-accepted fix(config): sanitize validation log output to prevent control character injection #39116 covered config IO validation logs; fix(storage): escape terminal controls in location reports #183359/fix(agents): escape terminal controls in creation summaries #183360 covered different report owners. fix(cli): diagnose unreadable configuration in validation and setup #166573 changes read-failure admission/wording and does not repair these report paths. No viable competing same-root fix or Alix/Leon production-file overlap found in all-state semantic/symbol/file scans.

  • Cleanup: only synthetic task-owned HOME/config/state/workspace/temp data used; no credentials, production service/channel, model API, deployment or restart. Generated individual fixture directories/receipts remain available for audit and may be removed after review.

  • Not tested: Linux isolated local config reports only. No running Gateway or owner-file mismatch RPC, packaged install, native Windows/macOS or released-version upgrade claim. Existing ordinary backup-existence regression is retained; no real backup filename with controls is claimed. No config writer, validation/admission policy or migration behavior changes. Required upstream CI is NOT_RUN before creation.

Actual baseline and exact-head CLI streams and independent readback

Streams are JSON-escaped so control bytes cannot execute. Generated private temporary roots are replaced with $FIXTURE. The historical collector field unexpectedConfigWrites records the successful config-byte equality check; it is not a count of write operations. The missing-file assertion checks final absence, not create syscalls.

{
  "phase": "red",
  "head": "1b6eb7bf2e7f7cb31ce9ee71c6f1d778f7ee6ce0",
  "at": "2026-10-26T13:07:41.436Z",
  "runs": [
    {
      "label": "validate-valid-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate"
      ],
      "code": 0,
      "signal": null,
      "stdout": "Config valid: $FIXTURE/config-café\u001b[31m\noperator-forged\tend\rrow\u0007.json\n",
      "stderr": "",
      "seconds": 5.173915538999999
    },
    {
      "label": "validate-valid-json",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate",
        "--json"
      ],
      "code": 0,
      "signal": null,
      "stdout": "{\"valid\":true,\"path\":\"$FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\",\"warnings\":[]}\n",
      "stderr": "",
      "seconds": 2.7073440119999996
    },
    {
      "label": "dry-run-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "set",
        "gateway.mode",
        "\"local\"",
        "--strict-json",
        "--dry-run"
      ],
      "code": 0,
      "signal": null,
      "stdout": "Dry run successful: 1 update(s) validated against $FIXTURE/config-café\u001b[31m\noperator-forged\tend\rrow\u0007.json.\n",
      "stderr": "",
      "seconds": 2.558673177999999
    },
    {
      "label": "dry-run-json",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "set",
        "gateway.mode",
        "\"local\"",
        "--strict-json",
        "--dry-run",
        "--json"
      ],
      "code": 0,
      "signal": null,
      "stdout": "{\n  \"ok\": true,\n  \"operations\": 1,\n  \"configPath\": \"$FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\",\n  \"inputModes\": [\n    \"json\"\n  ],\n  \"checks\": {\n    \"schema\": true,\n    \"resolvability\": true,\n    \"resolvabilityComplete\": true\n  },\n  \"refsChecked\": 0,\n  \"skippedExecRefs\": 0\n}\n",
      "stderr": "",
      "seconds": 2.7443084640000017
    },
    {
      "label": "raw-file-contract",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "file"
      ],
      "code": 0,
      "signal": null,
      "stdout": "$FIXTURE/config-café\u001b[31m\noperator-forged\tend\rrow\u0007.json\n",
      "stderr": "",
      "seconds": 1.443272293
    },
    {
      "label": "file-json-contract",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "file",
        "--json"
      ],
      "code": 0,
      "signal": null,
      "stdout": "{\n  \"path\": \"$FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\"\n}\n",
      "stderr": "",
      "seconds": 1.4788355330000014
    },
    {
      "label": "shared-config-confirmation",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "setup",
        "--baseline"
      ],
      "code": 0,
      "signal": null,
      "stdout": "Config OK: $FIXTURE/config-café\u001b[31m\noperator-forged\tend\rrow\u0007.json\nWorkspace OK: $FIXTURE/workspace\nSessions OK: $FIXTURE/state/agents/main/sessions\n\nSetup complete: config, workspace, and session directories are ready.\nNext guided path: openclaw onboard.\nNext targeted changes: openclaw configure for models, channels, Gateway, plugins, skills, and health checks.\nAdd a chat channel later: openclaw channels add.\n",
      "stderr": "",
      "seconds": 7.0979904839999985
    },
    {
      "label": "ordinary-control",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate"
      ],
      "code": 0,
      "signal": null,
      "stdout": "Config valid: $FIXTURE/openclaw.json\n",
      "stderr": "",
      "seconds": 3.7622045889999973
    },
    {
      "label": "validate-missing-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate"
      ],
      "code": 1,
      "signal": null,
      "stdout": "",
      "stderr": "Config file not found: $FIXTURE/missing-café\u001b[31m\noperator-forged\tend\rrow\u0007.json\nCreate one with openclaw onboard or run openclaw doctor --fix.\n",
      "seconds": 1.9384147620000003
    },
    {
      "label": "validate-invalid-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate"
      ],
      "code": 1,
      "signal": null,
      "stdout": "",
      "stderr": "Config needs correction: $FIXTURE/config-café\u001b[31m\noperator-forged\tend\rrow\u0007.json\n  - config-café\\noperator-forged\\tend\\rrow.json:1 — gateway.mode: Invalid input (allowed: \"local\", \"remote\"), got: \"not-a-mode\"\n\nRun `openclaw doctor --fix` to repair, or fix the keys above manually.\nRun openclaw config schema to inspect supported settings and values, then rerun openclaw config validate.\n",
      "seconds": 3.7166528240000005
    },
    {
      "label": "get-invalid-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "get",
        "gateway.mode"
      ],
      "code": 1,
      "signal": null,
      "stdout": "",
      "stderr": "OpenClaw config is invalid: $FIXTURE/config-café\u001b[31m\noperator-forged\tend\rrow\u0007.json\n- config-café\\noperator-forged\\tend\\rrow.json:1 — gateway.mode: Invalid input (allowed: \"local\", \"remote\"), got: \"not-a-mode\"\nRun `openclaw doctor --fix` to repair, then retry.\n",
      "seconds": 3.9865900699999983
    },
    {
      "label": "validate-invalid-json",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate",
        "--json"
      ],
      "code": 1,
      "signal": null,
      "stdout": "{\n  \"ok\": false,\n  \"error\": {\n    \"type\": \"cli_error\",\n    \"message\": \"OpenClaw config is invalid: $FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\"\n  },\n  \"repairHint\": \"Run `openclaw doctor --fix` to repair, then retry.\",\n  \"valid\": false,\n  \"path\": \"$FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\",\n  \"issues\": [\n    {\n      \"path\": \"gateway.mode\",\n      \"message\": \"Invalid input (allowed: \\\"local\\\", \\\"remote\\\")\",\n      \"allowedValues\": [\n        \"local\",\n        \"remote\"\n      ]\n    }\n  ]\n}\n",
      "stderr": "",
      "seconds": 3.632472041000001
    }
  ],
  "observations": [
    {
      "label": "valid config path",
      "controls": 3,
      "forgedLine": true,
      "escapedLine": false,
      "unicode": true
    },
    {
      "label": "dry-run config path",
      "controls": 3,
      "forgedLine": true,
      "escapedLine": false,
      "unicode": true
    },
    {
      "label": "shared config confirmation",
      "controls": 3,
      "forgedLine": true,
      "escapedLine": false,
      "unicode": true
    },
    {
      "label": "missing config path",
      "controls": 3,
      "forgedLine": true,
      "escapedLine": false,
      "unicode": true
    },
    {
      "label": "invalid config path",
      "controls": 3,
      "forgedLine": true,
      "escapedLine": true,
      "unicode": true
    },
    {
      "label": "invalid config admission path",
      "controls": 3,
      "forgedLine": true,
      "escapedLine": true,
      "unicode": true
    }
  ],
  "readback": {
    "configSha256Before": "0d15ed758d7ea1a89c48e0c95e4fa9ff5e668e138ae5b35e504902500bcbf04b",
    "configSha256After": "0d15ed758d7ea1a89c48e0c95e4fa9ff5e668e138ae5b35e504902500bcbf04b",
    "invalidSha256Before": "f434f03a33b8eebba75a72ff641267806aec3c6cf83fded216dd488453b36cf6",
    "invalidSha256After": "f434f03a33b8eebba75a72ff641267806aec3c6cf83fded216dd488453b36cf6",
    "unexpectedConfigWrites": 0,
    "missingFileCreates": 0,
    "jsonRawPathsPreserved": true,
    "shellRawFileContractPreserved": true,
    "ordinaryControlPass": true
  }
}
{
  "phase": "green",
  "head": "d6c0205dfe60bd7531538403b8a863335c003980",
  "at": "2026-10-26T13:28:09.498Z",
  "runs": [
    {
      "label": "validate-valid-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate"
      ],
      "code": 0,
      "signal": null,
      "stdout": "Config valid: $FIXTURE/config-café\\noperator-forged\\tend\\rrow.json\n",
      "stderr": "",
      "seconds": 2.5448491689999995
    },
    {
      "label": "validate-valid-json",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate",
        "--json"
      ],
      "code": 0,
      "signal": null,
      "stdout": "{\"valid\":true,\"path\":\"$FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\",\"warnings\":[]}\n",
      "stderr": "",
      "seconds": 2.433712214
    },
    {
      "label": "dry-run-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "set",
        "gateway.mode",
        "\"local\"",
        "--strict-json",
        "--dry-run"
      ],
      "code": 0,
      "signal": null,
      "stdout": "Dry run successful: 1 update(s) validated against $FIXTURE/config-café\\noperator-forged\\tend\\rrow.json.\n",
      "stderr": "",
      "seconds": 2.4946486009999997
    },
    {
      "label": "dry-run-json",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "set",
        "gateway.mode",
        "\"local\"",
        "--strict-json",
        "--dry-run",
        "--json"
      ],
      "code": 0,
      "signal": null,
      "stdout": "{\n  \"ok\": true,\n  \"operations\": 1,\n  \"configPath\": \"$FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\",\n  \"inputModes\": [\n    \"json\"\n  ],\n  \"checks\": {\n    \"schema\": true,\n    \"resolvability\": true,\n    \"resolvabilityComplete\": true\n  },\n  \"refsChecked\": 0,\n  \"skippedExecRefs\": 0\n}\n",
      "stderr": "",
      "seconds": 2.517111822000001
    },
    {
      "label": "raw-file-contract",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "file"
      ],
      "code": 0,
      "signal": null,
      "stdout": "$FIXTURE/config-café\u001b[31m\noperator-forged\tend\rrow\u0007.json\n",
      "stderr": "",
      "seconds": 1.4338743799999993
    },
    {
      "label": "file-json-contract",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "file",
        "--json"
      ],
      "code": 0,
      "signal": null,
      "stdout": "{\n  \"path\": \"$FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\"\n}\n",
      "stderr": "",
      "seconds": 1.3524563249999992
    },
    {
      "label": "shared-config-confirmation",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "setup",
        "--baseline"
      ],
      "code": 0,
      "signal": null,
      "stdout": "Config OK: $FIXTURE/config-café\\noperator-forged\\tend\\rrow.json\nWorkspace OK: $FIXTURE/workspace\nSessions OK: $FIXTURE/state/agents/main/sessions\n\nSetup complete: config, workspace, and session directories are ready.\nNext guided path: openclaw onboard.\nNext targeted changes: openclaw configure for models, channels, Gateway, plugins, skills, and health checks.\nAdd a chat channel later: openclaw channels add.\n",
      "stderr": "",
      "seconds": 5.370175889
    },
    {
      "label": "ordinary-control",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate"
      ],
      "code": 0,
      "signal": null,
      "stdout": "Config valid: $FIXTURE/openclaw.json\n",
      "stderr": "",
      "seconds": 3.5487223480000027
    },
    {
      "label": "validate-missing-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate"
      ],
      "code": 1,
      "signal": null,
      "stdout": "",
      "stderr": "Config file not found: $FIXTURE/missing-café\\noperator-forged\\tend\\rrow.json\nCreate one with openclaw onboard or run openclaw doctor --fix.\n",
      "seconds": 1.8684768019999973
    },
    {
      "label": "validate-invalid-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate"
      ],
      "code": 1,
      "signal": null,
      "stdout": "",
      "stderr": "Config needs correction: $FIXTURE/config-café\\noperator-forged\\tend\\rrow.json\n  - config-café\\noperator-forged\\tend\\rrow.json:1 — gateway.mode: Invalid input (allowed: \"local\", \"remote\"), got: \"not-a-mode\"\n\nRun `openclaw doctor --fix` to repair, or fix the keys above manually.\nRun openclaw config schema to inspect supported settings and values, then rerun openclaw config validate.\n",
      "seconds": 3.515998334
    },
    {
      "label": "get-invalid-human",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "get",
        "gateway.mode"
      ],
      "code": 1,
      "signal": null,
      "stdout": "",
      "stderr": "OpenClaw config is invalid: $FIXTURE/config-café\\noperator-forged\\tend\\rrow.json\n- config-café\\noperator-forged\\tend\\rrow.json:1 — gateway.mode: Invalid input (allowed: \"local\", \"remote\"), got: \"not-a-mode\"\nRun `openclaw doctor --fix` to repair, then retry.\n",
      "seconds": 3.344807140000001
    },
    {
      "label": "validate-invalid-json",
      "args": [
        "$CHECKOUT/openclaw.mjs",
        "config",
        "validate",
        "--json"
      ],
      "code": 1,
      "signal": null,
      "stdout": "{\n  \"ok\": false,\n  \"error\": {\n    \"type\": \"cli_error\",\n    \"message\": \"OpenClaw config is invalid: $FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\"\n  },\n  \"repairHint\": \"Run `openclaw doctor --fix` to repair, then retry.\",\n  \"valid\": false,\n  \"path\": \"$FIXTURE/config-café\\u001b[31m\\noperator-forged\\tend\\rrow\\u0007.json\",\n  \"issues\": [\n    {\n      \"path\": \"gateway.mode\",\n      \"message\": \"Invalid input (allowed: \\\"local\\\", \\\"remote\\\")\",\n      \"allowedValues\": [\n        \"local\",\n        \"remote\"\n      ]\n    }\n  ]\n}\n",
      "stderr": "",
      "seconds": 3.693903065999999
    }
  ],
  "observations": [
    {
      "label": "valid config path",
      "controls": 0,
      "forgedLine": false,
      "escapedLine": true,
      "unicode": true
    },
    {
      "label": "dry-run config path",
      "controls": 0,
      "forgedLine": false,
      "escapedLine": true,
      "unicode": true
    },
    {
      "label": "shared config confirmation",
      "controls": 0,
      "forgedLine": false,
      "escapedLine": true,
      "unicode": true
    },
    {
      "label": "missing config path",
      "controls": 0,
      "forgedLine": false,
      "escapedLine": true,
      "unicode": true
    },
    {
      "label": "invalid config path",
      "controls": 0,
      "forgedLine": false,
      "escapedLine": true,
      "unicode": true
    },
    {
      "label": "invalid config admission path",
      "controls": 0,
      "forgedLine": false,
      "escapedLine": true,
      "unicode": true
    }
  ],
  "readback": {
    "configSha256Before": "c187780405363a71086a2c1e24d98db463f61e284c448138e5ed242772cd5b43",
    "configSha256After": "c187780405363a71086a2c1e24d98db463f61e284c448138e5ed242772cd5b43",
    "invalidSha256Before": "3028f7764aa92b4bbd54cb61f52b47074b18a9b1c03e38fe614846acc577bca7",
    "invalidSha256After": "3028f7764aa92b4bbd54cb61f52b47074b18a9b1c03e38fe614846acc577bca7",
    "unexpectedConfigWrites": 0,
    "missingFileCreates": 0,
    "jsonRawPathsPreserved": true,
    "shellRawFileContractPreserved": true,
    "ordinaryControlPass": true
  }
}
Reproduction collectors

Save the following two files outside each checkout, build that clean checkout normally with pnpm build cliStartup, and run node proof-config.mjs "$CHECKOUT" red on the pinned base or green on this head. Collectors only use their own synthetic temporary directories.

proof-common.mjs:

import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {execFileSync, spawn} from 'node:child_process';

export const unusual = 'café\x1b[31m\noperator-forged\tend\rrow\x07';

export function fixture(name) {
 const checkout=path.resolve(process.argv[2]);
 const phase=process.argv[3];
 assert.ok(['red','green'].includes(phase));
 const head=execFileSync('git',['rev-parse','HEAD'],{cwd:checkout,encoding:'utf8'}).trim();
 assert.equal(execFileSync('git',['status','--porcelain'],{cwd:checkout,encoding:'utf8'}).trim(),'');
 const stamp=JSON.parse(fs.readFileSync(path.join(checkout,'dist/.buildstamp')));
 assert.equal(stamp.head,head);
 assert.equal(stamp.inputsClean,true);
 const root=fs.mkdtempSync(path.join(os.tmpdir(),`alix-escape-${name}-`));
 for(const leaf of ['home','state','workspace','tmp'])fs.mkdirSync(path.join(root,leaf));
 const configPath=path.join(root,'openclaw.json');
 const config={agents:{ownership:'explicit',defaults:{systemAgent:{agentId:'main'}},entries:{main:{workspace:path.join(root,'workspace')}}},tools:{profile:'minimal'},plugins:{allow:[],slots:{memory:'none'}},logging:{level:'warn',consoleLevel:'warn',file:path.join(root,'runtime.log')}};
 const writeConfig=()=>fs.writeFileSync(configPath,JSON.stringify(config),{mode:0o600});
 writeConfig();
 const env={PATH:`${path.dirname(process.execPath)}:/usr/bin:/bin`,HOME:path.join(root,'home'),TMPDIR:path.join(root,'tmp'),LANG:'C.UTF-8',TZ:'UTC',TERM:'dumb',NO_COLOR:'1',COLUMNS:'320',CI:'1',DO_NOT_TRACK:'1',OPENCLAW_CONFIG_PATH:configPath,OPENCLAW_STATE_DIR:path.join(root,'state'),OPENCLAW_NO_RESPAWN:'1',OPENCLAW_DISABLE_BONJOUR:'1'};
 const receipt={name,phase,head,at:new Date().toISOString(),root,runs:[],observations:[],readback:{}};
 const save=()=>fs.writeFileSync(path.join(root,'receipt.json'),JSON.stringify(receipt,null,2));
 async function command(label, executable, args, options={}){
  const started=performance.now();
  const row=await new Promise((resolve,reject)=>{
   const child=spawn(executable,args,{cwd:checkout,env:{...env,...options.env},stdio:['ignore','pipe','pipe']});
   let stdout='',stderr='';
   const timer=setTimeout(()=>child.kill('SIGKILL'),90000);
   child.stdout.setEncoding('utf8').on('data',x=>{stdout+=x;});
   child.stderr.setEncoding('utf8').on('data',x=>{stderr+=x;});
   child.on('error',reject);
   child.on('close',(code,signal)=>{clearTimeout(timer);resolve({label,args,code,signal,stdout,stderr,seconds:(performance.now()-started)/1000});});
  });
  receipt.runs.push(row);save();
  assert.equal(row.signal,null,`${label}: setup/timeout is not product RED`);
  assert.equal(row.code,options.exit??0,`${label}: ${row.stderr}`);
  return row;
 }
 const run=async(label,args,options)=>command(label,process.execPath,[path.join(checkout,'openclaw.mjs'),...args],options);
 function text(label,output,options={}){
  const controls=[...output.matchAll(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g)].length;
  const forgedLine=output.includes('\noperator-forged');
  const observation={label,controls,forgedLine,escapedLine:output.includes('\\noperator-forged'),unicode:output.includes('café')};
  receipt.observations.push(observation);save();
  assert.equal(controls>0,phase==='red',`${label}: control result`);
  if(!options.table)assert.equal(forgedLine,phase==='red',`${label}: injected report row`);
  assert.equal(observation.unicode,true,`${label}: Unicode control`);
  if(phase==='green')assert.equal(observation.escapedLine,true,`${label}: retain visible escaped line`);
 }
 function finish(){receipt.result='PASS';save();console.log(JSON.stringify({name,phase,head,result:'PASS',receipt:path.join(root,'receipt.json'),observations:receipt.observations,readback:receipt.readback}));}
 return {checkout,root,configPath,config,writeConfig,env,receipt,run,command,text,save,finish,hash:bytes=>createHash('sha256').update(bytes).digest('hex')};
}

proof-config.mjs:

import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fixture, unusual } from './proof-common.mjs';

const f = fixture('config-paths');
f.config.agents.defaults.skipBootstrap = true;
f.config.gateway = { mode: 'local' };
f.writeConfig();
const configPath = path.join(f.root, `config-${unusual}.json`);
fs.copyFileSync(f.configPath, configPath);
const env = { OPENCLAW_CONFIG_PATH: configPath };
const before = fs.readFileSync(configPath);
const valid = await f.run('validate-valid-human', ['config', 'validate'], { env });
assert.ok(valid.stdout.includes('Config valid: '));
f.text('valid config path', valid.stdout);
const json = await f.run('validate-valid-json', ['config', 'validate', '--json'], { env });
assert.equal(JSON.parse(json.stdout).path, configPath);
assert.equal(JSON.parse(json.stdout).valid, true);
const dryArgs = ['config', 'set', 'gateway.mode', '"local"', '--strict-json', '--dry-run'];
const dry = await f.run('dry-run-human', dryArgs, { env });
assert.ok(dry.stdout.includes('Dry run successful: 1 update(s) validated against '));
f.text('dry-run config path', dry.stdout);
const dryJson = await f.run('dry-run-json', [...dryArgs, '--json'], { env });
assert.equal(JSON.parse(dryJson.stdout).configPath, configPath);
assert.equal(JSON.parse(dryJson.stdout).ok, true);
const raw = await f.run('raw-file-contract', ['config', 'file'], { env });
assert.equal(raw.stdout, `${configPath}\n`);
const fileJson = await f.run('file-json-contract', ['config', 'file', '--json'], { env });
assert.equal(JSON.parse(fileJson.stdout).path, configPath);
const setup = await f.run('shared-config-confirmation', ['setup', '--baseline'], { env });
assert.ok(setup.stdout.includes('Config OK: '));
f.text('shared config confirmation', setup.stdout);
assert.deepEqual(fs.readFileSync(configPath), before);
const afterValid = fs.readFileSync(configPath);
const ordinary = await f.run('ordinary-control', ['config', 'validate']);
assert.ok(ordinary.stdout.includes(`Config valid: ${f.configPath}\n`));
assert.equal(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(ordinary.stdout), false);
const missingPath = path.join(f.root, `missing-${unusual}.json`);
const missing = await f.run('validate-missing-human', ['config', 'validate'], { env: { OPENCLAW_CONFIG_PATH: missingPath }, exit: 1 });
assert.ok(missing.stderr.includes('Config file not found: '));
f.text('missing config path', missing.stderr);
assert.equal(fs.existsSync(missingPath), false);
const invalidBytes = Buffer.from(JSON.stringify({ ...f.config, gateway: { mode: 'not-a-mode' } }));
fs.writeFileSync(configPath, invalidBytes);
const invalid = await f.run('validate-invalid-human', ['config', 'validate'], { env, exit: 1 });
assert.ok(invalid.stderr.includes('Config needs correction: '));
f.text('invalid config path', invalid.stderr);
const refused = await f.run('get-invalid-human', ['config', 'get', 'gateway.mode'], { env, exit: 1 });
assert.ok(refused.stderr.includes('OpenClaw config is invalid: '));
f.text('invalid config admission path', refused.stderr);
const invalidJson = await f.run('validate-invalid-json', ['config', 'validate', '--json'], { env, exit: 1 });
assert.equal(JSON.parse(invalidJson.stdout).path, configPath);
assert.equal(JSON.parse(invalidJson.stdout).valid, false);
assert.deepEqual(fs.readFileSync(configPath), invalidBytes);
f.receipt.readback = { configSha256Before: f.hash(before), configSha256After: f.hash(afterValid), invalidSha256Before: f.hash(invalidBytes), invalidSha256After: f.hash(fs.readFileSync(configPath)), unexpectedConfigWrites: 0, missingFileCreates: 0, jsonRawPathsPreserved: true, shellRawFileContractPreserved: true, ordinaryControlPass: true };
f.finish();

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@Alix-007
Alix-007 marked this pull request as ready for review October 26, 2026 13:40
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation cli CLI command changes size: S labels Oct 26, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR sanitizes config filenames in human-readable reports while preserving raw paths in JSON and shell-oriented output.

Example: Run config validate with the filename /tmp/café followed by a newline and operator-forged.json.

  • Before: The filename creates a separate operator-forged.json report row.
  • After: The report displays /tmp/café\noperator-forged.json on one line.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-level fix with relevant shipped-CLI before/after evidence and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied built-CLI traces on the pinned base and exact head exercise validation, invalid-config admission, dry-run, and setup confirmation in isolated Linux fixtures; head output contains no injected rows, preserves Unicode and raw JSON/shell paths, and retains config bytes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Config filenames containing terminal controls can change terminal presentation or create forged status rows.
Reason: A narrow display repair prevents misleading reports without rejecting valid filenames or changing settings and command semantics.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current-main terminal-output defect with a focused change using existing owners; no actionable introduced bugs were found.

Priority: P2
Reviewed head: d6c0205dfe60bd7531538403b8a863335c003980

Before merge

None.

Findings

None.

Agent review details

How this fits together

Config CLI commands and shared confirmation messages consume raw config paths; the existing display formatter now sanitizes those paths before terminal output.

flowchart TD
  A[Raw config path] --> B[Config commands]
  B --> C[Config path formatter]
  C --> D[Terminal text sanitizer]
  D --> E[Human reports]
  B --> F[Raw JSON and shell output]
Loading

Technical review

Best possible solution:

Land the existing display-boundary fix while retaining raw filesystem and machine-output contracts.

Do we have a high-confidence way to reproduce the issue?

Current-main source directly interpolates control-bearing filenames, and the supplied pinned-base CLI captures demonstrate forged rows; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The smallest complete fix is to sanitize paths in the existing display formatter and replace direct human-report formatting with that owner, as this PR does.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3d409f3138c4.

Provenance checked

  • Shared config path display keeps the original intent (5d001cb: Introduce a shared config logging formatter; later changes preserve live path selection and truthful backup reporting.)
  • Config validation and invalid-config admission keeps the original intent (fix(config): render actionable validation errors #124763: Provide actionable config diagnostics with filenames, source locations, and repair guidance; subsequent refactors preserve command and JSON contracts.)
  • Dry-run report rendering keeps the original intent (2d625da: Separate output formatting from validation and persistence while preserving complete JSON output.)
  • Gateway config-file mismatch diagnostic keeps the original intent (5f62201: Keep the Gateway as the single writer and refuse mutations prepared from a different config file.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned change: The introduced diff changes display formatting and its regression coverage without changing config validation policy, persistence, or command options. (src/config/logging.ts:18, d6c0205dfe60)
  • Current main still exposes the defect: Current main returns displayPath(path) without terminal sanitization; validation reports likewise interpolate shortened raw filenames. (src/config/logging.ts:17, 3d409f3138c4)
  • Existing sanitizer contract: sanitizeTerminalText strips ANSI sequences and other control characters while rendering newline, tab, and carriage return visibly. (packages/terminal-core/src/safe-text.ts:11, d6c0205dfe60)
  • Exact-head CLI proof: The complete PR body supplies base/head built-CLI streams and collectors for validation, invalid-config admission, dry-run, setup confirmation, raw config file output, and JSON. Head captures remove injected report rows, retain Unicode, preserve raw machine paths, and show unchanged valid and invalid config hashes. (d6c0205dfe60)
  • Feature history: The config logging helper was introduced under the earlier name formatConfigPath; subsequent history preserves runtime path selection and backup-existence checks. (src/config/logging.ts, 5d001cb9531c)
  • Prior accepted sanitization: In fix(config): sanitize validation log output to prevent control character injection #39116 (comment), steipete records manually landing validation-log sanitization; that work covered a different output owner and does not replace this PR.

Likely related people:

  • Peter Steinberger: Raw commit 24ed5ad adds src/config/logging.ts:16 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 24ed5ad90e5b; files: src/config/logging.ts)
  • Dallin Romney: Raw commit 5f62201 adds src/cli/config-cli.ts:122 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5f622010788d; files: src/cli/config-cli.ts)
  • Josh Avant: Raw commit e999631 adds src/cli/config-set-dryrun.ts:12 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: e99963100d22; files: src/cli/config-set-dryrun.ts)

PR surface

Source +2, Tests +91, Docs +4. Total +97 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 11 9 +2
Tests 3 113 22 +91
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 128 31 +97

Labels

Label changes:

  • add P2: Control-bearing config filenames can alter terminal presentation and forge report rows, with limited exposure in an operator-facing CLI surface.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Control-bearing config filenames can alter terminal presentation and forge report rows, with limited exposure in an operator-facing CLI surface.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 26, 2026, 9:58 AM ET / 13:58 UTC.

obviyus added a commit that referenced this pull request Oct 27, 2026
fix(cli): escape terminal controls in untrusted values through one owner

CLI human-readable output printed user-controlled values such as config paths, names, directories, binding descriptions, plugin metadata and dead-letter scopes without neutralizing terminal control sequences, so a crafted value could inject ANSI, OSC 8 or C1 sequences into the terminal. Earlier fixes wrapped one call site at a time. A single owner now does this: `terminalText` in terminal-core's safe-text escapes interpolated values before styling, and the display-only `displayPath` delegates to it. Raw path shortening, JSON output and the trusted styling of `renderTable` are unchanged, and the per-site wrapping is replaced.

This absorbs #184685, #184666, #184324, #184303, #176763, #176773 and #172873 by @Alix-007 and #184861 by @qingminglong, whose original commits are kept, and moves the earlier merged per-site fixes onto the same owner.

Evidence: built CLI in a secretless container, with ESC/CSI, OSC 8 and C1 sequences injected into values for eleven commands across eight families. Main printed the raw sequences; this change printed them neutralized, normal colored output and JSON values were unchanged, and dead-letter errors keep their stderr and JSON contracts. Raw-byte captures: #185927 (comment). Production +81.

Co-authored-by: Alix-007 <[email protected]>
Co-authored-by: qingminlong <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Thanks @Alix-007. This is now fixed at the root in #185927 (2d2b465): one terminalText owner in terminal-core's safe-text escapes untrusted values for all CLI human output, replacing the per-site wrapping. Your commit from this PR is kept in that merge and you're credited as co-author, so I'm closing this one as covered. For future output sites, please route values through terminalText (or displayPath for paths) instead of opening a PR per call site.

@obviyus obviyus closed this Oct 27, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
fix(cli): escape terminal controls in untrusted values through one owner

CLI human-readable output printed user-controlled values such as config paths, names, directories, binding descriptions, plugin metadata and dead-letter scopes without neutralizing terminal control sequences, so a crafted value could inject ANSI, OSC 8 or C1 sequences into the terminal. Earlier fixes wrapped one call site at a time. A single owner now does this: `terminalText` in terminal-core's safe-text escapes interpolated values before styling, and the display-only `displayPath` delegates to it. Raw path shortening, JSON output and the trusted styling of `renderTable` are unchanged, and the per-site wrapping is replaced.

This absorbs openclaw#184685, openclaw#184666, openclaw#184324, openclaw#184303, openclaw#176763, openclaw#176773 and openclaw#172873 by @Alix-007 and openclaw#184861 by @qingminglong, whose original commits are kept, and moves the earlier merged per-site fixes onto the same owner.

Evidence: built CLI in a secretless container, with ESC/CSI, OSC 8 and C1 sequences injected into values for eleven commands across eight families. Main printed the raw sequences; this change printed them neutralized, normal colored output and JSON values were unchanged, and dead-letter errors keep their stderr and JSON contracts. Raw-byte captures: openclaw#185927 (comment). Production +81.

Co-authored-by: Alix-007 <[email protected]>
Co-authored-by: qingminlong <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@Alix-007

Copy link
Copy Markdown
Contributor Author

Thanks @obviyus for the shared fix and for keeping the attribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants