fix: harden shared platform helpers (#3877)
This commit is contained in:
@@ -6,6 +6,7 @@ describe('parseKey', () => {
|
||||
['a', { key: 'a', modifiers: [] }],
|
||||
['7', { key: '7', modifiers: [] }],
|
||||
[';', { key: ';', modifiers: [] }],
|
||||
['+', { key: '+', modifiers: [] }],
|
||||
['Return', { key: 'Enter', modifiers: [] }],
|
||||
['Escape', { key: 'Escape', modifiers: [] }],
|
||||
['BackSpace', { key: 'Backspace', modifiers: [] }],
|
||||
@@ -42,6 +43,8 @@ describe('parseKey', () => {
|
||||
['cmd+a', { key: 'a', modifiers: ['Meta'] }],
|
||||
['command+a', { key: 'a', modifiers: ['Meta'] }],
|
||||
['CmdOrCtrl+a', { key: 'a', modifiers: [process.platform === 'darwin' ? 'Meta' : 'Ctrl'] }],
|
||||
['ctrl++', { key: '+', modifiers: ['Ctrl'] }],
|
||||
['ctrl+shift++', { key: '+', modifiers: ['Ctrl', 'Shift'] }],
|
||||
['super+Left', { key: 'ArrowLeft', modifiers: ['Meta'] }],
|
||||
['win+Right', { key: 'ArrowRight', modifiers: ['Meta'] }]
|
||||
])('maps chord %s', (input, expected) => {
|
||||
|
||||
@@ -50,10 +50,7 @@ const KEY_NAMES: Record<string, string> = {
|
||||
}
|
||||
|
||||
export function parseKey(input: string): KeyChord {
|
||||
const parts = input
|
||||
.split('+')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
const parts = splitKeyChord(input)
|
||||
if (parts.length === 0) {
|
||||
throw new RuntimeClientError('invalid_argument', 'key must not be empty')
|
||||
}
|
||||
@@ -66,6 +63,28 @@ export function parseKey(input: string): KeyChord {
|
||||
}
|
||||
}
|
||||
|
||||
function splitKeyChord(input: string): string[] {
|
||||
const trimmed = input.trim()
|
||||
// Why: `+` is both the chord separator and a printable key users can press.
|
||||
if (trimmed === '+') {
|
||||
return ['+']
|
||||
}
|
||||
if (trimmed.endsWith('+')) {
|
||||
return [
|
||||
...trimmed
|
||||
.slice(0, -1)
|
||||
.split('+')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean),
|
||||
'+'
|
||||
]
|
||||
}
|
||||
return input
|
||||
.split('+')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
function parseModifier(input: string): string {
|
||||
const platformModifier = PLATFORM_MODIFIER_NAMES[input.toLowerCase()]
|
||||
if (platformModifier) {
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
__resetMacTailscaleDnsDiagnosticCacheForTests,
|
||||
parseMacTailscaleDnsDiagnostic,
|
||||
withMacTailscaleDnsHint,
|
||||
withMacTailscaleDnsHintForDiagnostic
|
||||
} from './macos-tailscale-dns-diagnostic'
|
||||
|
||||
vi.mock('node:child_process', () => ({
|
||||
execFileSync: vi.fn()
|
||||
}))
|
||||
|
||||
const MAGIC_DNS_ONLY_SCUTIL = `
|
||||
DNS configuration
|
||||
|
||||
@@ -81,3 +88,31 @@ describe('withMacTailscaleDnsHintForDiagnostic', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('withMacTailscaleDnsHint', () => {
|
||||
const originalPlatform = process.platform
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
|
||||
vi.mocked(execFileSync).mockReset()
|
||||
__resetMacTailscaleDnsDiagnosticCacheForTests()
|
||||
})
|
||||
|
||||
it('reads macOS DNS state through the system scutil path', () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' })
|
||||
vi.mocked(execFileSync).mockReturnValue(MAGIC_DNS_ONLY_SCUTIL)
|
||||
|
||||
const result = withMacTailscaleDnsHint('Codex failed.', 'dns lookup failed')
|
||||
|
||||
expect(result).toContain('Tailscale MagicDNS (100.100.100.100)')
|
||||
expect(execFileSync).toHaveBeenCalledWith(
|
||||
'/usr/sbin/scutil',
|
||||
['--dns'],
|
||||
expect.objectContaining({
|
||||
encoding: 'utf8',
|
||||
timeout: 1500,
|
||||
stdio: ['ignore', 'pipe', 'ignore']
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -52,7 +52,7 @@ function readMacTailscaleDnsDiagnostic(now = Date.now()): DnsDiagnostic | null {
|
||||
|
||||
let diagnostic: DnsDiagnostic | null = null
|
||||
try {
|
||||
const output = execFileSync('scutil', ['--dns'], {
|
||||
const output = execFileSync('/usr/sbin/scutil', ['--dns'], {
|
||||
encoding: 'utf8',
|
||||
timeout: 1500,
|
||||
stdio: ['ignore', 'pipe', 'ignore']
|
||||
|
||||
@@ -457,7 +457,8 @@ describe('RateLimitService', () => {
|
||||
expect(service.getState().inactiveCodexAccounts).toEqual([
|
||||
{
|
||||
accountId: 'account-1',
|
||||
claude: expect.objectContaining({
|
||||
rateLimits: expect.objectContaining({
|
||||
provider: 'codex',
|
||||
session: expect.objectContaining({ usedPercent: 33 })
|
||||
}),
|
||||
updatedAt: expect.any(Number),
|
||||
@@ -497,7 +498,7 @@ describe('RateLimitService', () => {
|
||||
const fetchOnOpen = service.fetchInactiveCodexAccountsOnOpen()
|
||||
await Promise.resolve()
|
||||
expect(service.getState().inactiveCodexAccounts).toEqual([
|
||||
{ accountId: 'account-b', claude: null, updatedAt: 0, isFetching: true }
|
||||
{ accountId: 'account-b', rateLimits: null, updatedAt: 0, isFetching: true }
|
||||
])
|
||||
|
||||
inactiveAccounts = []
|
||||
@@ -669,7 +670,7 @@ describe('RateLimitService', () => {
|
||||
const fetchOnOpen = service.fetchInactiveClaudeAccountsOnOpen()
|
||||
await Promise.resolve()
|
||||
expect(service.getState().inactiveClaudeAccounts).toEqual([
|
||||
{ accountId: 'account-1', claude: null, updatedAt: 0, isFetching: true }
|
||||
{ accountId: 'account-1', rateLimits: null, updatedAt: 0, isFetching: true }
|
||||
])
|
||||
|
||||
service.evictInactiveClaudeCache('account-1')
|
||||
@@ -711,7 +712,8 @@ describe('RateLimitService', () => {
|
||||
expect(service.getState().inactiveClaudeAccounts).toEqual([
|
||||
{
|
||||
accountId: 'account-1',
|
||||
claude: expect.objectContaining({
|
||||
rateLimits: expect.objectContaining({
|
||||
provider: 'claude',
|
||||
session: expect.objectContaining({ usedPercent: 7 })
|
||||
}),
|
||||
updatedAt: expect.any(Number),
|
||||
|
||||
@@ -42,8 +42,8 @@ const MIN_REFETCH_MS = 5 * 60 * 1000 // 5 minutes — debounce resume/manual ref
|
||||
const STALE_THRESHOLD_MS = 30 * 60 * 1000 // 30 minutes — after this, stale data is dropped
|
||||
const INACTIVE_FETCH_DEBOUNCE_MS = 60 * 1000 // 60 seconds — debounce fetch-on-open
|
||||
|
||||
// Why: the internal state only tracks claude and codex. The inactiveClaudeAccounts
|
||||
// array is derived from the cache on demand in getState() and pushToRenderer().
|
||||
// Why: inactive account arrays are derived from provider-specific caches on
|
||||
// demand in getState() and pushToRenderer().
|
||||
type InternalRateLimitState = {
|
||||
claude: ProviderRateLimits | null
|
||||
codex: ProviderRateLimits | null
|
||||
@@ -1024,7 +1024,7 @@ export class RateLimitService {
|
||||
for (const [accountId, limits] of cache) {
|
||||
result.push({
|
||||
accountId,
|
||||
claude: limits,
|
||||
rateLimits: limits,
|
||||
updatedAt: limits.updatedAt,
|
||||
isFetching: fetching.has(accountId)
|
||||
})
|
||||
@@ -1035,7 +1035,7 @@ export class RateLimitService {
|
||||
if (!cache.has(accountId)) {
|
||||
result.push({
|
||||
accountId,
|
||||
claude: null,
|
||||
rateLimits: null,
|
||||
updatedAt: 0,
|
||||
isFetching: true
|
||||
})
|
||||
|
||||
@@ -781,11 +781,11 @@ function ClaudeSwitcherMenu({
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{inactiveUsage?.isFetching && !inactiveUsage.claude ? (
|
||||
{inactiveUsage?.isFetching && !inactiveUsage.rateLimits ? (
|
||||
<InlineUsageSkeleton />
|
||||
) : inactiveUsage?.claude ? (
|
||||
) : inactiveUsage?.rateLimits ? (
|
||||
<InlineUsageBars
|
||||
limits={inactiveUsage.claude}
|
||||
limits={inactiveUsage.rateLimits}
|
||||
isFetching={inactiveUsage.isFetching}
|
||||
/>
|
||||
) : null}
|
||||
@@ -1297,7 +1297,7 @@ function CodexSwitcherMenu({
|
||||
const showSignInAction =
|
||||
!target.active &&
|
||||
target.id !== null &&
|
||||
isUnavailableInactiveUsage(inactiveUsage?.claude)
|
||||
isUnavailableInactiveUsage(inactiveUsage?.rateLimits)
|
||||
const isSigningIn = reauthenticatingAccountId === target.id
|
||||
const isBusy = isSwitching || reauthenticatingAccountId !== null
|
||||
|
||||
@@ -1329,7 +1329,7 @@ function CodexSwitcherMenu({
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{inactiveUsage?.isFetching && !inactiveUsage.claude ? (
|
||||
{inactiveUsage?.isFetching && !inactiveUsage.rateLimits ? (
|
||||
<InlineUsageSkeleton />
|
||||
) : showSignInAction ? (
|
||||
<InlineUsageSignInAction
|
||||
@@ -1344,9 +1344,9 @@ function CodexSwitcherMenu({
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : inactiveUsage?.claude ? (
|
||||
) : inactiveUsage?.rateLimits ? (
|
||||
<InlineUsageBars
|
||||
limits={inactiveUsage.claude}
|
||||
limits={inactiveUsage.rateLimits}
|
||||
isFetching={inactiveUsage.isFetching}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -39,7 +39,7 @@ export type RateLimitRuntimeTarget = {
|
||||
|
||||
export type InactiveAccountUsage = {
|
||||
accountId: string
|
||||
claude: ProviderRateLimits | null
|
||||
rateLimits: ProviderRateLimits | null
|
||||
updatedAt: number
|
||||
isFetching: boolean
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { execFileSync } from 'child_process'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { __resetSecureFileWindowsUserSidForTests, hardenSecurePath } from './secure-file'
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
execFileSync: vi.fn()
|
||||
}))
|
||||
|
||||
describe('hardenSecurePath', () => {
|
||||
const originalSystemRoot = process.env.SystemRoot
|
||||
const originalWindir = process.env.WINDIR
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.SystemRoot = 'C:\\Windows'
|
||||
delete process.env.WINDIR
|
||||
__resetSecureFileWindowsUserSidForTests()
|
||||
vi.mocked(execFileSync).mockReset()
|
||||
vi.mocked(execFileSync).mockImplementation((file) => {
|
||||
if (file === 'C:\\Windows\\System32\\whoami.exe') {
|
||||
return '"USER","S-1-5-21-1000"'
|
||||
}
|
||||
return ''
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalSystemRoot === undefined) {
|
||||
delete process.env.SystemRoot
|
||||
} else {
|
||||
process.env.SystemRoot = originalSystemRoot
|
||||
}
|
||||
if (originalWindir === undefined) {
|
||||
delete process.env.WINDIR
|
||||
} else {
|
||||
process.env.WINDIR = originalWindir
|
||||
}
|
||||
__resetSecureFileWindowsUserSidForTests()
|
||||
})
|
||||
|
||||
it('rewrites Windows ACLs through the system PowerShell path', () => {
|
||||
hardenSecurePath('C:\\Users\\me\\.orca\\secret.json', {
|
||||
isDirectory: false,
|
||||
platform: 'win32'
|
||||
})
|
||||
|
||||
expect(execFileSync).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'C:\\Windows\\System32\\whoami.exe',
|
||||
['/user', '/fo', 'csv', '/nh'],
|
||||
expect.objectContaining({ encoding: 'utf-8' })
|
||||
)
|
||||
const [, powershellArgs, powershellOptions] = vi.mocked(execFileSync).mock.calls[1]!
|
||||
expect(vi.mocked(execFileSync).mock.calls[1]![0]).toBe(
|
||||
'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
|
||||
)
|
||||
expect(powershellArgs).toEqual(
|
||||
expect.arrayContaining([
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-ExecutionPolicy',
|
||||
'Bypass',
|
||||
'C:\\Users\\me\\.orca\\secret.json',
|
||||
'S-1-5-21-1000',
|
||||
'0'
|
||||
])
|
||||
)
|
||||
const script = (powershellArgs as string[])[5]!
|
||||
expect(script).toContain('SetAccessRuleProtection($true, $false)')
|
||||
expect(script).toContain('RemoveAccessRuleSpecific')
|
||||
expect(script).toContain('Unexpected ACL entry')
|
||||
expect(powershellOptions).toEqual(
|
||||
expect.objectContaining({ stdio: 'ignore', windowsHide: true, timeout: 5000 })
|
||||
)
|
||||
})
|
||||
|
||||
it('adds inheritable rules when hardening a Windows directory', () => {
|
||||
hardenSecurePath('C:\\Users\\me\\.orca', { isDirectory: true, platform: 'win32' })
|
||||
|
||||
const powershellArgs = vi.mocked(execFileSync).mock.calls[1]![1] as string[]
|
||||
expect(powershellArgs.at(-1)).toBe('1')
|
||||
expect(powershellArgs[5]).toContain('ContainerInherit')
|
||||
expect(powershellArgs[5]).toContain('ObjectInherit')
|
||||
})
|
||||
|
||||
it('keeps Windows hardening best-effort when ACL rewriting fails', () => {
|
||||
vi.mocked(execFileSync).mockImplementationOnce(() => '"USER","S-1-5-21-1000"')
|
||||
vi.mocked(execFileSync).mockImplementationOnce(() => {
|
||||
throw new Error('access denied')
|
||||
})
|
||||
|
||||
expect(() =>
|
||||
hardenSecurePath('C:\\Users\\me\\.orca\\secret.json', {
|
||||
isDirectory: false,
|
||||
platform: 'win32'
|
||||
})
|
||||
).not.toThrow()
|
||||
})
|
||||
})
|
||||
+82
-16
@@ -1,7 +1,7 @@
|
||||
import { execFileSync } from 'child_process'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'fs'
|
||||
import { dirname } from 'path'
|
||||
import { dirname, win32 as pathWin32 } from 'path'
|
||||
|
||||
let cachedWindowsUserSid: string | null | undefined
|
||||
|
||||
@@ -51,27 +51,80 @@ export function hardenSecurePath(
|
||||
}
|
||||
): void {
|
||||
if (options.platform === 'win32') {
|
||||
bestEffortRestrictWindowsPath(targetPath)
|
||||
bestEffortRestrictWindowsPath(targetPath, options.isDirectory)
|
||||
return
|
||||
}
|
||||
chmodSync(targetPath, options.isDirectory ? 0o700 : 0o600)
|
||||
}
|
||||
|
||||
function bestEffortRestrictWindowsPath(targetPath: string): void {
|
||||
const WINDOWS_RESTRICT_ACL_SCRIPT = `
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$path = $args[0]
|
||||
$currentUserSid = $args[1]
|
||||
$isDirectory = $args[2] -eq '1'
|
||||
$allowedSidTexts = @($currentUserSid, 'S-1-5-18', 'S-1-5-32-544')
|
||||
$allowedSids = @{}
|
||||
foreach ($sidText in $allowedSidTexts) {
|
||||
$allowedSids[$sidText] = $true
|
||||
}
|
||||
$acl = Get-Acl -LiteralPath $path
|
||||
$acl.SetAccessRuleProtection($true, $false)
|
||||
foreach ($rule in @($acl.Access)) {
|
||||
[void]$acl.RemoveAccessRuleSpecific($rule)
|
||||
}
|
||||
$inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::None
|
||||
if ($isDirectory) {
|
||||
$inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
|
||||
}
|
||||
foreach ($sidText in $allowedSidTexts) {
|
||||
$sid = [System.Security.Principal.SecurityIdentifier]::new($sidText)
|
||||
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new(
|
||||
$sid,
|
||||
[System.Security.AccessControl.FileSystemRights]::FullControl,
|
||||
$inheritanceFlags,
|
||||
[System.Security.AccessControl.PropagationFlags]::None,
|
||||
[System.Security.AccessControl.AccessControlType]::Allow
|
||||
)
|
||||
[void]$acl.AddAccessRule($rule)
|
||||
}
|
||||
Set-Acl -LiteralPath $path -AclObject $acl
|
||||
$verifiedAcl = Get-Acl -LiteralPath $path
|
||||
if (-not $verifiedAcl.AreAccessRulesProtected) {
|
||||
throw 'ACL inheritance is still enabled'
|
||||
}
|
||||
$fullControl = [System.Security.AccessControl.FileSystemRights]::FullControl
|
||||
foreach ($rule in @($verifiedAcl.Access)) {
|
||||
$sid = $rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value
|
||||
if (-not $allowedSids.ContainsKey($sid)) {
|
||||
throw "Unexpected ACL entry $sid"
|
||||
}
|
||||
if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) {
|
||||
throw "Unexpected ACL deny entry $sid"
|
||||
}
|
||||
if (($rule.FileSystemRights -band $fullControl) -ne $fullControl) {
|
||||
throw "ACL entry $sid does not grant FullControl"
|
||||
}
|
||||
}
|
||||
`.trim()
|
||||
|
||||
function bestEffortRestrictWindowsPath(targetPath: string, isDirectory: boolean): void {
|
||||
const currentUserSid = getCurrentWindowsUserSid()
|
||||
if (!currentUserSid) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
execFileSync(
|
||||
'icacls',
|
||||
getWindowsSystemToolPath('WindowsPowerShell\\v1.0\\powershell.exe'),
|
||||
[
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-ExecutionPolicy',
|
||||
'Bypass',
|
||||
'-Command',
|
||||
WINDOWS_RESTRICT_ACL_SCRIPT,
|
||||
targetPath,
|
||||
'/inheritance:r',
|
||||
'/grant:r',
|
||||
`*${currentUserSid}:(F)`,
|
||||
'*S-1-5-18:(F)',
|
||||
'*S-1-5-32-544:(F)'
|
||||
currentUserSid,
|
||||
isDirectory ? '1' : '0'
|
||||
],
|
||||
{
|
||||
stdio: 'ignore',
|
||||
@@ -81,7 +134,7 @@ function bestEffortRestrictWindowsPath(targetPath: string): void {
|
||||
)
|
||||
} catch {
|
||||
// Why: credential-file hardening should not prevent Orca from starting on
|
||||
// Windows machines where icacls is unavailable or locked down differently.
|
||||
// Windows machines where PowerShell ACL APIs are unavailable or locked down.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,12 +143,16 @@ function getCurrentWindowsUserSid(): string | null {
|
||||
return cachedWindowsUserSid
|
||||
}
|
||||
try {
|
||||
const output = execFileSync('whoami', ['/user', '/fo', 'csv', '/nh'], {
|
||||
encoding: 'utf-8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
windowsHide: true,
|
||||
timeout: 5000
|
||||
}).trim()
|
||||
const output = execFileSync(
|
||||
getWindowsSystemToolPath('whoami.exe'),
|
||||
['/user', '/fo', 'csv', '/nh'],
|
||||
{
|
||||
encoding: 'utf-8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
windowsHide: true,
|
||||
timeout: 5000
|
||||
}
|
||||
).trim()
|
||||
const columns = parseCsvLine(output)
|
||||
cachedWindowsUserSid = columns[1] ?? null
|
||||
} catch {
|
||||
@@ -104,6 +161,15 @@ function getCurrentWindowsUserSid(): string | null {
|
||||
return cachedWindowsUserSid
|
||||
}
|
||||
|
||||
function getWindowsSystemToolPath(relativeSystem32Path: string): string {
|
||||
const systemRoot = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows'
|
||||
return pathWin32.join(systemRoot, 'System32', relativeSystem32Path)
|
||||
}
|
||||
|
||||
function parseCsvLine(line: string): string[] {
|
||||
return line.split(/","/).map((part) => part.replace(/^"/, '').replace(/"$/, ''))
|
||||
}
|
||||
|
||||
export function __resetSecureFileWindowsUserSidForTests(): void {
|
||||
cachedWindowsUserSid = undefined
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user