Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ jobs:
./packages/core/src/test/unit/cli-config-models-help.test.ts
./packages/core/src/test/unit/cli-context-help.test.ts
./packages/core/src/test/unit/cli-mcp-help.test.ts
./packages/config/src/test/unit/settings-files.test.ts
./packages/core/src/test/unit/permission-settings-fail-closed.test.ts
./packages/core/src/test/integration/cli-settings-fail-closed.test.ts
./apps/server/src/settings-policy.test.ts

- name: Typecheck
if: ${{ !cancelled() && steps.install.outcome == 'success' && runner.os == 'Linux' }}
Expand Down
5 changes: 5 additions & 0 deletions apps/cli/src/entrypoints/cli/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { grantReadPermissionForOriginalDir } from '#core/utils/permissions/files
import { setCwd, setOriginalCwd } from '#core/utils/state'
import { debug as debugLogger } from '#core/utils/debugLogger'
import { LEGACY_ENV } from '#config/compat/legacyEnv'
import { loadToolPermissionContextFromDisk } from '#core/permissions/toolPermissionSettings'

export async function setup(cwd: string, safeMode?: boolean): Promise<void> {
process.env.KODE_PROJECT_DIR = cwd
Expand All @@ -16,6 +17,10 @@ export async function setup(cwd: string, safeMode?: boolean): Promise<void> {
}
await setCwd(cwd)

// Validate all policy sources before watchers, hooks, plugins or model calls,
// including interactive and plain-text print entrypoints.
loadToolPermissionContextFromDisk({ projectDir: cwd })

// Always grant read permissions for original working dir
grantReadPermissionForOriginalDir()

Expand Down
24 changes: 12 additions & 12 deletions apps/server/src/acp/agent/handlers/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ export async function handleSessionNew(args: {
await setCwd(cwd)
grantReadPermissionForOriginalDir()

const toolPermissionContext = loadToolPermissionContextFromDisk({
projectDir: cwd,
includeKodeProjectConfig: true,
isBypassPermissionsModeAvailable: true,
})

const mcpServers = Array.isArray(p.mcpServers)
? (p.mcpServers as Protocol.McpServer[])
: []
Expand All @@ -73,12 +79,6 @@ export async function handleSessionNew(args: {
const acpMcpClients = await connectAcpMcpServers(mcpServers)
const mcpClients = mergeMcpClients(configuredMcpClients, acpMcpClients)

const toolPermissionContext = loadToolPermissionContextFromDisk({
projectDir: cwd,
includeKodeProjectConfig: true,
isBypassPermissionsModeAvailable: true,
})

const sessionId = `sess_${nanoid()}`
const currentModeId = toolPermissionContext.mode

Expand Down Expand Up @@ -137,6 +137,12 @@ export async function handleSessionLoad(args: {
throw new JsonRpcError(-32602, `Session not found: ${sessionId}`)
}

const toolPermissionContext = loadToolPermissionContextFromDisk({
projectDir: cwd,
includeKodeProjectConfig: true,
isBypassPermissionsModeAvailable: true,
})

const mcpServers = Array.isArray(p.mcpServers)
? (p.mcpServers as Protocol.McpServer[])
: []
Expand All @@ -147,12 +153,6 @@ export async function handleSessionLoad(args: {
const acpMcpClients = await connectAcpMcpServers(mcpServers)
const mcpClients = mergeMcpClients(configuredMcpClients, acpMcpClients)

const toolPermissionContext = loadToolPermissionContextFromDisk({
projectDir: cwd,
includeKodeProjectConfig: true,
isBypassPermissionsModeAvailable: true,
})

const currentModeId = coercePermissionMode(
typeof persisted.currentModeId === 'string' && persisted.currentModeId
? persisted.currentModeId
Expand Down
19 changes: 14 additions & 5 deletions apps/server/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { basename, resolve } from 'node:path'

import { loadToolPermissionContextFromDisk } from '@kode/core/utils/permissions/toolPermissionSettings'
import type { Tool } from '@kode/core/tooling/Tool'
import { SettingsFileError } from '@kode/config'

import { maybeServeWebui } from '../server/webui'
import { routeChat } from './chat'
Expand Down Expand Up @@ -111,6 +112,18 @@ export function createRoutes(args: {
const selectedCwd =
workspaces.find(w => w.id === selected)?.path ?? resolve(args.cwd)

let toolPermissionContext
try {
toolPermissionContext = loadToolPermissionContextFromDisk({
projectDir: selectedCwd,
includeKodeProjectConfig: true,
isBypassPermissionsModeAvailable: true,
})
} catch (error) {
if (!(error instanceof SettingsFileError)) throw error
return Response.json({ error: error.message }, { status: 500 })
}

const sessionId = crypto.randomUUID()
const session: DaemonSession = {
sessionId,
Expand All @@ -119,11 +132,7 @@ export function createRoutes(args: {
messages: [],
readFileTimestamps: {},
responseState: {},
toolPermissionContext: loadToolPermissionContextFromDisk({
projectDir: selectedCwd,
includeKodeProjectConfig: true,
isBypassPermissionsModeAvailable: true,
}),
toolPermissionContext,
activeAbortController: null,
inflightPermissionRequests: new Map(),
}
Expand Down
176 changes: 176 additions & 0 deletions apps/server/src/settings-policy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { SettingsFileError } from '@kode/config'
import { createDefaultToolPermissionContext } from '@kode/core/types/toolPermissionContext'
import {
getCwd,
getOriginalCwd,
setCwd,
setOriginalCwd,
} from '@kode/core/utils/state'
import { createRoutes } from './routes'
import { createWebSocketHandlers } from './ws/connection'
import type { DaemonSession } from './ws/types'
import {
handleSessionLoad,
handleSessionNew,
} from './acp/agent/handlers/sessions'
import { persistAcpSessionToDisk } from './acp/agent/sessionStore'
import type { SessionState } from './acp/agent/types'
import type { JsonRpcPeer } from './acp/jsonrpc'

describe('server policy initialization failures', () => {
const originalConfigDir = process.env.KODE_CONFIG_DIR
const originalCwd = getCwd()
const originalWorkingDir = getOriginalCwd()
let root: string
let policyPath: string

beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'kode-server-policy-'))
mkdirSync(join(root, '.kode'))
mkdirSync(join(root, 'config'))
process.env.KODE_CONFIG_DIR = join(root, 'config')
writeFileSync(join(root, 'config', 'settings.json'), '{}')
policyPath = join(root, '.kode', 'settings.json')
writeFileSync(policyPath, '{"permissions":')
})

afterEach(async () => {
await setCwd(originalCwd)
setOriginalCwd(originalWorkingDir)
if (originalConfigDir === undefined) delete process.env.KODE_CONFIG_DIR
else process.env.KODE_CONFIG_DIR = originalConfigDir
rmSync(root, { recursive: true, force: true })
})

test('WebSocket upgrade reports a policy error and creates no session; repair allows a new session', async () => {
const sessions = new Map<string, DaemonSession>()
let upgraded = false
const routes = createRoutes({
webuiRoot: null,
checkToken: () => true,
listWorkspaces: async () => ({
currentId: root,
workspaces: [
{
id: root,
path: root,
title: 'fixture',
branch: null,
isCurrent: true,
},
],
}),
sessions,
cwd: root,
echo: true,
commands: [],
tools: [],
toolNames: [],
slashCommands: [],
})
const server = {
upgrade: () => {
upgraded = true
return true
},
}
const response = await routes.fetch(
new Request('http://localhost/ws'),
server,
)
expect(response?.status).toBe(500)
expect(await response?.text()).toContain('Cannot load settings')
expect(upgraded).toBe(false)
expect(sessions.size).toBe(0)

writeFileSync(policyPath, '{"permissions":{"deny":["Write(.env)"]}}')
expect(
await routes.fetch(new Request('http://localhost/ws'), server),
).toBeUndefined()
expect(upgraded).toBe(true)
expect(
[...sessions.values()][0]?.toolPermissionContext.alwaysDenyRules
.projectSettings,
).toEqual(['Write(.env)'])
})

test('failed new-session closes the socket and cannot reuse its old policy through queued frames', async () => {
const controller = new AbortController()
const session: DaemonSession = {
sessionId: 'old-session',
cwd: root,
ws: null,
messages: [],
readFileTimestamps: {},
responseState: {},
toolPermissionContext: createDefaultToolPermissionContext(),
activeAbortController: controller,
inflightPermissionRequests: new Map(),
}
const sessions = new Map([[session.sessionId, session]])
const messages: string[] = []
let closeCode = 0
const ws = {
data: { session },
send: (message: string) => messages.push(message),
close: (code: number) => {
closeCode = code
},
} as unknown as Parameters<
ReturnType<typeof createWebSocketHandlers>['message']
>[0]
const handlers = createWebSocketHandlers({
sessions,
tools: [],
commands: [],
toolNames: [],
slashCommands: [],
echo: true,
})
await handlers.message(ws, Buffer.from('{"type":"new_session"}'))
expect(controller.signal.aborted).toBe(true)
expect(sessions.size).toBe(0)
expect(closeCode).toBe(1011)
expect(messages.join('\n')).toContain('Cannot load settings')
writeFileSync(policyPath, '{}')
await handlers.message(ws, Buffer.from('{"type":"new_session"}'))
expect(sessions.size).toBe(0)
})

test('ACP session/new and session/load reject before connecting dependencies or registering a session', async () => {
const sessions = new Map<string, SessionState>()
// No peer operations should occur until policy initialization succeeds.
const peer = {} as JsonRpcPeer
await expect(
handleSessionNew({
peer,
sessions,
params: { cwd: root, mcpServers: [] },
}),
).rejects.toBeInstanceOf(SettingsFileError)
expect(sessions.size).toBe(0)

persistAcpSessionToDisk({
sessionId: 'saved-session',
cwd: root,
mcpServers: [],
messages: [],
toolPermissionContext: createDefaultToolPermissionContext(),
readFileTimestamps: {},
responseState: {},
currentModeId: 'yolo',
} as unknown as SessionState)
await expect(
handleSessionLoad({
peer,
sessions,
params: { cwd: root, sessionId: 'saved-session', mcpServers: [] },
}),
).rejects.toBeInstanceOf(SettingsFileError)
expect(sessions.size).toBe(0)
})
})
22 changes: 17 additions & 5 deletions apps/server/src/ws/connection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { RawData, WebSocket } from 'ws'
import { spawnSync } from 'node:child_process'
import { readFileSync, writeFileSync } from 'node:fs'
import { SettingsFileError } from '@kode/config'

import {
makeSdkInitMessage,
Expand Down Expand Up @@ -188,6 +189,8 @@ export function createWebSocketHandlers(args: {

async message(ws: WsWithSession, message: RawData) {
const session = ws.data.session
// Ignore queued frames after a failed initialization or a closed session.
if (args.sessions.get(session.sessionId) !== session) return
const parsed = parseClientWsMessage(message)
if (parsed.ok === false) {
sendJson(ws, log('error', parsed.error))
Expand Down Expand Up @@ -257,11 +260,20 @@ export function createWebSocketHandlers(args: {
session.responseState = {}
session.activeAbortController = null

session.toolPermissionContext = loadToolPermissionContextFromDisk({
projectDir: session.cwd,
includeKodeProjectConfig: true,
isBypassPermissionsModeAvailable: true,
})
try {
session.toolPermissionContext = loadToolPermissionContextFromDisk({
projectDir: session.cwd,
includeKodeProjectConfig: true,
isBypassPermissionsModeAvailable: true,
})
} catch (error) {
if (!(error instanceof SettingsFileError)) throw error
sendJson(ws, log('error', error.message))
// Do not leave a failed new-session request using the old policy.
args.sessions.delete(session.sessionId)
ws.close(1011, 'Cannot load permission settings')
return
}

const nextId = crypto.randomUUID()
args.sessions.delete(session.sessionId)
Expand Down
14 changes: 14 additions & 0 deletions docs/develop/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@ Legacy compatibility:

Example: output style selection is stored in `settings.local.json` under `outputStyle`.

### Settings load failures

Missing settings files are optional. Existing files must be readable JSON objects;
`permissions`, when present, must be an object, and `allow`, `deny`, `ask`, and
`additionalDirectories` must be arrays of strings when present. Other keys are
preserved for compatibility.

An unreadable, truncated, or invalid settings file stops permission initialization.
The error identifies the file without printing its contents. CLI startup exits
nonzero, including text, JSON, and stream-JSON print modes; server session creation
fails. Repair the reported file or restore its intended policy and retry. A broken
primary file never falls back to an older `.claude` policy. Legacy fallback and
migration remain available when the primary file is absent.

## Models

### Model profiles + pointers (stored in global config)
Expand Down
14 changes: 14 additions & 0 deletions packages/config/src/errors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
// Do not retain the original error: JSON parser messages can contain settings
// values (including credentials). Hosts can safely display this diagnostic.
export class SettingsFileError extends Error {
constructor(
readonly filePath: string,
reason: string,
) {
super(
`Cannot load settings from ${JSON.stringify(filePath)}: ${reason}. Fix the settings file before continuing.`,
)
this.name = 'SettingsFileError'
}
}

export class ConfigParseError extends Error {
filePath: string
defaultConfig: unknown
Expand Down
Loading
Loading