Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -1,77 +0,0 @@
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
getRuntimeMetadataPath,
|
||||
MAX_RUNTIME_METADATA_FILE_BYTES
|
||||
} from '../../shared/runtime-bootstrap'
|
||||
import {
|
||||
getServeUpdateHandoffPath,
|
||||
MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES
|
||||
} from '../../shared/serve-update-handoff'
|
||||
import { readMetadata, tryReadMetadata } from './metadata'
|
||||
import {
|
||||
readServeUpdateHandoff,
|
||||
readServeUpdateHandoffSync,
|
||||
recordServeUpdateHandoffFailure
|
||||
} from './serve-update-supervisor'
|
||||
import { RuntimeClientError } from './types'
|
||||
|
||||
describe('CLI runtime control-file bounds', () => {
|
||||
const paths: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const path of paths.splice(0)) {
|
||||
rmSync(path, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
function makeRoot(): string {
|
||||
const path = mkdtempSync(join(tmpdir(), 'orca-cli-control-file-bound-'))
|
||||
paths.push(path)
|
||||
return path
|
||||
}
|
||||
|
||||
it('reports oversized runtime metadata as unavailable', () => {
|
||||
const root = makeRoot()
|
||||
const metadataPath = getRuntimeMetadataPath(root)
|
||||
writeFileSync(metadataPath, '{"runtimeId":"runtime-1"}')
|
||||
truncateSync(metadataPath, MAX_RUNTIME_METADATA_FILE_BYTES + 1)
|
||||
|
||||
expect(tryReadMetadata(root)).toBeNull()
|
||||
expect(() => readMetadata(root)).toThrow(RuntimeClientError)
|
||||
})
|
||||
|
||||
it('ignores oversized serve-update handoff state in sync and async readers', async () => {
|
||||
const handoffPath = getServeUpdateHandoffPath(makeRoot())
|
||||
writeFileSync(handoffPath, '{"schemaVersion":1}')
|
||||
truncateSync(handoffPath, MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES + 1)
|
||||
|
||||
expect(readServeUpdateHandoffSync(handoffPath)).toBeNull()
|
||||
await expect(readServeUpdateHandoff(handoffPath)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('preserves the prior handoff when bounded transactional serialization fails', async () => {
|
||||
const handoffPath = getServeUpdateHandoffPath(makeRoot())
|
||||
const initial = {
|
||||
schemaVersion: 1 as const,
|
||||
phase: 'install-requested' as const,
|
||||
fromVersion: '1.0.0',
|
||||
targetVersion: '1.0.1',
|
||||
servingPid: process.pid
|
||||
}
|
||||
writeFileSync(handoffPath, JSON.stringify(initial))
|
||||
|
||||
await expect(
|
||||
recordServeUpdateHandoffFailure(
|
||||
handoffPath,
|
||||
initial,
|
||||
'x'.repeat(MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES + 1)
|
||||
)
|
||||
).rejects.toThrow(`JSON output exceeds ${MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES} bytes`)
|
||||
|
||||
expect(JSON.parse(readFileSync(handoffPath, 'utf8'))).toEqual(initial)
|
||||
expect(existsSync(`${handoffPath}.${process.pid}.tmp`)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -519,33 +519,6 @@ describe('serveOrcaApp', () => {
|
||||
expect(child.unref).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('preserves recipe JSON after 100,000 one-byte fragments', async () => {
|
||||
const { child, result, stdoutSpy } = startRecipeJsonServer()
|
||||
const output = Buffer.from(`${' '.repeat(100_000)}${RECIPE_JSON}\n`)
|
||||
queueMicrotask(() => {
|
||||
for (let index = 0; index < output.byteLength; index += 1) {
|
||||
child.stdout.emit('data', output.subarray(index, index + 1))
|
||||
}
|
||||
})
|
||||
|
||||
await expect(result).resolves.toBe(0)
|
||||
expect(stdoutSpy).toHaveBeenCalledWith(`${RECIPE_JSON}\n`)
|
||||
})
|
||||
|
||||
it('kills a server that emits an oversized recipe line without a newline', async () => {
|
||||
const { child, result } = startRecipeJsonServer()
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', Buffer.alloc(4 * 1024 * 1024 + 1, 0x78))
|
||||
})
|
||||
|
||||
await expect(result).rejects.toMatchObject({
|
||||
code: 'runtime_serve_failed',
|
||||
message: 'Recipe JSON output exceeded 4194304 byte line limit.'
|
||||
})
|
||||
expect(child.kill).toHaveBeenCalledWith('SIGTERM')
|
||||
expect(child.stdout.listenerCount('data')).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects when the server exits without valid recipe JSON', async () => {
|
||||
const { child, result, stdoutSpy, stderrSpy } = startRecipeJsonServer()
|
||||
const secrets = ['UPPER-SECRET', 'SLASH-SECRET', 'LEGACY-SECRET', 'PRIVATE-SECRET']
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { spawn as spawnProcess, type SpawnOptions } from 'node:child_process'
|
||||
import { resolve } from 'node:path'
|
||||
import { StringDecoder } from 'node:string_decoder'
|
||||
import {
|
||||
SERVE_UPDATE_HANDOFF_PATH_ENV,
|
||||
getServeUpdateHandoffPath
|
||||
} from '../../shared/serve-update-handoff'
|
||||
import {
|
||||
getEphemeralVmRecipeResultConnection,
|
||||
parseEphemeralVmRecipeResult
|
||||
} from '../../shared/ephemeral-vm-recipes'
|
||||
import { getDefaultUserDataPath } from './metadata'
|
||||
import { getMacAppBundlePath } from './mac-app-update-bundle'
|
||||
import { waitForRecipeJson } from './recipe-json-output'
|
||||
import {
|
||||
readServeUpdateHandoffSync,
|
||||
resumeInterruptedServeUpdate,
|
||||
@@ -14,6 +18,8 @@ import {
|
||||
} from './serve-update-supervisor'
|
||||
import { RuntimeClientError } from './types'
|
||||
|
||||
const IGNORED_NON_RECIPE_STDOUT = '[serve] ignored non-recipe stdout'
|
||||
|
||||
export function launchOrcaApp(): void {
|
||||
const overrideCommand = process.env.ORCA_OPEN_COMMAND
|
||||
if (typeof overrideCommand === 'string' && overrideCommand.trim().length > 0) {
|
||||
@@ -159,6 +165,97 @@ export function serveOrcaApp(
|
||||
})
|
||||
}
|
||||
|
||||
function waitForRecipeJson(child: ReturnType<typeof spawnProcess>): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let output = ''
|
||||
let settled = false
|
||||
const timeout = setTimeout(() => {
|
||||
finish(new RuntimeClientError('runtime_serve_failed', 'Timed out waiting for recipe JSON.'))
|
||||
child.kill('SIGTERM')
|
||||
}, 60000)
|
||||
const finish = (error?: Error): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
child.stdout?.off('data', onData)
|
||||
child.off('error', onError)
|
||||
child.off('close', onClose)
|
||||
if (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
child.stdout?.destroy?.()
|
||||
child.unref()
|
||||
resolve(0)
|
||||
}
|
||||
const writeIgnoredRecipeStdout = (): void => {
|
||||
// Why: non-readiness child stdout is untrusted and cannot be safely
|
||||
// redacted, including schema-valid results with arbitrary user data.
|
||||
process.stderr.write(`${IGNORED_NON_RECIPE_STDOUT}\n`)
|
||||
}
|
||||
const processRecipeOutputLine = (line: string): void => {
|
||||
const normalizedLine = line.endsWith('\r') ? line.slice(0, -1) : line
|
||||
if (!normalizedLine.trim()) {
|
||||
return
|
||||
}
|
||||
const parsed = parseEphemeralVmRecipeResult(normalizedLine)
|
||||
if (!parsed.ok) {
|
||||
writeIgnoredRecipeStdout()
|
||||
return
|
||||
}
|
||||
if (getEphemeralVmRecipeResultConnection(parsed.result).type !== 'orca-server') {
|
||||
writeIgnoredRecipeStdout()
|
||||
return
|
||||
}
|
||||
process.stdout.write(`${normalizedLine.trim()}\n`)
|
||||
finish()
|
||||
}
|
||||
const stdoutDecoder = new StringDecoder('utf8')
|
||||
const onData = (chunk: Buffer | string): void => {
|
||||
output += typeof chunk === 'string' ? chunk : stdoutDecoder.write(chunk)
|
||||
while (!settled) {
|
||||
const newlineIndex = output.indexOf('\n')
|
||||
if (newlineIndex === -1) {
|
||||
return
|
||||
}
|
||||
const line = output.slice(0, newlineIndex)
|
||||
output = output.slice(newlineIndex + 1)
|
||||
processRecipeOutputLine(line)
|
||||
}
|
||||
}
|
||||
const onError = (error: Error): void => {
|
||||
finish(error)
|
||||
}
|
||||
const onClose = (code: number | null, signal: NodeJS.Signals | null): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
output += stdoutDecoder.end()
|
||||
if (output.trim()) {
|
||||
processRecipeOutputLine(output)
|
||||
}
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
finish(
|
||||
new RuntimeClientError(
|
||||
'runtime_serve_failed',
|
||||
typeof code === 'number'
|
||||
? `Orca serve exited before printing valid recipe JSON with code ${code}.`
|
||||
: `Orca serve exited before printing valid recipe JSON via ${signal}.`
|
||||
)
|
||||
)
|
||||
}
|
||||
child.stdout?.on('data', onData)
|
||||
child.once('error', onError)
|
||||
// Why: `exit` can precede the final piped stdout data. `close` waits until
|
||||
// stdio closes so a last recipe chunk is not mistaken for missing output.
|
||||
child.once('close', onClose)
|
||||
})
|
||||
}
|
||||
|
||||
function getExecutableAppArgs(): string[] {
|
||||
return process.env.ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT === '1' ? [resolveAppRoot()] : []
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { MAC_BUNDLE_INFO_PLIST_MAX_BYTES, waitForMacBundleVersion } from './mac-app-update-bundle'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
|
||||
for (const root of roots.splice(0)) {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
const originalPlatform = process.platform
|
||||
|
||||
describe('waitForMacBundleVersion', () => {
|
||||
it('rejects a sparse oversized Info.plist without reading its payload', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' })
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-mac-bundle-bounds-'))
|
||||
roots.push(root)
|
||||
const contentsPath = join(root, 'Orca.app', 'Contents')
|
||||
const executable = join(contentsPath, 'MacOS', 'Orca')
|
||||
mkdirSync(join(contentsPath, 'MacOS'), { recursive: true })
|
||||
writeFileSync(executable, '')
|
||||
const plistPath = join(contentsPath, 'Info.plist')
|
||||
writeFileSync(plistPath, '')
|
||||
truncateSync(plistPath, MAC_BUNDLE_INFO_PLIST_MAX_BYTES + 1)
|
||||
|
||||
await expect(waitForMacBundleVersion(executable, '1.2.3', 1)).resolves.toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,8 @@
|
||||
import { watch, type FSWatcher } from 'node:fs'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader'
|
||||
|
||||
const MAC_BUNDLE_UPDATE_TIMEOUT_MS = 120_000
|
||||
export const MAC_BUNDLE_INFO_PLIST_MAX_BYTES = 1024 * 1024
|
||||
|
||||
export function getMacAppBundlePath(executable: string): string | null {
|
||||
if (process.platform !== 'darwin') {
|
||||
@@ -79,9 +78,7 @@ export async function waitForMacBundleVersion(
|
||||
|
||||
async function readMacBundleVersion(infoPlistPath: string): Promise<string | null> {
|
||||
try {
|
||||
const plist = (
|
||||
await readNodeFileWithinLimit(infoPlistPath, MAC_BUNDLE_INFO_PLIST_MAX_BYTES)
|
||||
).buffer.toString('utf8')
|
||||
const plist = await readFile(infoPlistPath, 'utf8')
|
||||
const match = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(plist)
|
||||
return match?.[1]?.trim() || null
|
||||
} catch {
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import {
|
||||
findTransport,
|
||||
getRuntimeMetadataPath,
|
||||
MAX_RUNTIME_METADATA_FILE_BYTES,
|
||||
parseRuntimeMetadataJson,
|
||||
type RuntimeMetadata
|
||||
} from '../../shared/runtime-bootstrap'
|
||||
import { RuntimeClientError } from './types'
|
||||
@@ -13,11 +11,7 @@ import { RuntimeClientError } from './types'
|
||||
export function readMetadata(userDataPath: string): RuntimeMetadata {
|
||||
const metadataPath = getRuntimeMetadataPath(userDataPath)
|
||||
try {
|
||||
const metadata = parseRuntimeMetadataJson(
|
||||
readNodeFileSyncWithinLimit(metadataPath, MAX_RUNTIME_METADATA_FILE_BYTES).buffer.toString(
|
||||
'utf8'
|
||||
)
|
||||
)
|
||||
const metadata = JSON.parse(readFileSync(metadataPath, 'utf8')) as RuntimeMetadata | null
|
||||
if (!metadata || !findTransport(metadata, 'unix', 'named-pipe') || !metadata.authToken) {
|
||||
throw new RuntimeClientError(
|
||||
'runtime_unavailable',
|
||||
@@ -39,11 +33,7 @@ export function readMetadata(userDataPath: string): RuntimeMetadata {
|
||||
export function tryReadMetadata(userDataPath: string): RuntimeMetadata | null {
|
||||
const metadataPath = getRuntimeMetadataPath(userDataPath)
|
||||
try {
|
||||
return parseRuntimeMetadataJson(
|
||||
readNodeFileSyncWithinLimit(metadataPath, MAX_RUNTIME_METADATA_FILE_BYTES).buffer.toString(
|
||||
'utf8'
|
||||
)
|
||||
)
|
||||
return JSON.parse(readFileSync(metadataPath, 'utf8')) as RuntimeMetadata | null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
import type { ChildProcess } from 'node:child_process'
|
||||
import {
|
||||
getEphemeralVmRecipeResultConnection,
|
||||
parseEphemeralVmRecipeResult
|
||||
} from '../../shared/ephemeral-vm-recipes'
|
||||
import { GrowingByteBuffer } from '../../shared/growing-byte-buffer'
|
||||
import { RuntimeClientError } from './types'
|
||||
|
||||
const IGNORED_NON_RECIPE_STDOUT = '[serve] ignored non-recipe stdout'
|
||||
const MAX_RECIPE_OUTPUT_LINE_BYTES = 4 * 1024 * 1024
|
||||
|
||||
export function waitForRecipeJson(child: ChildProcess): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const output = new GrowingByteBuffer()
|
||||
let settled = false
|
||||
const timeout = setTimeout(() => {
|
||||
finish(new RuntimeClientError('runtime_serve_failed', 'Timed out waiting for recipe JSON.'))
|
||||
child.kill('SIGTERM')
|
||||
}, 60000)
|
||||
const finish = (error?: Error): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
output.clear()
|
||||
child.stdout?.off('data', onData)
|
||||
child.off('error', onError)
|
||||
child.off('close', onClose)
|
||||
if (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
child.stdout?.destroy?.()
|
||||
child.unref()
|
||||
resolve(0)
|
||||
}
|
||||
const writeIgnoredRecipeStdout = (): void => {
|
||||
// Why: non-readiness child stdout can contain arbitrary user data.
|
||||
process.stderr.write(`${IGNORED_NON_RECIPE_STDOUT}\n`)
|
||||
}
|
||||
const processRecipeOutputLine = (line: string): void => {
|
||||
const normalizedLine = line.endsWith('\r') ? line.slice(0, -1) : line
|
||||
if (!normalizedLine.trim()) {
|
||||
return
|
||||
}
|
||||
const parsed = parseEphemeralVmRecipeResult(normalizedLine)
|
||||
if (!parsed.ok) {
|
||||
writeIgnoredRecipeStdout()
|
||||
return
|
||||
}
|
||||
if (getEphemeralVmRecipeResultConnection(parsed.result).type !== 'orca-server') {
|
||||
writeIgnoredRecipeStdout()
|
||||
return
|
||||
}
|
||||
process.stdout.write(`${normalizedLine.trim()}\n`)
|
||||
finish()
|
||||
}
|
||||
const oversizedLineError = (): RuntimeClientError =>
|
||||
new RuntimeClientError(
|
||||
'runtime_serve_failed',
|
||||
`Recipe JSON output exceeded ${MAX_RECIPE_OUTPUT_LINE_BYTES} byte line limit.`
|
||||
)
|
||||
const onData = (chunk: Buffer | string): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
output.append(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
|
||||
while (!settled) {
|
||||
const newlineIndex = output.indexOfByte(0x0a)
|
||||
if (newlineIndex === -1) {
|
||||
break
|
||||
}
|
||||
if (newlineIndex > MAX_RECIPE_OUTPUT_LINE_BYTES) {
|
||||
finish(oversizedLineError())
|
||||
child.kill('SIGTERM')
|
||||
return
|
||||
}
|
||||
const line = output.takePrefixString(newlineIndex)
|
||||
output.discardPrefix(1)
|
||||
processRecipeOutputLine(line)
|
||||
}
|
||||
if (!settled && output.byteLength > MAX_RECIPE_OUTPUT_LINE_BYTES) {
|
||||
finish(oversizedLineError())
|
||||
child.kill('SIGTERM')
|
||||
}
|
||||
}
|
||||
const onError = (error: Error): void => {
|
||||
finish(error)
|
||||
}
|
||||
const onClose = (code: number | null, signal: NodeJS.Signals | null): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
if (output.byteLength > MAX_RECIPE_OUTPUT_LINE_BYTES) {
|
||||
finish(oversizedLineError())
|
||||
return
|
||||
}
|
||||
const finalOutput = output.takeString()
|
||||
if (finalOutput.trim()) {
|
||||
processRecipeOutputLine(finalOutput)
|
||||
}
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
finish(
|
||||
new RuntimeClientError(
|
||||
'runtime_serve_failed',
|
||||
typeof code === 'number'
|
||||
? `Orca serve exited before printing valid recipe JSON with code ${code}.`
|
||||
: `Orca serve exited before printing valid recipe JSON via ${signal}.`
|
||||
)
|
||||
)
|
||||
}
|
||||
child.stdout?.on('data', onData)
|
||||
child.once('error', onError)
|
||||
// Why: `close` waits for final piped stdout data that can arrive after `exit`.
|
||||
child.once('close', onClose)
|
||||
})
|
||||
}
|
||||
@@ -1,14 +1,9 @@
|
||||
import type { ChildProcess, SpawnOptions, spawn } from 'node:child_process'
|
||||
import { rename, unlink, writeFile } from 'node:fs/promises'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
||||
import {
|
||||
readNodeFileSyncWithinLimit,
|
||||
readNodeFileWithinLimit
|
||||
} from '../../shared/node-bounded-file-reader'
|
||||
import { stringifyJsonWithinByteLimit } from '../../shared/node-bounded-json-stringify'
|
||||
import {
|
||||
MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES,
|
||||
parseServeUpdateHandoffJson,
|
||||
parseServeSupervisorMessage,
|
||||
parseServeUpdateHandoffState,
|
||||
type ServeUpdateHandoffState
|
||||
} from '../../shared/serve-update-handoff'
|
||||
import { RuntimeClientError } from './types'
|
||||
@@ -218,11 +213,7 @@ export async function readServeUpdateHandoff(
|
||||
handoffPath: string
|
||||
): Promise<ServeUpdateHandoffState | null> {
|
||||
try {
|
||||
const { buffer } = await readNodeFileWithinLimit(
|
||||
handoffPath,
|
||||
MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES
|
||||
)
|
||||
return parseServeUpdateHandoffJson(buffer.toString('utf8'))
|
||||
return parseServeUpdateHandoffState(JSON.parse(await readFile(handoffPath, 'utf8')))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -230,8 +221,7 @@ export async function readServeUpdateHandoff(
|
||||
|
||||
export function readServeUpdateHandoffSync(handoffPath: string): ServeUpdateHandoffState | null {
|
||||
try {
|
||||
const { buffer } = readNodeFileSyncWithinLimit(handoffPath, MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES)
|
||||
return parseServeUpdateHandoffJson(buffer.toString('utf8'))
|
||||
return parseServeUpdateHandoffState(JSON.parse(readFileSync(handoffPath, 'utf8')))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -269,12 +259,6 @@ async function writeServeUpdateHandoffState(
|
||||
state: ServeUpdateHandoffState
|
||||
): Promise<void> {
|
||||
const temporaryPath = `${handoffPath}.${process.pid}.tmp`
|
||||
try {
|
||||
const { serialized } = stringifyJsonWithinByteLimit(state, MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES)
|
||||
await writeFile(temporaryPath, serialized, { mode: 0o600 })
|
||||
await rename(temporaryPath, handoffPath)
|
||||
} catch (error) {
|
||||
await unlink(temporaryPath).catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
await writeFile(temporaryPath, JSON.stringify(state), { mode: 0o600 })
|
||||
await rename(temporaryPath, handoffPath)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { createServer, type Socket } from 'node:net'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { RuntimeMetadata } from '../../shared/runtime-bootstrap'
|
||||
import { CLI_RUNTIME_JSON_STRUCTURE_LIMITS, sendRequest } from './transport'
|
||||
import { sendRequest } from './transport'
|
||||
|
||||
const servers = new Set<ReturnType<typeof createServer>>()
|
||||
const sockets = new Set<Socket>()
|
||||
@@ -114,36 +114,4 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => {
|
||||
})
|
||||
expect(Date.now() - start).toBeLessThan(5000)
|
||||
})
|
||||
|
||||
it('rejects excessive response nesting before JSON.parse', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-'))
|
||||
const endpoint = join(userDataPath, 'runtime.sock')
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket)
|
||||
socket.once('close', () => sockets.delete(socket))
|
||||
socket.once('data', () => {
|
||||
const depth = CLI_RUNTIME_JSON_STRUCTURE_LIMITS.nestingDepth + 1
|
||||
socket.write(`${'['.repeat(depth)}0${']'.repeat(depth)}\n`)
|
||||
})
|
||||
})
|
||||
servers.add(server)
|
||||
await new Promise<void>((resolve) => server.listen(endpoint, resolve))
|
||||
const parseSpy = vi.spyOn(JSON, 'parse')
|
||||
const metadata: RuntimeMetadata = {
|
||||
runtimeId: 'runtime-1',
|
||||
pid: 123,
|
||||
transports: [{ kind: 'unix', endpoint }],
|
||||
authToken: 'token',
|
||||
startedAt: 1
|
||||
}
|
||||
|
||||
try {
|
||||
await expect(sendRequest(metadata, 'status.get', undefined, 1000)).rejects.toMatchObject({
|
||||
code: 'invalid_runtime_response'
|
||||
})
|
||||
expect(parseSpy).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
parseSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import { createConnection } from 'node:net'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { GrowingByteBuffer } from '../../shared/growing-byte-buffer'
|
||||
import { assertJsonTextStructureWithinLimits } from '../../shared/json-text-structure-limit'
|
||||
import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootstrap'
|
||||
import { isKeepaliveFrame, RuntimeRpcEnvelopeSchema } from './envelope-schema'
|
||||
import { RuntimeClientError, type RuntimeRpcResponse } from './types'
|
||||
|
||||
const MAX_RUNTIME_RESPONSE_LINE_BYTES = 64 * 1024 * 1024
|
||||
export const CLI_RUNTIME_JSON_STRUCTURE_LIMITS = {
|
||||
structuralTokens: 1_000_000,
|
||||
nestingDepth: 128
|
||||
} as const
|
||||
|
||||
export async function sendRequest<TResult>(
|
||||
metadata: RuntimeMetadata,
|
||||
method: string,
|
||||
@@ -30,7 +22,7 @@ export async function sendRequest<TResult>(
|
||||
return
|
||||
}
|
||||
const socket = createConnection(transport.endpoint)
|
||||
const buffer = new GrowingByteBuffer()
|
||||
let buffer = ''
|
||||
let settled = false
|
||||
const requestId = randomUUID()
|
||||
|
||||
@@ -56,16 +48,15 @@ export async function sendRequest<TResult>(
|
||||
}
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
buffer.clear()
|
||||
socket.end()
|
||||
if (result.ok === false) {
|
||||
socket.destroy()
|
||||
reject(result.error)
|
||||
} else {
|
||||
socket.end()
|
||||
resolve(result.response)
|
||||
}
|
||||
}
|
||||
|
||||
socket.setEncoding('utf8')
|
||||
socket.once('error', () => {
|
||||
finish({
|
||||
ok: false,
|
||||
@@ -88,39 +79,24 @@ export async function sendRequest<TResult>(
|
||||
)
|
||||
})
|
||||
})
|
||||
socket.on('data', (chunk: Buffer) => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
buffer.append(chunk)
|
||||
socket.on('data', (chunk) => {
|
||||
buffer += chunk
|
||||
// Why: the server may interleave `{"_keepalive":true}\n` frames with the
|
||||
// final success/failure frame to keep both idle timers alive during a
|
||||
// long-poll (see design doc §3.1). Read frames in a loop until we see a
|
||||
// terminal frame. Each keepalive refreshes the client-side timer so a
|
||||
// 10 min wait doesn't trip the 60 s default ceiling.
|
||||
let newlineIndex = buffer.indexOfByte(0x0a)
|
||||
let newlineIndex = buffer.indexOf('\n')
|
||||
while (newlineIndex !== -1 && !settled) {
|
||||
const lineBytes = newlineIndex
|
||||
if (lineBytes > MAX_RUNTIME_RESPONSE_LINE_BYTES) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
`The Orca runtime response exceeded the ${MAX_RUNTIME_RESPONSE_LINE_BYTES} byte frame limit.`
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
const line = buffer.takePrefixString(lineBytes)
|
||||
buffer.discardPrefix(1)
|
||||
const line = buffer.slice(0, newlineIndex)
|
||||
buffer = buffer.slice(newlineIndex + 1)
|
||||
if (line.trim().length === 0) {
|
||||
newlineIndex = buffer.indexOfByte(0x0a)
|
||||
newlineIndex = buffer.indexOf('\n')
|
||||
continue
|
||||
}
|
||||
|
||||
let raw: unknown
|
||||
try {
|
||||
assertJsonTextStructureWithinLimits(line, CLI_RUNTIME_JSON_STRUCTURE_LIMITS)
|
||||
raw = JSON.parse(line)
|
||||
} catch {
|
||||
finish({
|
||||
@@ -139,7 +115,7 @@ export async function sendRequest<TResult>(
|
||||
// major). See §7 risk #9.
|
||||
if (isKeepaliveFrame(raw)) {
|
||||
timeout.refresh()
|
||||
newlineIndex = buffer.indexOfByte(0x0a)
|
||||
newlineIndex = buffer.indexOf('\n')
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -165,7 +141,7 @@ export async function sendRequest<TResult>(
|
||||
const frame = parsed.data
|
||||
if ('_keepalive' in frame) {
|
||||
timeout.refresh()
|
||||
newlineIndex = buffer.indexOfByte(0x0a)
|
||||
newlineIndex = buffer.indexOf('\n')
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -193,15 +169,6 @@ export async function sendRequest<TResult>(
|
||||
finish({ ok: true, response })
|
||||
return
|
||||
}
|
||||
if (buffer.byteLength > MAX_RUNTIME_RESPONSE_LINE_BYTES) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
`The Orca runtime response exceeded the ${MAX_RUNTIME_RESPONSE_LINE_BYTES} byte frame limit.`
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
socket.on('connect', () => {
|
||||
socket.write(
|
||||
|
||||
Reference in New Issue
Block a user