Jelajahi Sumber

fix: preserve private read-only config during permission repair

hetaoBackend 2 bulan lalu
induk
melakukan
400a025182

+ 1 - 1
docs/examples.md

@@ -64,7 +64,7 @@ pnpm mcode provider list --json
 
 `--context-limit` and `--output-limit` each accept a positive safe integer (at most `9007199254740991`). Either flag can be used independently. The same limits apply to every repeated `--model`; only the first model is tested and selected by `--use`. The JSON list shows the configured values as `contextLimit` and `maxOutputTokens`. Without these flags, the existing defaults remain unchanged (unknown custom models currently fall back to 200,000 context tokens and 16,384 output tokens). Model discovery does not infer your local server's context size.
 
-`--api-key-env` reads the current environment variable value and stores that value in the active profile's `config.yaml`; it does not save an environment-variable reference. The file still contains plaintext credentials. On POSIX systems, MCode restricts the config and its migration backups to mode `0600`, including existing files when loaded. Config writes and temporary copies also use `0600`. Windows file modes do not provide equivalent ACL protection; restrict access to the profile directory using Windows permissions.
+`--api-key-env` reads the current environment variable value and stores that value in the active profile's `config.yaml`; it does not save an environment-variable reference. The file still contains plaintext credentials. On POSIX systems, config writes and temporary copies use `0600`. When loading existing files, MCode removes group/other access while preserving the owner's permissions; already-private files such as `0400` or `0600` do not require a permission change. Loading fails if an unsafe main config cannot be restricted. Older migration backups are also checked, but inspection or repair failures produce a warning identifying the directory or backup that needs manual attention rather than preventing the main config from loading. Windows file modes do not provide equivalent ACL protection; restrict access to the profile directory using Windows permissions.
 
 [Live acceptance](verification.md) separately verified MiniMax Token Plan and one configured BYOK provider. This is not a guarantee for every compatible service.
 

+ 22 - 3
packages/config/src/byok-config.ts

@@ -474,13 +474,32 @@ function rewriteNexusModelProvider(
   return true;
 }
 
-/** Repair credential-bearing backups produced by older versions on profile load. */
+/** Repair old backups without making archival maintenance a config-load dependency. */
 export function restrictLegacyByokBackups(configPath: string): void {
   if (process.platform === 'win32') return;
   const directory = path.dirname(configPath);
-  for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
+  let entries: fs.Dirent[];
+  try {
+    entries = fs.readdirSync(directory, { withFileTypes: true });
+  } catch {
+    console.warn(
+      `[config] Could not inspect legacy BYOK backups in ${JSON.stringify(directory)}. ` +
+      'Backup permissions were not verified; check directory access and restrict backup permissions manually.',
+    );
+    return;
+  }
+  for (const entry of entries) {
     if (entry.isFile() && entry.name.startsWith(LEGACY_BYOK_BACKUP_PREFIX)) {
-      restrictConfigFileSync(path.join(directory, entry.name));
+      const backupPath = path.join(directory, entry.name);
+      try {
+        restrictConfigFileSync(backupPath);
+      } catch {
+        // Do not expose arbitrary error messages that could contain config content.
+        console.warn(
+          `[config] Could not restrict legacy BYOK backup ${JSON.stringify(backupPath)}. ` +
+          'It may still be readable by other users; restrict its permissions manually.',
+        );
+      }
     }
   }
 }

+ 6 - 3
packages/config/src/private-config-file.ts

@@ -3,10 +3,13 @@ import fs from "node:fs";
 /** Config documents and their copies can contain plaintext credentials. */
 export const PRIVATE_CONFIG_FILE_MODE = 0o600;
 
-/** Tighten existing POSIX files as well as newly created ones. */
+/** Remove non-owner access without changing an owner's read-only policy. */
 export function restrictConfigFileSync(filePath: string): void {
-  if (process.platform !== "win32")
-    fs.chmodSync(filePath, PRIVATE_CONFIG_FILE_MODE);
+  if (process.platform === "win32") return;
+  const mode = fs.statSync(filePath).mode;
+  // Already-private files may live on read-only mounts or be immutable.
+  if ((mode & 0o077) === 0) return;
+  fs.chmodSync(filePath, mode & 0o700);
 }
 
 /** Restrict access before truncating or writing any secret-bearing content. */

+ 81 - 0
packages/config/test/config-file-permissions.test.ts

@@ -1,6 +1,7 @@
 import fs from "node:fs";
 import os from "node:os";
 import { join } from "node:path";
+import { spawnSync } from "node:child_process";
 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
 import {
   getConfig,
@@ -130,6 +131,51 @@ describe.skipIf(process.platform === "win32")(
       expect(fs.readFileSync(configPath, "utf8")).toBe(document);
     });
 
+    it.each([0o400, 0o600])("loads an already-private %i config without chmod", (mode) => {
+      fs.writeFileSync(configPath, document, { mode });
+      const chmod = vi.spyOn(fs, "chmodSync").mockImplementation(() => {
+        throw new Error("synthetic read-only filesystem");
+      });
+      expect(() => getConfig()).not.toThrow();
+      expect(chmod).not.toHaveBeenCalled();
+      expect(fs.statSync(configPath).mode & 0o777).toBe(mode);
+    });
+
+    it("removes non-owner access without granting owner write permission", () => {
+      fs.writeFileSync(configPath, document);
+      fs.chmodSync(configPath, 0o440);
+      getConfig();
+      expect(fs.statSync(configPath).mode & 0o777).toBe(0o400);
+    });
+
+    it("still rejects loading an unsafe main config when chmod fails", () => {
+      fs.writeFileSync(configPath, document);
+      fs.chmodSync(configPath, 0o644);
+      vi.spyOn(fs, "chmodSync").mockImplementation(() => {
+        throw new Error("synthetic chmod failure");
+      });
+      expect(() => getConfig()).toThrow("synthetic chmod failure");
+      expect(fs.readFileSync(configPath, "utf8")).toBe(document);
+    });
+
+    it.skipIf(process.platform !== "darwin")("loads immutable private config and backup files", () => {
+      const backup = join(dataDir, "config.yaml.bak.byok-legacy-provider.immutable");
+      const files = [configPath, backup];
+      try {
+        for (const file of files) {
+          fs.writeFileSync(file, document, { mode: 0o400 });
+          const result = spawnSync("chflags", ["uchg", file], { encoding: "utf8" });
+          expect(result.status, result.stderr).toBe(0);
+        }
+        const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+        expect(() => getConfig()).not.toThrow();
+        expect(warn).not.toHaveBeenCalled();
+        for (const file of files) expect(fs.statSync(file).mode & 0o777).toBe(0o400);
+      } finally {
+        for (const file of files) spawnSync("chflags", ["nouchg", file]);
+      }
+    });
+
     it("creates managed defaults privately", () => {
       vi.stubEnv("__MAVIS_RUNTIME_MANAGED", "1");
       getConfig();
@@ -157,6 +203,41 @@ describe.skipIf(process.platform === "win32")(
       expect(fs.readFileSync(backup, "utf8")).toBe(document);
     });
 
+    it("warns on backup repair failure, loads the config and repairs remaining backups", () => {
+      fs.writeFileSync(configPath, document, { mode: 0o600 });
+      const failed = join(dataDir, "config.yaml.bak.byok-legacy-provider.1");
+      const repaired = join(dataDir, "config.yaml.bak.byok-legacy-provider.2");
+      for (const backup of [failed, repaired]) {
+        fs.writeFileSync(backup, document);
+        fs.chmodSync(backup, 0o644);
+      }
+      const chmod = fs.chmodSync;
+      vi.spyOn(fs, "chmodSync").mockImplementation((file, mode) => {
+        if (file === failed) throw new Error(secret);
+        chmod(file, mode);
+      });
+      const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+      expect(() => getConfig()).not.toThrow();
+      expect(fs.statSync(failed).mode & 0o777).toBe(0o644);
+      expect(fs.statSync(repaired).mode & 0o777).toBe(0o600);
+      expect(warn).toHaveBeenCalledTimes(1);
+      expect(warn).toHaveBeenCalledWith(expect.stringContaining(JSON.stringify(failed)));
+      expect(warn).toHaveBeenCalledWith(expect.stringContaining("restrict its permissions manually"));
+      expect(JSON.stringify(warn.mock.calls)).not.toContain(secret);
+    });
+
+    it("warns when backup inspection fails without blocking the main config", () => {
+      fs.writeFileSync(configPath, document, { mode: 0o600 });
+      vi.spyOn(fs, "readdirSync").mockImplementation(() => {
+        throw new Error(secret);
+      });
+      const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+      expect(() => getConfig()).not.toThrow();
+      expect(warn).toHaveBeenCalledWith(expect.stringContaining(JSON.stringify(dataDir)));
+      expect(warn).toHaveBeenCalledWith(expect.stringContaining("Backup permissions were not verified"));
+      expect(JSON.stringify(warn.mock.calls)).not.toContain(secret);
+    });
+
     it("keeps a symlinked status-line config and its credentials private", async () => {
       const target = join(root, "linked.yaml");
       fs.writeFileSync(target, document);