Skip to content

fix(cli): harden config file permission handling#1370

Open
cv wants to merge 15 commits intomainfrom
cv/config-io-preset-validation
Open

fix(cli): harden config file permission handling#1370
cv wants to merge 15 commits intomainfrom
cv/config-io-preset-validation

Conversation

@cv
Copy link
Copy Markdown
Contributor

@cv cv commented Apr 2, 2026

Summary

This PR was originally broader, but most of that work has since landed on main independently.
After merging main into this branch, the remaining diff is now narrowly focused on config I/O hardening:

  • improve ConfigPermissionError messages with actionable remediation for wrong-owner / sudo-created ~/.nemoclaw state
  • tighten pre-existing config directory permissions to 0700
  • avoid the existsSync() / read TOCTOU pattern in config reads
  • add an explicit writability check in ensureConfigDir()
  • route registry lock-directory creation through the shared permission-aware config-dir helper
  • expand focused tests for config I/O and registry behavior

Files still changed in this PR:

  • src/lib/config-io.ts
  • src/lib/config-io.test.ts
  • src/lib/registry.ts

Why keep this PR

The main TypeScript migration and initial config-io extraction already landed on main.
This PR now carries only the remaining permission-hardening and follow-up fixes that were not absorbed upstream.

Testing

  • npm run build:cli
  • npx vitest run src/lib/config-io.test.ts test/registry.test.js test/policies.test.js

Related issues

…lidation

Add src/lib/config-io.ts with atomic JSON read/write (temp + rename),
EACCES error handling with user-facing remediation hints, and directory
permission enforcement.

- Refactor credentials.js to use readConfigFile/writeConfigFile
- Refactor registry.js to use readConfigFile/writeConfigFile
- Add validatePreset() to policies.js (warns on missing binaries section)
- ConfigPermissionError with actionable remediation (sudo chown / rm)
- Co-located tests for config-io module

Fixes #692, #606. Supersedes the config-io and preset validation parts
of #782 (without the runner.js redaction, which landed separately in
#1246).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 2, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Added a permission-aware config I/O module with atomic write semantics and a dedicated permission error type; replaced inline fs/JSON logic in registry and credentials with the new helpers; added preset validation in policies; added tests and a CommonJS shim for the compiled config-io output.

Changes

Cohort / File(s) Summary
Config I/O Implementation
src/lib/config-io.ts, bin/lib/config-io.js
New TypeScript module providing ConfigPermissionError, ensureConfigDir(), writeConfigFile(), and readConfigFile() (atomic temp-file writes, EACCES wrapping); added CJS re-export shim forwarding to dist/lib/config-io.
Refactored File I/O Users
bin/lib/credentials.js, bin/lib/registry.js
Replaced inline fs/JSON parsing, mkdir/chmod, and manual atomic-write logic with calls to readConfigFile/writeConfigFile and ensureConfigDir from config-io; removed ad-hoc temp-file and permission handling.
Policy Validation
bin/lib/policies.js
Added and exported validatePreset(presetContent, presetName) which warns and causes early return from applyPreset() when binaries: is missing.
Tests Added/Updated
src/lib/config-io.test.ts, test/registry.test.js
New Vitest suite for config-io covering dir perms (0o700), atomic writes, defaults for missing/corrupt files, temp-file cleanup, and ConfigPermissionError contents; updated registry test to expect wrapped error message "Cannot write config file".

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant CIO as config-io
    participant FS as Filesystem

    App->>CIO: writeConfigFile(targetPath, data)
    CIO->>CIO: ensureConfigDir(parentDir)
    CIO->>FS: mkdir -p parentDir (mode 0o700)
    FS-->>CIO: success / EACCES
    alt EACCES
        CIO->>App: throw ConfigPermissionError (with remediation)
    else Success
        CIO->>FS: write temp file (0o600, PID-suffix)
        FS-->>CIO: write success / error
        CIO->>FS: rename(temp, target)
        FS-->>CIO: rename success / EACCES
        alt Rename EACCES
            CIO->>FS: unlink(temp) [best-effort]
            CIO->>App: throw ConfigPermissionError
        else Success
            CIO->>App: return
        end
    end
Loading
sequenceDiagram
    participant App as Application
    participant CIO as config-io
    participant FS as Filesystem

    App->>CIO: readConfigFile(path, default)
    CIO->>FS: stat/access path
    FS-->>CIO: exists / missing / EACCES
    alt EACCES
        CIO->>App: throw ConfigPermissionError
    else Missing
        CIO->>App: return default
    else Exists
        CIO->>FS: readFile(path)
        FS-->>CIO: contents
        CIO->>CIO: JSON.parse(contents)
        alt Parse error
            CIO->>App: return default
        else Success
            CIO->>App: return parsed data
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A rabbit's note on safe config:
I hop where files are written neat,
Temp names snug, and modes to meet,
If perms deny, I'll warn and show
How to chown home so configs grow. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR implements core requirements from issue #692: adds ConfigPermissionError with remediation guidance [#692], ensures directories created with 0o700 permissions [#692], detects and handles EACCES gracefully [#692], and adds validatePreset to handle invalid presets [#676].
Out of Scope Changes check ✅ Passed All changes are scoped to config-io module implementation, refactoring related modules (credentials, registry, policies), and corresponding test updates—all directly related to the PR's stated objectives.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'fix(cli): harden config file permission handling' directly aligns with the main objectives: adding robust config file I/O with permission error handling via ConfigPermissionError and refactoring credential/registry modules to use safe file operations.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cv/config-io-preset-validation

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@bin/lib/policies.js`:
- Around line 65-73: The current check in validatePreset using
presetContent.includes("binaries:") can be fooled by comments or scalars;
instead parse the YAML and detect a real top-level key. Replace the substring
check in validatePreset with a YAML parse (e.g., yaml.parse / js-yaml.safeLoad)
of presetContent and then check for Object.prototype.hasOwnProperty.call(parsed,
"binaries") (and that parsed.binaries is not undefined/null); if parsing fails,
log a warning and treat the preset as missing the binaries section so the
original warning is emitted for presetName.

In `@src/lib/config-io.ts`:
- Around line 29-41: The current buildRemediation() message assumes sudo is
available; update it to include non-sudo fallback actions so environments
without sudo get actionable guidance. In the buildRemediation() function
(reference: nemoclawDir and HOME usage) add alternative suggestions such as
recreating the config under the current user's home (e.g., remove or move the
directory if writable), instructing to remove the directory without sudo when
the user owns it (e.g., rm -rf $HOME/.nemoclaw), and advising to relocate or
initialize config in a user-writable path (for example creating a new config
under $HOME or specifying an alternative CONFIG_HOME), so the error message
covers both sudo and non-sudo environments. Ensure the text clearly
distinguishes when sudo is required vs when the non-sudo command applies.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b236f71c-5208-4de3-9a9b-e2b0d59af3a1

📥 Commits

Reviewing files that changed from the base of the PR and between 86b3dee and 38424c6.

📒 Files selected for processing (7)
  • bin/lib/config-io.js
  • bin/lib/credentials.js
  • bin/lib/policies.js
  • bin/lib/registry.js
  • src/lib/config-io.test.ts
  • src/lib/config-io.ts
  • test/registry.test.js

Comment on lines +65 to +73
function validatePreset(presetContent, presetName) {
if (!presetContent.includes("binaries:")) {
console.warn(
` Warning: preset '${presetName}' has no binaries section — ` +
`this will cause 403 errors in the sandbox (ref: #676)`,
);
return false;
}
return true;
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.

⚠️ Potential issue | 🟡 Minor

Detect the actual YAML key, not a raw substring.

presetContent.includes("binaries:") also matches comments, descriptions, or other scalar text, so a preset can still lack the real binaries section and skip the warning. Please parse the preset or at least anchor the check to a YAML key.

Suggested fix
 function validatePreset(presetContent, presetName) {
-  if (!presetContent.includes("binaries:")) {
+  let parsed = null;
+  try {
+    parsed = YAML.parse(presetContent);
+  } catch {
+    parsed = null;
+  }
+  if (
+    !parsed ||
+    typeof parsed !== "object" ||
+    !Object.prototype.hasOwnProperty.call(parsed, "binaries")
+  ) {
     console.warn(
       `  Warning: preset '${presetName}' has no binaries section — ` +
         `this will cause 403 errors in the sandbox (ref: `#676`)`,
     );
     return false;
   }
   return true;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bin/lib/policies.js` around lines 65 - 73, The current check in
validatePreset using presetContent.includes("binaries:") can be fooled by
comments or scalars; instead parse the YAML and detect a real top-level key.
Replace the substring check in validatePreset with a YAML parse (e.g.,
yaml.parse / js-yaml.safeLoad) of presetContent and then check for
Object.prototype.hasOwnProperty.call(parsed, "binaries") (and that
parsed.binaries is not undefined/null); if parsing fails, log a warning and
treat the preset as missing the binaries section so the original warning is
emitted for presetName.

Comment on lines +29 to +41
function buildRemediation(): string {
const home = process.env.HOME || os.homedir();
const nemoclawDir = path.join(home, ".nemoclaw");
return [
" To fix, run one of:",
"",
` sudo chown -R $(whoami) ${nemoclawDir}`,
` # or, if the directory was created by another user:`,
` sudo rm -rf ${nemoclawDir} && nemoclaw onboard`,
"",
" This usually happens when NemoClaw was first run with sudo",
" or the config directory was created by a different user.",
].join("\n");
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.

⚠️ Potential issue | 🟠 Major

Remediation still assumes sudo exists.

Issue #692 explicitly includes environments where sudo is unavailable, but both suggested fixes here still require it. In those installs the new ConfigPermissionError is still not actionable. Please add a non-sudo fallback, e.g. recreating config under a user-writable HOME or config directory.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/config-io.ts` around lines 29 - 41, The current buildRemediation()
message assumes sudo is available; update it to include non-sudo fallback
actions so environments without sudo get actionable guidance. In the
buildRemediation() function (reference: nemoclawDir and HOME usage) add
alternative suggestions such as recreating the config under the current user's
home (e.g., remove or move the directory if writable), instructing to remove the
directory without sudo when the user owns it (e.g., rm -rf $HOME/.nemoclaw), and
advising to relocate or initialize config in a user-writable path (for example
creating a new config under $HOME or specifying an alternative CONFIG_HOME), so
the error message covers both sudo and non-sudo environments. Ensure the text
clearly distinguishes when sudo is required vs when the non-sudo command
applies.

cv added a commit that referenced this pull request Apr 2, 2026
Convert the last 3 blocked-by-#782 CJS modules to TypeScript:

- credentials.js → src/lib/credentials.ts
- registry.js → src/lib/registry.ts
- policies.js → src/lib/policies.ts

716 CLI tests pass. Coverage ratchet passes.
Depends on #1370 (config-io module). Relates to #924.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Copy link
Copy Markdown
Contributor

@ericksoa ericksoa left a comment

Choose a reason for hiding this comment

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

Nice consolidation — the deduplication of atomic-write logic from credentials.js and registry.js into a shared module is clean, and the ConfigPermissionError with remediation hints is a real UX win for #692.

A few items worth considering before merge (inline comments below).

@wscurran wscurran added NemoClaw CLI Use this label to identify issues with the NemoClaw command-line interface (CLI). enhancement: refactoring labels Apr 3, 2026
cv and others added 2 commits April 3, 2026 01:35
- ensureConfigDir: chmod 0o700 on pre-existing dirs with weaker modes
  (preserves old credentials.js hardening behavior)
- readConfigFile: remove TOCTOU existsSync, catch ENOENT directly
- acquireLock: use ensureConfigDir for consistent permission errors
- applyPreset: bail early when validatePreset returns false

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@cv
Copy link
Copy Markdown
Contributor Author

cv commented Apr 3, 2026

All four items addressed in a63e957:

  1. chmod on pre-existing dirsensureConfigDir now stat-checks and tightens permissions when the existing mode is weaker than 0o700 (preserves the old chmodSync hardening)
  2. TOCTOU removedreadConfigFile now tries readFileSync directly and catches ENOENT alongside corrupt JSON
  3. acquireLock uses ensureConfigDir — permission failures in lock acquisition now surface ConfigPermissionError with remediation
  4. applyPreset bails early — returns false when validatePreset fails instead of continuing to apply a preset missing binaries

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@bin/lib/policies.js`:
- Around line 253-256: The calls to applyPreset (used in the resume flow,
interactive flow, and single selection flow) are ignoring its boolean return and
thus silently continuing on failure; update each call site that currently just
calls applyPreset (notably the resume, interactive and single-selection code
paths) to check the return value and handle failure the same way as the other
sites: either throw an error when applyPreset returns false or wrap the call in
the same try/catch + retry logic used at the other locations (the handlers
around applyPreset that perform retries at lines noted in the review), ensuring
failures are logged and cause the flow to abort or retry rather than silently
proceeding.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c59564c8-12c4-4072-badd-41205052bfa1

📥 Commits

Reviewing files that changed from the base of the PR and between 45f3d93 and a63e957.

📒 Files selected for processing (3)
  • bin/lib/policies.js
  • bin/lib/registry.js
  • src/lib/config-io.ts
✅ Files skipped from review due to trivial changes (1)
  • src/lib/config-io.ts

@cv cv enabled auto-merge (squash) April 3, 2026 09:00
cv added a commit that referenced this pull request Apr 3, 2026
The selectFromList function was added to policies.js on main (via #1370)
after our TS migration branched. Add the typed implementation to keep
the TS module in sync.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@cv cv requested a review from ericksoa April 4, 2026 00:17
@cv cv changed the title fix(cli): add config-io module for safe config file I/O and preset validation fix(cli): harden config file permission handling Apr 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement: refactoring NemoClaw CLI Use this label to identify issues with the NemoClaw command-line interface (CLI).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants