Skip to content

fix(kimi): preserve config mode during hook writes - #20623

Closed
Pr1p wants to merge 3 commits into
stablyai:mainfrom
Pr1p:fix/kimi-config-file-mode
Closed

Pr1p wants to merge 3 commits into
stablyai:mainfrom
Pr1p:fix/kimi-config-file-mode

Conversation

@Pr1p

@Pr1p Pr1p commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Updating Kimi hook settings replaces its TOML config through a temporary file. The settings stayed intact, but the replacement file could lose its private permissions. This keeps existing permissions and makes a newly created config owner-only. If Orca cannot read an existing config's permissions, it leaves that config untouched instead of guessing.

What Changed

  • Create the temporary Kimi config file with mode 0600.
  • Restore an existing config's permission mode before the atomic rename replaces its inode.
  • Stop the rewrite when an existing config's mode cannot be read, rather than replacing it with guessed permissions.
  • Add POSIX regressions for preserving an existing 0640 file under a restrictive umask and for creating a new 0600 file.
  • Add a focused regression that simulates a mode-read failure and verifies the existing config is untouched.
  • Isolate USERPROFILE alongside HOME in the hook-service tests so Windows never writes a managed script to the real user profile.

Why

Kimi's config may contain an api_key. Atomic rename swaps in the temporary inode, so its mode becomes the config mode unless explicitly restored. This prevents an existing private config from becoming more broadly readable while retaining user-selected permissions. Aborting on an unreadable mode avoids a race or metadata failure silently narrowing an existing file's access.

Linked Issue

Fixes #20597

Visual Proof

N/A — this only changes local TOML file permissions; there is no rendered UI or interaction change.

Testing

  • I manually tested these changes locally — not applicable: this is a local filesystem permission change and needs no Kimi account or network request.
  • Automated tests added/updated.
    • node ... vitest ... src/main/kimi/hook-service.test.ts src/main/kimi/hook-service-mode-read-failure.test.ts src/main/kimi/kimi-hook-config-toml.test.ts — 33 passed, 2 POSIX-only permission tests skipped on Windows and will run on Linux CI.
    • oxlint src/main/kimi/hook-service.ts src/main/kimi/hook-service.test.ts src/main/kimi/hook-service-mode-read-failure.test.ts
    • A direct node typecheck made no progress locally after 2.5 minutes; CI should run the full typecheck.

AI Disclosure

Used OpenAI Codex (GPT-5) for implementation and test authoring. I reviewed the change and ran the focused validation above.

Review

  • Security: newly created configs are owner-only; an existing user-selected mode is preserved through the atomic rewrite.
  • Failure handling: a mode-read failure leaves an existing config untouched instead of guessing a replacement mode.
  • Backwards compatibility: TOML content and the atomic backup/rename behavior are unchanged when metadata is available.

Agent skill upstream boundary

  • Not applicable.

Notes

  • POSIX file modes do not have an equivalent Windows assertion, so the permission-specific regressions are intentionally skipped on Windows and run in Linux CI.
  • No UI, mobile, SSH/remote, or path/shortcut behavior changes.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one minor test-quality suggestion inline.

Reviewed changes

  • Preserve config.toml mode across the atomic rewrite — writeConfigToml() now pins 0o600 for a newly created config and, when overwriting, reads the existing statSync(...).mode & 0o777; it writes the temp file with mode: 0o600 and then chmodSync(tmpPath, mode) so the rename can't widen the config (e.g. 0600 → 0644 under a permissive umask).
  • POSIX regression coverage — hook-service.test.ts adds tests that an existing 0640 survives install + remove under umask 077, and that a fresh config is 0600.
  • Test isolation hardening — USERPROFILE is now redirected to the temp dir alongside HOME, so Windows can't write the managed script into the real user profile.

The core fix is correct: the explicit chmodSync is what defeats umask masking (passing mode to writeFileSync alone would still be masked). I verified the .bak copy keeps the source mode, so the backup doesn't reintroduce the exposure.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/kimi/hook-service.test.ts Resolved
@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 0b519a76-4240-4234-832b-bbdfe16da8d0

📥 Commits

Reviewing files that changed from the base of the PR and between c4fc209 and 94defbc.

📒 Files selected for processing (2)
  • src/main/kimi/hook-service-mode-read-failure.test.ts
  • src/main/kimi/hook-service.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

writeConfigToml now preserves the existing config.toml mode during atomic replacement. New configuration files use mode 0600. A mode-read failure now propagates without overwriting the existing file. Tests isolate HOME and USERPROFILE, restore environment state, and verify POSIX permissions and failure behavior.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 94def

Configuration updates preserve existing permissions, create new files with owner-only permissions, and leave existing files unchanged when mode inspection fails. No merge-blocking issue remains.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: preserving Kimi configuration file permissions during hook writes.
Description check ✅ Passed The description follows the repository template and covers the change, rationale, linked issue, testing, platform impact, AI disclosure, review notes, and checklist. It also explains that full typeche…
Linked Issues check ✅ Passed The changes satisfy the coding requirements in issue #20597. writeConfigToml() uses mode 0600 for new temporary files. It reads and applies the existing mode before atomic replacement. A failed mo…
Out of Scope Changes check ✅ Passed The changes remain within issue #20597. Production changes update Kimi configuration write permissions and failure handling. The added tests verify the required behavior. The Windows environment isola…
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 3 files.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)
src/main/kimi/hook-service.ts (1)

142-161: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Abort when statSync cannot read the existing config mode

KimiHookService.install() and remove() call writeConfigToml. If statSync(configPath) fails after the content changes, mode remains 0o600. If the path exists again at the later check, copyFileSync and renameSync replace it with mode 0o600. A delete-and-recreate race can produce this path. This violates the existing-file mode-preservation contract and can remove access granted by the prior mode. Handle the metadata read separately and abort when statSync fails. Use 0o600 only when the config is known to be absent.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d339c147-ecd8-4414-aeef-7c32c4e5ec3d

📥 Commits

Reviewing files that changed from the base of the PR and between 93c3702 and 78fa0f8.

📒 Files selected for processing (2)
  • src/main/kimi/hook-service.test.ts
  • src/main/kimi/hook-service.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior pullfrog review (78fa0f8 → c4fc209): a single test-determinism commit.

  • Pinned the umask in the new-config mode regression — the creates a new config with an owner-only mode test now wraps install() in process.umask(0o022) and restores the previous umask in finally. Under unfixed code the temp write becomes 0o666 & ~0o022 = 0o644, so the assertion fails regardless of the runner's ambient umask; with the fix it stays 0o600. This addresses the prior inline note and the regression now has real teeth.

The core fix from 78fa0f8 is unchanged and remains correct: the explicit chmodSync(tmpPath, mode) is what defeats umask masking after the atomic rename swaps the inode.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The new mode-read-failure test trips the required changed-code quality gate: its casting scan flags three as casts, so the static_analysis job the verify aggregate requires will stay red until they are suppressed or removed.

Reviewed changes

Reviewed the delta since the prior pullfrog review (c4fc209 → 94defbc).

  • Abort on an unreadable config mode — writeConfigToml() moved mode = statSync(configPath).mode & 0o777 outside the read try/catch, so a metadata failure now throws instead of silently rewriting an existing config with a guessed 0o600. The registry callers (runInstaller, removeManagedAgentHooks) catch and convert to an error status, so the new throw is a safe failure mode.
  • Added a mode-read-failure regression — hook-service-mode-read-failure.test.ts mocks node:fs.statSync to throw for the config path and asserts install() rejects and the config text is untouched. It fails against the pre-94defbc code that swallowed the stat error, so it has real regression value.

The functional change is correct; the only blocker is the gate failure below.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

import { tmpdir } from 'node:os'
import { join } from 'node:path'

const modeReadFailure = vi.hoisted(() => ({ path: null as string | null }))

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.

This new file fails the required changed-code quality gate: the casting scan (assertionStyle: never from config/oxlint-code-quality-casting.json) reports three typescript/consistent-type-assertions errors on the added as casts (reported at lines 6, 10 and 14). pnpm run check:code-quality:changed is enforced by the static_analysis job that verify requires, so the PR stays red until they are suppressed or removed. The author's local oxlint run used the root config, where an as cast is legal, which is why it looked clean.

Technical details
# Casting gate fails on the new mode-read-failure test

## Affected sites
- `src/main/kimi/hook-service-mode-read-failure.test.ts:6` — `path: null as string | null`.
- `src/main/kimi/hook-service-mode-read-failure.test.ts:10` and `:14` — the `statSync` mock: `(…) => unknown` and `) as typeof actual.statSync`.

## Required outcome
- `pnpm run check:code-quality:changed` reports 0 casting findings without weakening the test.

## Suggested approach
- Add `// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: <why>` directly above each cast. Verified locally that this suppresses the rule, and the gate's `isCastingDirectiveUnusedWarning` exempts the root-scan "unused directive" warning the directive would otherwise raise.
- Or remove the casts: `vi.hoisted((): { path: string | null } => ({ path: null }))`, and type the mock function with an annotation instead of `as typeof actual.statSync`.

@nwparker

Copy link
Copy Markdown
Contributor

Closing as superseded by merged #22422, which carries the reviewed fix and regression coverage. Thank you for the original contribution.

@nwparker nwparker closed this Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Atomic TOML config writes (temp+rename) lose restrictive file mode; Kimi config.toml can drop 0600

2 participants