| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387 |
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
- import { initDb, closeDb, getDb } from '../db';
- import { encrypt, decrypt } from '../utils/crypto';
- // ---------------------------------------------------------------------------
- // Mock AWS SDK – must be declared before importing the module under test
- // ---------------------------------------------------------------------------
- const mockSend = vi.fn();
- vi.mock('@aws-sdk/client-ec2', () => {
- return {
- EC2Client: vi.fn().mockImplementation(() => ({ send: mockSend })),
- RunInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RunInstances', ...p })),
- DescribeInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'DescribeInstances', ...p })),
- GetPasswordDataCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'GetPasswordData', ...p })),
- StopInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'StopInstances', ...p })),
- StartInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'StartInstances', ...p })),
- RebootInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RebootInstances', ...p })),
- TerminateInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'TerminateInstances', ...p })),
- };
- });
- import {
- launchInstance,
- stopInstance,
- startInstance,
- rebootInstance,
- terminateInstance,
- getInstanceRdpInfo,
- loadAwsConfig,
- getMaxLifetimeHours,
- } from './instance-manager';
- // ---------------------------------------------------------------------------
- // Helpers
- // ---------------------------------------------------------------------------
- /** Seed a minimal AWS config row so the service can read it. */
- function seedAwsConfig() {
- const db = getDb();
- db.prepare(
- `INSERT INTO aws_config (access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- ).run('AKIAIOSFODNN7EXAMPLE', encrypt('wJalrXUtnFEMI/K7MDENG'), 'us-east-1', 'ami-12345678', 't3.medium', 'my-key', 'sg-12345');
- }
- /** Insert a system_settings row for max lifetime. */
- function seedMaxLifetime(hours: number) {
- const db = getDb();
- const existing = db.prepare("SELECT id FROM system_settings WHERE key = 'max_instance_lifetime_hours'").get() as any;
- if (existing) {
- db.prepare("UPDATE system_settings SET value = ? WHERE key = 'max_instance_lifetime_hours'").run(String(hours));
- } else {
- db.prepare("INSERT INTO system_settings (key, value) VALUES ('max_instance_lifetime_hours', ?)").run(String(hours));
- }
- }
- /** Insert a user row and return the id. */
- function seedUser(username = 'testuser'): number {
- const db = getDb();
- const result = db.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', 'user')").run(username);
- return Number(result.lastInsertRowid);
- }
- /** Insert an instance row directly for lifecycle tests. */
- function seedInstance(userId: number, overrides: Record<string, any> = {}): number {
- const db = getDb();
- const defaults = {
- ec2_instance_id: 'i-abc123',
- machine_guid: '11111111-1111-1111-1111-111111111111',
- status: 'running',
- public_ip: '1.2.3.4',
- rdp_username: 'Administrator',
- rdp_password_encrypted: encrypt('P@ssw0rd'),
- started_at: Math.floor(Date.now() / 1000),
- expires_at: Math.floor(Date.now() / 1000) + 86400,
- };
- const vals = { ...defaults, ...overrides };
- const result = db
- .prepare(
- `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run(
- userId,
- vals.ec2_instance_id,
- vals.machine_guid,
- vals.status,
- vals.public_ip,
- vals.rdp_username,
- vals.rdp_password_encrypted,
- vals.started_at,
- vals.expires_at,
- );
- return Number(result.lastInsertRowid);
- }
- // ---------------------------------------------------------------------------
- // Setup / Teardown
- // ---------------------------------------------------------------------------
- beforeEach(() => {
- initDb(':memory:');
- mockSend.mockReset();
- });
- afterEach(() => {
- closeDb();
- });
- // ---------------------------------------------------------------------------
- // loadAwsConfig
- // ---------------------------------------------------------------------------
- describe('loadAwsConfig', () => {
- it('should throw when no AWS config exists', () => {
- expect(() => loadAwsConfig()).toThrow('请先配置 AWS 参数');
- });
- it('should return config when properly seeded', () => {
- seedAwsConfig();
- const config = loadAwsConfig();
- expect(config.access_key).toBe('AKIAIOSFODNN7EXAMPLE');
- expect(config.region).toBe('us-east-1');
- expect(config.ami_id).toBe('ami-12345678');
- });
- });
- // ---------------------------------------------------------------------------
- // getMaxLifetimeHours
- // ---------------------------------------------------------------------------
- describe('getMaxLifetimeHours', () => {
- it('should return 24 by default', () => {
- expect(getMaxLifetimeHours()).toBe(24);
- });
- it('should return configured value', () => {
- seedMaxLifetime(48);
- expect(getMaxLifetimeHours()).toBe(48);
- });
- });
- // ---------------------------------------------------------------------------
- // launchInstance
- // ---------------------------------------------------------------------------
- describe('launchInstance', () => {
- it('should launch an instance and return full RDP credentials', async () => {
- seedAwsConfig();
- const userId = seedUser();
- seedMaxLifetime(12);
- // Mock AWS calls in order:
- // 1. RunInstances
- mockSend.mockResolvedValueOnce({
- Instances: [{ InstanceId: 'i-new123' }],
- });
- // 2. DescribeInstances (waitForState polling – already running)
- mockSend.mockResolvedValueOnce({
- Reservations: [{ Instances: [{ State: { Name: 'running' } }] }],
- });
- // 3. DescribeInstances (get public IP)
- mockSend.mockResolvedValueOnce({
- Reservations: [{ Instances: [{ PublicIpAddress: '54.1.2.3' }] }],
- });
- // 4. GetPasswordData
- mockSend.mockResolvedValueOnce({
- PasswordData: 'MyWindowsP@ss',
- });
- const result = await launchInstance(userId, 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', decrypt);
- expect(result.ec2InstanceId).toBe('i-new123');
- expect(result.machineGuid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
- expect(result.status).toBe('running');
- expect(result.publicIp).toBe('54.1.2.3');
- expect(result.rdpUsername).toBe('Administrator');
- expect(result.rdpPassword).toBe('MyWindowsP@ss');
- expect(result.expiresAt).toBe(result.startedAt + 12 * 3600);
- // Verify DB record
- const db = getDb();
- const row = db.prepare('SELECT * FROM instances WHERE ec2_instance_id = ?').get('i-new123') as any;
- expect(row.status).toBe('running');
- expect(row.public_ip).toBe('54.1.2.3');
- expect(row.machine_guid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
- });
- it('should throw when AWS config is missing', async () => {
- const userId = seedUser();
- await expect(launchInstance(userId, '11111111-1111-1111-1111-111111111111', decrypt)).rejects.toThrow(
- '请先配置 AWS 参数',
- );
- });
- it('should throw and mark instance terminated when RunInstances fails', async () => {
- seedAwsConfig();
- const userId = seedUser();
- mockSend.mockRejectedValueOnce(new Error('InsufficientInstanceCapacity'));
- await expect(launchInstance(userId, '11111111-1111-1111-1111-111111111111', decrypt)).rejects.toThrow(
- 'EC2 实例启动失败',
- );
- });
- it('should use default max lifetime of 24 hours when not configured', async () => {
- seedAwsConfig();
- const userId = seedUser();
- mockSend.mockResolvedValueOnce({ Instances: [{ InstanceId: 'i-def456' }] });
- mockSend.mockResolvedValueOnce({
- Reservations: [{ Instances: [{ State: { Name: 'running' } }] }],
- });
- mockSend.mockResolvedValueOnce({
- Reservations: [{ Instances: [{ PublicIpAddress: '10.0.0.1' }] }],
- });
- mockSend.mockResolvedValueOnce({ PasswordData: 'pass123' });
- const result = await launchInstance(userId, '22222222-2222-2222-2222-222222222222', decrypt);
- expect(result.expiresAt).toBe(result.startedAt + 24 * 3600);
- });
- });
- // ---------------------------------------------------------------------------
- // stopInstance
- // ---------------------------------------------------------------------------
- describe('stopInstance', () => {
- it('should stop a running instance', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'running' });
- mockSend.mockResolvedValueOnce({});
- await stopInstance(instId, decrypt);
- const db = getDb();
- const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
- expect(row.status).toBe('stopped');
- });
- it('should throw when instance is not running', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'stopped' });
- await expect(stopInstance(instId, decrypt)).rejects.toThrow('只能关机运行中的实例');
- });
- it('should throw when instance does not exist', async () => {
- seedAwsConfig();
- await expect(stopInstance(9999, decrypt)).rejects.toThrow('实例不存在');
- });
- });
- // ---------------------------------------------------------------------------
- // startInstance
- // ---------------------------------------------------------------------------
- describe('startInstance', () => {
- it('should start a stopped instance', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'stopped' });
- mockSend.mockResolvedValueOnce({});
- await startInstance(instId, decrypt);
- const db = getDb();
- const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
- expect(row.status).toBe('running');
- });
- it('should throw when instance is not stopped', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'running' });
- await expect(startInstance(instId, decrypt)).rejects.toThrow('只能启动已停止的实例');
- });
- });
- // ---------------------------------------------------------------------------
- // rebootInstance
- // ---------------------------------------------------------------------------
- describe('rebootInstance', () => {
- it('should reboot a running instance and keep status as running', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'running' });
- mockSend.mockResolvedValueOnce({});
- await rebootInstance(instId, decrypt);
- const db = getDb();
- const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
- expect(row.status).toBe('running');
- });
- it('should throw when instance is not running', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'stopped' });
- await expect(rebootInstance(instId, decrypt)).rejects.toThrow('只能重启运行中的实例');
- });
- });
- // ---------------------------------------------------------------------------
- // terminateInstance
- // ---------------------------------------------------------------------------
- describe('terminateInstance', () => {
- it('should terminate a running instance', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'running' });
- mockSend.mockResolvedValueOnce({});
- await terminateInstance(instId, decrypt);
- const db = getDb();
- const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
- expect(row.status).toBe('terminated');
- });
- it('should terminate a stopped instance', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'stopped' });
- mockSend.mockResolvedValueOnce({});
- await terminateInstance(instId, decrypt);
- const db = getDb();
- const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
- expect(row.status).toBe('terminated');
- });
- it('should throw when instance is already terminated', async () => {
- seedAwsConfig();
- const userId = seedUser();
- const instId = seedInstance(userId, { status: 'terminated' });
- await expect(terminateInstance(instId, decrypt)).rejects.toThrow('实例已终止');
- });
- });
- // ---------------------------------------------------------------------------
- // getInstanceRdpInfo
- // ---------------------------------------------------------------------------
- describe('getInstanceRdpInfo', () => {
- it('should return decrypted RDP info', () => {
- const userId = seedUser();
- const instId = seedInstance(userId, {
- public_ip: '10.0.0.5',
- rdp_username: 'Administrator',
- rdp_password_encrypted: encrypt('SecretPass!'),
- });
- const info = getInstanceRdpInfo(instId, decrypt);
- expect(info.publicIp).toBe('10.0.0.5');
- expect(info.rdpUsername).toBe('Administrator');
- expect(info.rdpPassword).toBe('SecretPass!');
- });
- it('should throw when instance does not exist', () => {
- expect(() => getInstanceRdpInfo(9999, decrypt)).toThrow('实例不存在');
- });
- it('should return empty password when not set', () => {
- const userId = seedUser();
- const instId = seedInstance(userId, { rdp_password_encrypted: null });
- const info = getInstanceRdpInfo(instId, decrypt);
- expect(info.rdpPassword).toBe('');
- });
- });
|