Files
opencode-manager/backend/test/utils/ssh-validation.test.ts
theepicsaxguyandChris Scott da283a82cf Feature/enhanced source control (#138)
* feat: enhance source control with discard and commit detail views

- Add discard changes functionality with confirmation dialog
- Implement commit detail view with file list and diffs
- Update commit badges: blue for unpushed (local), purple for pushed (remote)
- Display current branch in commits header
- Reuse existing components (DeleteDialog, FileDiffView, GitFlatFileList)
- Add proper error handling and toast notifications
- Extend backend API with /discard and /commit/:hash endpoints
- Update types to include CommitDetails and CommitFile interfaces

Backend:
- Add discardChanges() method to GitService
- Add getCommitDetails() and getCommitDiff() methods
- Add POST /:id/git/discard endpoint
- Add GET /:id/git/commit/:hash and /:id/git/commit/:hash/diff endpoints

Frontend:
- Add discard button (rotate-left icon) to file items
- Add gitDiscardFiles API function and useGit mutation
- Create CommitDetailView component
- Update CommitsTab with color coding and branch display
- Extend SourceControlPanel for commit detail navigation
- Add confirmation dialog using DeleteDialog pattern

Tests:
- Backend tests passing with 77% line coverage
- Linting passes for all modified files
- Type safety maintained throughout

BREAKING CHANGES: None

* Fix critical bugs from code review

- Fix syntax error in GitService.ts (missing closing brace for getCommitDiff)
- Make AUTH_SECRET mandatory in crypto.ts to prevent weak encryption fallback
- Fix race condition in PassphraseHandler by using unique request IDs
- Add error logging to ssh-key-manager catch blocks
- Add type guards (isGitCredential, filterGitCredentials) to replace unsafe assertions
- Fix TypeScript errors and variable shadowing in GitService and settings
- Remove unused variable in sshHostKeyHandler
- Update GitService tests with proper mock data structure

All changes verified: lint passes, typecheck passes, 102/103 tests pass

* Fix critical bugs from code review

- Fix git restore command syntax (--source=HEAD → --source HEAD)
- Use crypto.randomBytes for secure requestId generation
- Add requestId to SSH host key broadcast for frontend compatibility
- Add missing onDiscard prop to GitFlatFileList
- Remove dead code (187 unreachable lines) in ChangesTab
- Fix regex alternation bug in commit stat parsing
- Optimize getCommitDetails with --numstat (N+1 → 1 git call)
- Optimize unpushed commit check to use merge-base instead of full list
- Remove useless conditional in handleDiscard
- Fix type contract violation in CommitDetailView onSelect

* fix: resolve code review issues

- Add missing handleDiscard function in ChangesTab.tsx
- Fix duplicate requestId property in sshHostKeyHandler.ts
- Remove unnecessary type assertion in settings.ts

* feat: enhance source control with commit view improvements and diff fixes

- Add readOnly mode to GitFlatFileList to hide stage/unstage buttons in commit view
- Fix commit file diff display by using correct git show command syntax
- Add line stats display (+additions/-deletions) for each file in commit view
- Show total commit stats in header (Changed Files N +X -Y)
- Fix commit file list parsing to use --name-status and --numstat
- Add 500KB diff size limit with truncation warning
- Fix discard changes for untracked files by deleting them directly
- Update Dockerfile to copy backend/node_modules correctly
- Fix TypeScript error in CommitDetailView onFileSelect call

* Refactor API error handling and enhance source control functionality

* Fix code review issues: OAuth error handling, unpushed detection, comments, and duplicates

- Remove shared handleApiError import from OAuth and restore local pattern

- Fix isCommitUnpushed to use getUnpushedCommitHashes for correct upstream detection

- Remove inline comments from ssh-key-manager.ts (style violation)

- Remove duplicate fetchCommitDiff function

- Add missing getErrorMessage import to repo-git.ts

* Refactor imports and type assertions in GitService, SSH tests, and handleApiError

* Refactor GitService methods for improved error handling and code clarity; add discardChanges functionality and enhance commit details retrieval

* Refactor Git and SSH services: streamline imports, enhance error handling, and remove unused code

* Refactor source control components: remove unused useGitAction hook and enhance error handling in handleGitAction

* Enhance error handling in Git routes and improve UI components for better user experience

* Remove unnecessary blank line in GitService class

* Fix commit log parsing and rename detection in GitService

* Refactor source control UI for full-screen diffs, improve mobile view, and add discard confirmation dialog

* Fix lint warnings and ignore test files in GitGuardian scan

---------

Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
2026-02-21 21:57:05 -05:00

266 lines
8.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest'
vi.mock('@opencode-manager/shared/config/env', () => ({
ENV: {
AUTH: {
SECRET: 'test-secret-for-encryption'
},
OPENCODE: {
PORT: 5551
},
SERVER: {
PORT: 5003
}
},
getReposPath: vi.fn(() => '/tmp/test-repos'),
getWorkspacePath: vi.fn(() => '/tmp/test-workspace')
}))
let mockExecuteCommand: any
vi.mock('../../src/utils/process', () => ({
executeCommand: vi.fn()
}))
vi.mock('fs', () => ({
promises: {
writeFile: vi.fn().mockResolvedValue(undefined),
unlink: vi.fn().mockResolvedValue(undefined)
}
}))
import { validateSSHPrivateKey } from '../../src/utils/ssh-validation'
import { executeCommand } from '../../src/utils/process'
beforeAll(() => {
mockExecuteCommand = executeCommand
})
describe('validateSSHPrivateKey', () => {
beforeEach(() => {
vi.clearAllMocks()
mockExecuteCommand.mockResolvedValue('ssh-ed25519 AAAAC...')
})
afterEach(() => {
vi.clearAllMocks()
})
describe('valid key formats', () => {
const validHeaders = [
{ name: 'OPENSSH', header: '-----BEGIN OPENSSH PRIVATE KEY-----' },
{ name: 'RSA', header: '-----BEGIN RSA PRIVATE KEY-----' },
{ name: 'EC', header: '-----BEGIN EC PRIVATE KEY-----' },
{ name: 'DSA', header: '-----BEGIN DSA PRIVATE KEY-----' },
{ name: 'ED25519', header: '-----BEGIN ED25519 PRIVATE KEY-----' },
{ name: 'PGP', header: '-----BEGIN PGP PRIVATE KEY BLOCK-----' }
]
validHeaders.forEach(({ name, header }) => {
it(`should accept valid ${name} key format`, async () => {
const key = `${header}\n${'A'.repeat(100)}\n-----END ${name} PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
})
})
it('should accept properly formatted OPENSSH key', async () => {
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
})
})
describe('passphrase detection', () => {
it('should detect key without passphrase', async () => {
mockExecuteCommand.mockResolvedValue('ssh-ed25519 AAAAC3...')
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
expect(result.hasPassphrase).toBe(false)
})
it('should detect key with passphrase via incorrect passphrase error', async () => {
mockExecuteCommand.mockRejectedValue(new Error('incorrect passphrase supplied to decrypt private key'))
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
expect(result.hasPassphrase).toBe(true)
})
it('should detect key with passphrase via failed error', async () => {
mockExecuteCommand.mockRejectedValue(new Error('failed: incorrect passphrase supplied to decrypt private key'))
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
expect(result.hasPassphrase).toBe(true)
})
it('should detect key with passphrase via Load key error', async () => {
mockExecuteCommand.mockRejectedValue(new Error('Load key "/tmp/temp-ssh-key-123": bad passphrase'))
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
expect(result.hasPassphrase).toBe(true)
})
})
describe('invalid key rejection', () => {
it('should reject key with invalid format', async () => {
mockExecuteCommand.mockRejectedValue(new Error('invalid format'))
const key = `-----BEGIN INVALID KEY-----
${'A'.repeat(120)}
-----END INVALID KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(false)
expect(result.error).toContain('Invalid SSH key')
})
it('should reject corrupted key', async () => {
mockExecuteCommand.mockRejectedValue(new Error('load key: invalid format'))
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(false)
expect(result.error).toContain('Invalid SSH key')
})
})
describe('empty/null/undefined key handling', () => {
it('should reject null key', async () => {
const result = await validateSSHPrivateKey(null as unknown as string)
expect(result.valid).toBe(false)
expect(result.error).toBe('SSH key is required')
})
it('should reject undefined key', async () => {
const result = await validateSSHPrivateKey(undefined as unknown as string)
expect(result.valid).toBe(false)
expect(result.error).toBe('SSH key is required')
})
it('should reject empty string', async () => {
const result = await validateSSHPrivateKey('')
expect(result.valid).toBe(false)
expect(result.error).toBe('SSH key is required')
})
it('should reject whitespace-only string', async () => {
const result = await validateSSHPrivateKey(' \n\t ')
expect(result.valid).toBe(false)
expect(result.error).toBe('SSH key cannot be empty')
})
})
describe('ssh-keygen command execution', () => {
it('should call ssh-keygen with correct arguments', async () => {
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
await validateSSHPrivateKey(key)
expect(mockExecuteCommand).toHaveBeenCalled()
const call = mockExecuteCommand.mock.calls[0]
expect(call).toBeDefined()
const args = call?.[0] as string[] | undefined
expect(args?.[0]).toBe('ssh-keygen')
expect(args?.[1]).toBe('-y')
expect(args?.[2]).toBe('-P')
expect(args?.[3]).toBe('')
expect(args?.[4]).toBe('-f')
})
it('should pass silent option to command execution', async () => {
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
await validateSSHPrivateKey(key)
expect(mockExecuteCommand).toHaveBeenCalled()
const call = mockExecuteCommand.mock.calls[0]
expect(call).toBeDefined()
const options = call?.[1] as { silent?: boolean } | undefined
expect(options?.silent).toBe(true)
})
})
describe('file cleanup after validation', () => {
it('should complete validation successfully with cleanup', async () => {
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
})
it('should complete validation with passphrase detection with cleanup', async () => {
mockExecuteCommand.mockRejectedValue(new Error('incorrect passphrase'))
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
expect(result.hasPassphrase).toBe(true)
})
})
describe('temp file permission handling', () => {
it('should complete validation which includes writing temp file', async () => {
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
${'A'.repeat(120)}
-----END OPENSSH PRIVATE KEY-----`
const result = await validateSSHPrivateKey(key)
expect(result.valid).toBe(true)
})
})
})