Files
opencode-manager/backend/test/utils/ssh-key-manager.test.ts
T
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

165 lines
5.9 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import * as fs from 'fs/promises'
import { parseSSHHost, normalizeHostPort, parseHostPort, writeTemporarySSHKey, cleanupSSHKey, cleanupAllSSHKeys } from '../../src/utils/ssh-key-manager'
describe('SSH Host Parsing', () => {
it('should parse git@host:path format', () => {
const result = parseSSHHost('git@github.com:user/repo.git')
expect(result.user).toBe('git')
expect(result.host).toBe('github.com')
expect(result.port).toBe('22')
})
it('should parse ssh:// format', () => {
const result = parseSSHHost('ssh://git@gitlab.com/user/repo.git')
expect(result.user).toBe('git')
expect(result.host).toBe('gitlab.com')
expect(result.port).toBe('22')
})
it('should parse ssh:// with custom port', () => {
const result = parseSSHHost('ssh://git@git.example.com:2222/user/repo.git')
expect(result.user).toBe('git')
expect(result.host).toBe('git.example.com')
expect(result.port).toBe('2222')
})
it('should parse git@host:port:path format', () => {
const result = parseSSHHost('git@github.com:22:user/repo.git')
expect(result.user).toBe('git')
expect(result.host).toBe('github.com')
expect(result.port).toBe('22')
})
it('should normalize host:port for non-standard ports', () => {
expect(normalizeHostPort('github.com', '2222')).toBe('github.com:2222')
expect(normalizeHostPort('github.com', '22')).toBe('github.com')
expect(normalizeHostPort('github.com', undefined)).toBe('github.com')
})
it('should parse host:port strings', () => {
expect(parseHostPort('github.com:2222')).toEqual({ host: 'github.com', port: '2222' })
expect(parseHostPort('github.com')).toEqual({ host: 'github.com', port: '22' })
})
})
describe('SSH Key Validation', () => {
describe('RSA Keys', () => {
const rsaKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAzR8u8I5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5
-----END RSA PRIVATE KEY-----`
it('should accept RSA private key', async () => {
const keyPath = await writeTemporarySSHKey(rsaKey, 'test-rsa')
expect(keyPath).toBeTruthy()
const stats = await fs.stat(keyPath)
const mode = stats.mode & 0o777
expect(mode).toBe(0o600)
await cleanupSSHKey(keyPath)
})
it('should accept RSA public key', async () => {
const rsaPublicKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
const keyPath = await writeTemporarySSHKey(rsaPublicKey, 'test-rsa-pub')
expect(keyPath).toBeTruthy()
await cleanupSSHKey(keyPath)
})
})
describe('ED25519 Keys', () => {
const ed25519Key = `-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
-----END OPENSSH PRIVATE KEY-----`
it('should accept ED25519 private key', async () => {
const keyPath = await writeTemporarySSHKey(ed25519Key, 'test-ed25519')
expect(keyPath).toBeTruthy()
await cleanupSSHKey(keyPath)
})
it('should accept ED25519 public key', async () => {
const ed25519PublicKey = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@test.com'
const keyPath = await writeTemporarySSHKey(ed25519PublicKey, 'test-ed25519-pub')
expect(keyPath).toBeTruthy()
await cleanupSSHKey(keyPath)
})
})
describe('ECDSA Keys', () => {
const ecdsaKey = `-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIP5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5
-----END EC PRIVATE KEY-----`
it('should accept ECDSA private key', async () => {
const keyPath = await writeTemporarySSHKey(ecdsaKey, 'test-ecdsa')
expect(keyPath).toBeTruthy()
await cleanupSSHKey(keyPath)
})
it('should accept ECDSA public key', async () => {
const ecdsaPublicKey = 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEM/test@test.com'
const keyPath = await writeTemporarySSHKey(ecdsaPublicKey, 'test-ecdsa-pub')
expect(keyPath).toBeTruthy()
await cleanupSSHKey(keyPath)
})
})
it('should reject invalid key format', async () => {
const invalidKey = 'not a valid ssh key'
await expect(writeTemporarySSHKey(invalidKey, 'test-invalid')).rejects.toThrow('Invalid SSH key format')
})
it('should reject empty key', async () => {
const emptyKey = ''
await expect(writeTemporarySSHKey(emptyKey, 'test-empty')).rejects.toThrow('Invalid SSH key format')
})
it('should set correct permissions on key file', async () => {
const validKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
const keyPath = await writeTemporarySSHKey(validKey, 'test-perms')
const stats = await fs.stat(keyPath)
const mode = stats.mode & 0o777
expect(mode).toBe(0o600)
await cleanupSSHKey(keyPath)
})
})
describe('SSH Key Cleanup', () => {
it('should clean up individual key', async () => {
const key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
const keyPath = await writeTemporarySSHKey(key, 'test-cleanup')
await cleanupSSHKey(keyPath)
await expect(fs.access(keyPath)).rejects.toThrow()
})
it('should clean up all keys', async () => {
const key1 = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test1@host'
const key2 = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test2@test.com'
await writeTemporarySSHKey(key1, 'test-cleanup-1')
await writeTemporarySSHKey(key2, 'test-cleanup-2')
await cleanupAllSSHKeys()
})
it('should handle cleanup of non-existent file gracefully', async () => {
const nonExistentPath = '/tmp/non-existent-ssh-key-12345'
await cleanupSSHKey(nonExistentPath)
})
it('should handle cleanup of already cleaned up file gracefully', async () => {
const key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
const keyPath = await writeTemporarySSHKey(key, 'test-double-cleanup')
await cleanupSSHKey(keyPath)
await cleanupSSHKey(keyPath)
})
})