chore: 保存 Agent 安全优化前基线

This commit is contained in:
Logan.Li committed 2026-09-02 23:31:38 +08:00
1 parent 08696896f9
commit ff016347cd
116 files changed
+3858 -2485

No files matched your search

+30 -7
View File
@@ -92,7 +92,9 @@ describe('terminal Agent CLI panel', () => {
})
fireEvent.click(screen.getByRole('button', { name: '发送' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'uptime'))
await waitFor(() =>
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'uptime', { fromAgent: true })
)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(await screen.findByText('load average: 0.01')).toBeVisible()
expect(await screen.findByText('负载正常,任务完成。')).toBeVisible()
@@ -102,7 +104,12 @@ describe('terminal Agent CLI panel', () => {
it('asks for confirmation for high-risk commands in the default relaxed mode', async () => {
vi.mocked(mockDesktopApi.aiComplete)
.mockResolvedValueOnce({ success: true, text: '```bash\nsystemctl restart nginx\n```', model: 'test', redactedCount: 0 })
.mockResolvedValueOnce({
success: true,
text: '```bash\nsystemctl restart nginx\n```',
model: 'test',
redactedCount: 0,
})
.mockResolvedValueOnce({ success: true, text: 'FINAL: nginx 已重启。', model: 'test', redactedCount: 0 })
vi.mocked(mockDesktopApi.sshExec).mockResolvedValueOnce({ success: true, result: 'ok', exitCode: 0 })
@@ -129,8 +136,18 @@ describe('terminal Agent CLI panel', () => {
it('Always skips confirmation for the same command shape in the current panel session', async () => {
vi.mocked(mockDesktopApi.aiComplete)
.mockResolvedValueOnce({ success: true, text: '```bash\nrm /tmp/tmp.AAA111\n```', model: 'test', redactedCount: 0 })
.mockResolvedValueOnce({ success: true, text: '```bash\nrm /tmp/tmp.BBB222\n```', model: 'test', redactedCount: 0 })
.mockResolvedValueOnce({
success: true,
text: '```bash\nrm /tmp/tmp.AAA111\n```',
model: 'test',
redactedCount: 0,
})
.mockResolvedValueOnce({
success: true,
text: '```bash\nrm /tmp/tmp.BBB222\n```',
model: 'test',
redactedCount: 0,
})
.mockResolvedValueOnce({ success: true, text: 'FINAL: 清理完成。', model: 'test', redactedCount: 0 })
vi.mocked(mockDesktopApi.sshExec)
.mockResolvedValueOnce({ success: true, result: 'ok', exitCode: 0 })
@@ -151,8 +168,12 @@ describe('terminal Agent CLI panel', () => {
const dialog = await screen.findByRole('dialog')
fireEvent.click(within(dialog).getByRole('button', { name: 'Always' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'rm /tmp/tmp.AAA111'))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'rm /tmp/tmp.BBB222'))
await waitFor(() =>
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'rm /tmp/tmp.AAA111', { fromAgent: true })
)
await waitFor(() =>
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'rm /tmp/tmp.BBB222', { fromAgent: true })
)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(await screen.findByText('清理完成。')).toBeVisible()
})
@@ -356,7 +377,9 @@ describe('terminal Agent CLI panel', () => {
fireEvent.change(screen.getByPlaceholderText(PLACEHOLDER), { target: { value: '查看时间' } })
fireEvent.click(screen.getByRole('button', { name: '发送' }))
await waitFor(() => expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'date'))
await waitFor(() =>
expect(mockDesktopApi.sshExec).toHaveBeenCalledWith('ssh-active-1', 'date', { fromAgent: true })
)
fireEvent.click(screen.getByRole('button', { name: '停止' }))
expect(mockDesktopApi.sshExecCancel).toHaveBeenCalledWith('ssh-active-1')
+190
View File
@@ -0,0 +1,190 @@
import { fireEvent, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import Sidebar from '../../src/components/layout/Sidebar'
import { useSessionStore, type Session } from '../../src/stores/sessionStore'
import { useTabStore } from '../../src/stores/tabStore'
import { unlockProForTests } from '../helpers/entitlement'
import { mockDesktopApi } from '../setup'
function makeSession(overrides: Partial<Session> & Pick<Session, 'id' | 'name'>): Session {
return {
host: `${overrides.id}.example.com`,
port: 22,
username: 'root',
authType: 'key',
...overrides,
}
}
function rowOf(name: string): HTMLElement {
const row = screen.getByText(name).closest('[data-session-row]')
if (!row) throw new Error(`session row not found: ${name}`)
return row as HTMLElement
}
function mockElementFromPoint(target: Element) {
const original = document.elementFromPoint
Object.defineProperty(document, 'elementFromPoint', {
configurable: true,
value: vi.fn(() => target),
})
return () => {
Object.defineProperty(document, 'elementFromPoint', {
configurable: true,
value: original,
})
}
}
/** Pointer-drag a session row onto `dropOn` (WKWebView-safe path, not HTML5 DnD). */
function pointerDrag(fromName: string, dropOn: Element) {
const source = rowOf(fromName)
const restore = mockElementFromPoint(dropOn)
fireEvent.pointerDown(source, { button: 0, pointerId: 1, clientX: 10, clientY: 10 })
fireEvent.pointerMove(source, { pointerId: 1, clientX: 30, clientY: 40 })
fireEvent.pointerUp(source, { button: 0, pointerId: 1, clientX: 30, clientY: 40 })
restore()
}
describe('sidebar session manual order', () => {
beforeEach(() => {
vi.clearAllMocks()
unlockProForTests()
window.opsxApi = mockDesktopApi
useSessionStore.setState({ sessions: [] })
useTabStore.setState({
tabs: [{ id: 'welcome', title: '欢迎', type: 'welcome', isActive: true }],
activeTabId: 'welcome',
})
})
function loadSessions(sessions: Session[]) {
vi.mocked(mockDesktopApi.sessionGetAll).mockResolvedValueOnce({ success: true, sessions })
}
function renderSidebar() {
render(<Sidebar onNewSession={vi.fn()} onQuickConnect={vi.fn()} onEditSession={vi.fn()} />)
}
it('renders groups in manual order with legacy rows kept after ordered ones', async () => {
loadSessions([
makeSession({ id: 'pre-jenkins', name: 'pre-jenkins', sortOrder: 2 }),
makeSession({ id: 'pre-monitor', name: 'pre-monitor', sortOrder: 0 }),
makeSession({ id: 'legacy-host', name: 'legacy-host' }),
])
renderSidebar()
await screen.findByText('pre-monitor')
const group = document.getElementById('session-group-default')!
const names = within(group)
.getAllByText(/pre-jenkins|pre-monitor|legacy-host/)
.map((node) => node.textContent)
expect(names).toEqual(['pre-monitor', 'pre-jenkins', 'legacy-host'])
})
it('persists a within-group drag as one batch reorder', async () => {
loadSessions([
makeSession({ id: 'a', name: 'alpha', sortOrder: 0 }),
makeSession({ id: 'b', name: 'bravo', sortOrder: 1 }),
makeSession({ id: 'c', name: 'charlie', sortOrder: 2 }),
])
renderSidebar()
await screen.findByText('alpha')
// jsdom rows report a zero rect, so a drop resolves to "insert after".
pointerDrag('charlie', rowOf('alpha'))
await vi.waitFor(() => {
expect(mockDesktopApi.sessionReorder).toHaveBeenCalledWith([
{ id: 'a', sortOrder: 0 },
{ id: 'c', sortOrder: 1 },
{ id: 'b', sortOrder: 2 },
])
})
// The store keeps its element order; the persisted sortOrders define display order.
const order = new Map(useSessionStore.getState().sessions.map((session) => [session.id, session.sortOrder]))
expect(order.get('a')).toBe(0)
expect(order.get('c')).toBe(1)
expect(order.get('b')).toBe(2)
})
it('moves a session into another group via its header', async () => {
loadSessions([
makeSession({ id: 'a', name: 'alpha', sortOrder: 0 }),
makeSession({ id: 'b', name: 'bravo', sortOrder: 1, group: 'prod' }),
])
renderSidebar()
await screen.findByText('alpha')
pointerDrag('alpha', screen.getByText('prod'))
await vi.waitFor(() => {
expect(mockDesktopApi.sessionReorder).toHaveBeenCalledWith([
{ id: 'b', sortOrder: 0 },
{ id: 'a', sortOrder: 1, group: 'prod' },
])
})
expect(useSessionStore.getState().sessions.find((session) => session.id === 'a')?.group).toBe('prod')
})
it('inserts a session among hosts already in another group', async () => {
loadSessions([
makeSession({ id: 'a', name: 'alpha', sortOrder: 0 }),
makeSession({ id: 'b', name: 'bravo', sortOrder: 0, group: 'test' }),
makeSession({ id: 'c', name: 'charlie', sortOrder: 1, group: 'test' }),
])
renderSidebar()
await screen.findByText('alpha')
fireEvent.click(screen.getByText('test'))
await screen.findByText('bravo')
pointerDrag('alpha', rowOf('bravo'))
await vi.waitFor(() => {
expect(mockDesktopApi.sessionReorder).toHaveBeenCalledWith([
{ id: 'b', sortOrder: 0 },
{ id: 'a', sortOrder: 1, group: 'test' },
{ id: 'c', sortOrder: 2 },
])
})
expect(useSessionStore.getState().sessions.find((session) => session.id === 'a')?.group).toBe('test')
})
it('sorts a group by name from the group context menu', async () => {
const user = userEvent.setup()
loadSessions([
makeSession({ id: 'b', name: 'bravo' }),
makeSession({ id: 'g', name: 'gamma' }),
makeSession({ id: 'a', name: 'alpha' }),
])
renderSidebar()
await screen.findByText('bravo')
await user.pointer([{ keys: '[MouseRight>]', target: screen.getByText('默认分组') }, { keys: '[/MouseRight]' }])
await user.click(screen.getByRole('button', { name: '按名称排序' }))
await vi.waitFor(() => {
expect(mockDesktopApi.sessionReorder).toHaveBeenCalledWith([
{ id: 'a', sortOrder: 0 },
{ id: 'b', sortOrder: 1 },
{ id: 'g', sortOrder: 2 },
])
})
})
it('skips the reorder write when the drop changes nothing', async () => {
loadSessions([
makeSession({ id: 'a', name: 'alpha', sortOrder: 0 }),
makeSession({ id: 'b', name: 'bravo', sortOrder: 1 }),
])
renderSidebar()
await screen.findByText('alpha')
// Dropping bravo after itself-equivalent position (after bravo) is a no-op.
pointerDrag('bravo', rowOf('bravo'))
await Promise.resolve()
expect(mockDesktopApi.sessionReorder).not.toHaveBeenCalled()
})
})
@@ -12,4 +12,13 @@ describe('remote shell close recovery', () => {
fireEvent.click(screen.getByRole('button', { name: '重新打开 Shell' }))
expect(reopen).toHaveBeenCalledTimes(1)
})
it('local shell exit never mentions the SSH connection', () => {
const reopen = vi.fn()
render(<ShellClosedOverlay reason="本地 Shell 已退出" idleTimeout={false} isLocal onReopen={reopen} />)
expect(screen.getByText('Shell 已退出')).toBeVisible()
expect(screen.getByText('重新打开 Shell 即可继续使用本地终端')).toBeVisible()
expect(screen.queryByText(/SSH 连接仍可用/)).toBeNull()
})
})
+5
View File
@@ -8,6 +8,11 @@ vi.mock('@tauri-apps/api/event', () => ({
listen: listenMock,
}))
// Subscription tests exercise the Tauri path; production no-ops outside Tauri.
vi.mock('../../src/platform/runtime', () => ({
isTauriRuntime: () => true,
}))
import { desktopApi } from '../../src/platform/desktop'
function deferred<T>() {
+9
View File
@@ -75,6 +75,7 @@ export const mockDesktopApi: DesktopApiContract = {
session: { id, ...updates },
})),
sessionDelete: vi.fn().mockResolvedValue({ success: true }),
sessionReorder: vi.fn().mockResolvedValue({ success: true }),
// Settings
settingsGet: vi.fn().mockResolvedValue({ success: true, value: undefined }),
@@ -98,6 +99,12 @@ export const mockDesktopApi: DesktopApiContract = {
features: [],
}),
licenseDeviceId: vi.fn().mockResolvedValue('test-device'),
licenseVerify: vi.fn().mockResolvedValue({
plan: 'free',
deviceId: 'test-device',
activated: false,
features: [],
}),
licenseSetEmail: vi.fn().mockResolvedValue({
plan: 'free',
deviceId: 'test-device',
@@ -160,9 +167,11 @@ export const mockDesktopApi: DesktopApiContract = {
shellPath: '/bin/zsh',
shellName: 'zsh',
}),
localOpenOutput: vi.fn().mockResolvedValue({ success: true, data: [] }),
localWrite: vi.fn().mockResolvedValue({ success: true }),
localResize: vi.fn().mockResolvedValue({ success: true }),
localKill: vi.fn().mockResolvedValue({ success: true }),
localKillAll: vi.fn().mockResolvedValue({ success: true, killed: 0 }),
onLocalData: vi.fn(),
onLocalExit: vi.fn(),
+39 -10
View File
@@ -2,7 +2,7 @@
* TabStore Tests - 标签页状态管理测试
*/
import { describe, it, expect, beforeEach } from 'vitest'
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { useTabStore } from '../../src/stores/tabStore'
describe('TabStore', () => {
@@ -31,7 +31,7 @@ describe('TabStore', () => {
const newTabs = useTabStore.getState().tabs
expect(newTabs).toHaveLength(tabs.length + 1)
expect(newTabs.find(t => t.type === 'terminal')).toBeDefined()
expect(newTabs.find((t) => t.type === 'terminal')).toBeDefined()
})
it('添加新标签后应该激活它', () => {
@@ -39,7 +39,7 @@ describe('TabStore', () => {
addTab({ title: 'Terminal', type: 'terminal' })
const { activeTabId, tabs } = useTabStore.getState()
const activeTab = tabs.find(t => t.id === activeTabId)
const activeTab = tabs.find((t) => t.id === activeTabId)
expect(activeTab?.type).toBe('terminal')
})
@@ -104,12 +104,12 @@ describe('TabStore', () => {
addTab({ title: 'Tab 2', type: 'sftp' })
const { tabs } = useTabStore.getState()
const tabToClose = tabs.find(t => t.title === 'Tab 1')
const tabToClose = tabs.find((t) => t.title === 'Tab 1')
if (tabToClose) {
closeTab(tabToClose.id)
const { tabs: newTabs } = useTabStore.getState()
expect(newTabs.find(t => t.isActive)?.title).toBe('Tab 2')
expect(newTabs.find((t) => t.isActive)?.title).toBe('Tab 2')
}
})
@@ -118,7 +118,7 @@ describe('TabStore', () => {
addTab({ title: 'Tab 1', type: 'terminal' })
const { tabs } = useTabStore.getState()
const tabToClose = tabs.find(t => t.title === 'Tab 1')
const tabToClose = tabs.find((t) => t.title === 'Tab 1')
if (tabToClose) {
const closed = closeTab(tabToClose.id)
@@ -133,7 +133,7 @@ describe('TabStore', () => {
addTab({ title: 'Tab 1', type: 'terminal' })
addTab({ title: 'Tab 2', type: 'sftp' })
const tabToKeep = useTabStore.getState().tabs.find(t => t.title === 'Tab 1')
const tabToKeep = useTabStore.getState().tabs.find((t) => t.title === 'Tab 1')
if (tabToKeep) {
closeOtherTabs(tabToKeep.id)
const { tabs: newTabs } = useTabStore.getState()
@@ -150,12 +150,12 @@ describe('TabStore', () => {
addTab({ title: 'Tab 2', type: 'sftp' })
const { tabs } = useTabStore.getState()
const tabToActivate = tabs.find(t => t.title === 'Tab 1')
const tabToActivate = tabs.find((t) => t.title === 'Tab 1')
if (tabToActivate) {
activateTab(tabToActivate.id)
const { tabs: newTabs, activeTabId } = useTabStore.getState()
const activeTab = newTabs.find(t => t.id === activeTabId)
const activeTab = newTabs.find((t) => t.id === activeTabId)
expect(activeTab?.title).toBe('Tab 1')
}
})
@@ -167,7 +167,7 @@ describe('TabStore', () => {
addTab({ title: 'Test Tab', type: 'terminal' })
const { tabs } = useTabStore.getState()
const testTab = tabs.find(t => t.title === 'Test Tab')
const testTab = tabs.find((t) => t.title === 'Test Tab')
if (testTab) {
const found = getTabById(testTab.id)
@@ -191,4 +191,33 @@ describe('TabStore', () => {
expect(tabs[0].title).toBe('Updated Welcome')
})
})
describe('持久化恢复', () => {
afterEach(() => {
localStorage.removeItem('opsxshell-tabs')
})
const seedTabs = (tabs: unknown[]) => {
localStorage.setItem('opsxshell-tabs', JSON.stringify({ state: { tabs, activeTabId: null }, version: 0 }))
}
it('SSH 标签恢复后仍需手动重连', async () => {
seedTabs([{ id: 'ssh-1', title: 'user@host', type: 'terminal', sessionId: 's1' }])
await useTabStore.persist.rehydrate()
const tab = useTabStore.getState().tabs.find((t) => t.id === 'ssh-1')
expect(tab?.needsReconnect).toBe(true)
})
it('本地终端标签恢复后直接拉起 Shell,不弹重连横幅', async () => {
seedTabs([{ id: 'local-1', title: 'Bash', type: 'terminal', isLocal: true, localShellPath: '/bin/bash' }])
await useTabStore.persist.rehydrate()
const tab = useTabStore.getState().tabs.find((t) => t.id === 'local-1')
expect(tab?.needsReconnect).toBe(false)
expect(tab?.localShellPath).toBe('/bin/bash')
})
})
})
+8
View File
@@ -31,6 +31,14 @@ describe('Agent command guardrail', () => {
expect(agentCommandNeedsConfirmation('critical', 'strict')).toBe(false)
})
it('confirm-all still auto-runs only the read-only whitelist', () => {
expect(agentCommandNeedsConfirmation('safe', 'relaxed', true)).toBe(false)
expect(agentCommandNeedsConfirmation('low', 'relaxed', true)).toBe(true)
expect(agentCommandNeedsConfirmation('medium', 'strict', true)).toBe(true)
expect(agentCommandNeedsConfirmation('high', 'relaxed', true)).toBe(true)
expect(agentCommandNeedsConfirmation('critical', 'relaxed', true)).toBe(false)
})
it('fingerprints similar temp-path commands for session Always', () => {
expect(agentCommandAllowFingerprint('rm /tmp/tmp.3RUZRHTwk2', 'high')).toBe(
agentCommandAllowFingerprint('rm /tmp/tmp.ABCDEFG123', 'high')
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest'
import { compareBySortOrder, groupSessionsInDisplayOrder } from '../../src/utils/sessionGroups'
import type { Session } from '../../src/stores/sessionStore'
function session(id: string, sortOrder?: number, group?: string): Session {
return {
id,
name: id,
host: `${id}.example.com`,
port: 22,
username: 'root',
authType: 'key',
...(sortOrder !== undefined ? { sortOrder } : {}),
...(group !== undefined ? { group } : {}),
}
}
describe('compareBySortOrder', () => {
it('sorts explicit sortOrder ascending', () => {
const rows = [{ sortOrder: 2 }, { sortOrder: 0 }, { sortOrder: 1 }]
expect([...rows].sort(compareBySortOrder).map((r) => r.sortOrder)).toEqual([0, 1, 2])
})
it('keeps rows without sortOrder after ordered rows', () => {
const rows = [{ sortOrder: undefined }, { sortOrder: 0 }, {}, { sortOrder: 1 }]
const sorted = [...rows].sort(compareBySortOrder)
expect(sorted.map((r) => r.sortOrder ?? null)).toEqual([0, 1, null, null])
})
})
describe('groupSessionsInDisplayOrder', () => {
it('filters one group and orders by manual order with legacy rows last', () => {
const sessions = [
session('legacy-a'),
session('ordered-b', 1, 'prod'),
session('ordered-a', 0, 'prod'),
session('legacy-b'),
session('other', 0, 'staging'),
]
expect(groupSessionsInDisplayOrder(sessions, 'prod').map((s) => s.id)).toEqual(['ordered-a', 'ordered-b'])
expect(groupSessionsInDisplayOrder(sessions, 'default').map((s) => s.id)).toEqual(['legacy-a', 'legacy-b'])
})
it('preserves storage order among legacy rows (stable sort)', () => {
const sessions = [session('first'), session('second'), session('third')]
expect(groupSessionsInDisplayOrder(sessions, 'default').map((s) => s.id)).toEqual(['first', 'second', 'third'])
})
it('rewriting 0..n-1 makes the manual order authoritative', () => {
const sessions = [session('a'), session('b'), session('c')]
const reordered = ['c', 'a', 'b']
const rewritten = reordered.map((id, index) => ({
...sessions.find((s) => s.id === id)!,
sortOrder: index,
}))
expect(rewritten.sort(compareBySortOrder).map((s) => s.id)).toEqual(['c', 'a', 'b'])
})
})
+31
View File
@@ -0,0 +1,31 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushShellBootstrap } from '../../src/utils/shellIO'
describe('flushShellBootstrap', () => {
beforeEach(() => {
vi.mocked(window.opsxApi.localOpenOutput).mockClear()
vi.mocked(window.opsxApi.sshShellOpenOutput).mockClear()
vi.mocked(window.opsxApi.localOpenOutput).mockResolvedValue({
success: true,
data: [98, 97, 115, 104],
})
vi.mocked(window.opsxApi.sshShellOpenOutput).mockResolvedValue({
success: true,
data: [109, 111, 116, 100],
})
})
it('opens buffered local PTY output for local-* ids', async () => {
const boot = await flushShellBootstrap('local-abc')
expect(window.opsxApi.localOpenOutput).toHaveBeenCalledWith('local-abc')
expect(window.opsxApi.sshShellOpenOutput).not.toHaveBeenCalled()
expect(boot).toEqual(new Uint8Array([98, 97, 115, 104]))
})
it('opens buffered SSH output for remote shell ids', async () => {
const boot = await flushShellBootstrap('shell-abc')
expect(window.opsxApi.sshShellOpenOutput).toHaveBeenCalledWith('shell-abc')
expect(window.opsxApi.localOpenOutput).not.toHaveBeenCalled()
expect(boot).toEqual(new Uint8Array([109, 111, 116, 100]))
})
})