instance-manager.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
  2. import { initDb, closeDb, getDb } from '../db';
  3. import { encrypt, decrypt } from '../utils/crypto';
  4. // ---------------------------------------------------------------------------
  5. // Mock AWS SDK – must be declared before importing the module under test
  6. // ---------------------------------------------------------------------------
  7. const mockSend = vi.fn();
  8. vi.mock('@aws-sdk/client-ec2', () => {
  9. return {
  10. EC2Client: vi.fn().mockImplementation(() => ({ send: mockSend })),
  11. RunInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RunInstances', ...p })),
  12. DescribeInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'DescribeInstances', ...p })),
  13. GetPasswordDataCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'GetPasswordData', ...p })),
  14. StopInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'StopInstances', ...p })),
  15. StartInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'StartInstances', ...p })),
  16. RebootInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'RebootInstances', ...p })),
  17. TerminateInstancesCommand: vi.fn().mockImplementation((p: any) => ({ _type: 'TerminateInstances', ...p })),
  18. };
  19. });
  20. import {
  21. launchInstance,
  22. stopInstance,
  23. startInstance,
  24. rebootInstance,
  25. terminateInstance,
  26. getInstanceRdpInfo,
  27. loadAwsConfig,
  28. getMaxLifetimeHours,
  29. } from './instance-manager';
  30. // ---------------------------------------------------------------------------
  31. // Helpers
  32. // ---------------------------------------------------------------------------
  33. /** Seed a minimal AWS config row so the service can read it. */
  34. function seedAwsConfig() {
  35. const db = getDb();
  36. db.prepare(
  37. `INSERT INTO aws_config (access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id)
  38. VALUES (?, ?, ?, ?, ?, ?, ?)`,
  39. ).run('AKIAIOSFODNN7EXAMPLE', encrypt('wJalrXUtnFEMI/K7MDENG'), 'us-east-1', 'ami-12345678', 't3.medium', 'my-key', 'sg-12345');
  40. }
  41. /** Insert a system_settings row for max lifetime. */
  42. function seedMaxLifetime(hours: number) {
  43. const db = getDb();
  44. const existing = db.prepare("SELECT id FROM system_settings WHERE key = 'max_instance_lifetime_hours'").get() as any;
  45. if (existing) {
  46. db.prepare("UPDATE system_settings SET value = ? WHERE key = 'max_instance_lifetime_hours'").run(String(hours));
  47. } else {
  48. db.prepare("INSERT INTO system_settings (key, value) VALUES ('max_instance_lifetime_hours', ?)").run(String(hours));
  49. }
  50. }
  51. /** Insert a user row and return the id. */
  52. function seedUser(username = 'testuser'): number {
  53. const db = getDb();
  54. const result = db.prepare("INSERT INTO users (username, password_hash, role) VALUES (?, 'hash', 'user')").run(username);
  55. return Number(result.lastInsertRowid);
  56. }
  57. /** Insert an instance row directly for lifecycle tests. */
  58. function seedInstance(userId: number, overrides: Record<string, any> = {}): number {
  59. const db = getDb();
  60. const defaults = {
  61. ec2_instance_id: 'i-abc123',
  62. machine_guid: '11111111-1111-1111-1111-111111111111',
  63. status: 'running',
  64. public_ip: '1.2.3.4',
  65. rdp_username: 'Administrator',
  66. rdp_password_encrypted: encrypt('P@ssw0rd'),
  67. started_at: Math.floor(Date.now() / 1000),
  68. expires_at: Math.floor(Date.now() / 1000) + 86400,
  69. };
  70. const vals = { ...defaults, ...overrides };
  71. const result = db
  72. .prepare(
  73. `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, public_ip, rdp_username, rdp_password_encrypted, started_at, expires_at)
  74. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  75. )
  76. .run(
  77. userId,
  78. vals.ec2_instance_id,
  79. vals.machine_guid,
  80. vals.status,
  81. vals.public_ip,
  82. vals.rdp_username,
  83. vals.rdp_password_encrypted,
  84. vals.started_at,
  85. vals.expires_at,
  86. );
  87. return Number(result.lastInsertRowid);
  88. }
  89. // ---------------------------------------------------------------------------
  90. // Setup / Teardown
  91. // ---------------------------------------------------------------------------
  92. beforeEach(() => {
  93. initDb(':memory:');
  94. mockSend.mockReset();
  95. });
  96. afterEach(() => {
  97. closeDb();
  98. });
  99. // ---------------------------------------------------------------------------
  100. // loadAwsConfig
  101. // ---------------------------------------------------------------------------
  102. describe('loadAwsConfig', () => {
  103. it('should throw when no AWS config exists', () => {
  104. expect(() => loadAwsConfig()).toThrow('请先配置 AWS 参数');
  105. });
  106. it('should return config when properly seeded', () => {
  107. seedAwsConfig();
  108. const config = loadAwsConfig();
  109. expect(config.access_key).toBe('AKIAIOSFODNN7EXAMPLE');
  110. expect(config.region).toBe('us-east-1');
  111. expect(config.ami_id).toBe('ami-12345678');
  112. });
  113. });
  114. // ---------------------------------------------------------------------------
  115. // getMaxLifetimeHours
  116. // ---------------------------------------------------------------------------
  117. describe('getMaxLifetimeHours', () => {
  118. it('should return 24 by default', () => {
  119. expect(getMaxLifetimeHours()).toBe(24);
  120. });
  121. it('should return configured value', () => {
  122. seedMaxLifetime(48);
  123. expect(getMaxLifetimeHours()).toBe(48);
  124. });
  125. });
  126. // ---------------------------------------------------------------------------
  127. // launchInstance
  128. // ---------------------------------------------------------------------------
  129. describe('launchInstance', () => {
  130. it('should launch an instance and return full RDP credentials', async () => {
  131. seedAwsConfig();
  132. const userId = seedUser();
  133. seedMaxLifetime(12);
  134. // Mock AWS calls in order:
  135. // 1. RunInstances
  136. mockSend.mockResolvedValueOnce({
  137. Instances: [{ InstanceId: 'i-new123' }],
  138. });
  139. // 2. DescribeInstances (waitForState polling – already running)
  140. mockSend.mockResolvedValueOnce({
  141. Reservations: [{ Instances: [{ State: { Name: 'running' } }] }],
  142. });
  143. // 3. DescribeInstances (get public IP)
  144. mockSend.mockResolvedValueOnce({
  145. Reservations: [{ Instances: [{ PublicIpAddress: '54.1.2.3' }] }],
  146. });
  147. // 4. GetPasswordData
  148. mockSend.mockResolvedValueOnce({
  149. PasswordData: 'MyWindowsP@ss',
  150. });
  151. const result = await launchInstance(userId, 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', decrypt);
  152. expect(result.ec2InstanceId).toBe('i-new123');
  153. expect(result.machineGuid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
  154. expect(result.status).toBe('running');
  155. expect(result.publicIp).toBe('54.1.2.3');
  156. expect(result.rdpUsername).toBe('Administrator');
  157. expect(result.rdpPassword).toBe('MyWindowsP@ss');
  158. expect(result.expiresAt).toBe(result.startedAt + 12 * 3600);
  159. // Verify DB record
  160. const db = getDb();
  161. const row = db.prepare('SELECT * FROM instances WHERE ec2_instance_id = ?').get('i-new123') as any;
  162. expect(row.status).toBe('running');
  163. expect(row.public_ip).toBe('54.1.2.3');
  164. expect(row.machine_guid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee');
  165. });
  166. it('should throw when AWS config is missing', async () => {
  167. const userId = seedUser();
  168. await expect(launchInstance(userId, '11111111-1111-1111-1111-111111111111', decrypt)).rejects.toThrow(
  169. '请先配置 AWS 参数',
  170. );
  171. });
  172. it('should throw and mark instance terminated when RunInstances fails', async () => {
  173. seedAwsConfig();
  174. const userId = seedUser();
  175. mockSend.mockRejectedValueOnce(new Error('InsufficientInstanceCapacity'));
  176. await expect(launchInstance(userId, '11111111-1111-1111-1111-111111111111', decrypt)).rejects.toThrow(
  177. 'EC2 实例启动失败',
  178. );
  179. });
  180. it('should use default max lifetime of 24 hours when not configured', async () => {
  181. seedAwsConfig();
  182. const userId = seedUser();
  183. mockSend.mockResolvedValueOnce({ Instances: [{ InstanceId: 'i-def456' }] });
  184. mockSend.mockResolvedValueOnce({
  185. Reservations: [{ Instances: [{ State: { Name: 'running' } }] }],
  186. });
  187. mockSend.mockResolvedValueOnce({
  188. Reservations: [{ Instances: [{ PublicIpAddress: '10.0.0.1' }] }],
  189. });
  190. mockSend.mockResolvedValueOnce({ PasswordData: 'pass123' });
  191. const result = await launchInstance(userId, '22222222-2222-2222-2222-222222222222', decrypt);
  192. expect(result.expiresAt).toBe(result.startedAt + 24 * 3600);
  193. });
  194. });
  195. // ---------------------------------------------------------------------------
  196. // stopInstance
  197. // ---------------------------------------------------------------------------
  198. describe('stopInstance', () => {
  199. it('should stop a running instance', async () => {
  200. seedAwsConfig();
  201. const userId = seedUser();
  202. const instId = seedInstance(userId, { status: 'running' });
  203. mockSend.mockResolvedValueOnce({});
  204. await stopInstance(instId, decrypt);
  205. const db = getDb();
  206. const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
  207. expect(row.status).toBe('stopped');
  208. });
  209. it('should throw when instance is not running', async () => {
  210. seedAwsConfig();
  211. const userId = seedUser();
  212. const instId = seedInstance(userId, { status: 'stopped' });
  213. await expect(stopInstance(instId, decrypt)).rejects.toThrow('只能关机运行中的实例');
  214. });
  215. it('should throw when instance does not exist', async () => {
  216. seedAwsConfig();
  217. await expect(stopInstance(9999, decrypt)).rejects.toThrow('实例不存在');
  218. });
  219. });
  220. // ---------------------------------------------------------------------------
  221. // startInstance
  222. // ---------------------------------------------------------------------------
  223. describe('startInstance', () => {
  224. it('should start a stopped instance', async () => {
  225. seedAwsConfig();
  226. const userId = seedUser();
  227. const instId = seedInstance(userId, { status: 'stopped' });
  228. mockSend.mockResolvedValueOnce({});
  229. await startInstance(instId, decrypt);
  230. const db = getDb();
  231. const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
  232. expect(row.status).toBe('running');
  233. });
  234. it('should throw when instance is not stopped', async () => {
  235. seedAwsConfig();
  236. const userId = seedUser();
  237. const instId = seedInstance(userId, { status: 'running' });
  238. await expect(startInstance(instId, decrypt)).rejects.toThrow('只能启动已停止的实例');
  239. });
  240. });
  241. // ---------------------------------------------------------------------------
  242. // rebootInstance
  243. // ---------------------------------------------------------------------------
  244. describe('rebootInstance', () => {
  245. it('should reboot a running instance and keep status as running', async () => {
  246. seedAwsConfig();
  247. const userId = seedUser();
  248. const instId = seedInstance(userId, { status: 'running' });
  249. mockSend.mockResolvedValueOnce({});
  250. await rebootInstance(instId, decrypt);
  251. const db = getDb();
  252. const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
  253. expect(row.status).toBe('running');
  254. });
  255. it('should throw when instance is not running', async () => {
  256. seedAwsConfig();
  257. const userId = seedUser();
  258. const instId = seedInstance(userId, { status: 'stopped' });
  259. await expect(rebootInstance(instId, decrypt)).rejects.toThrow('只能重启运行中的实例');
  260. });
  261. });
  262. // ---------------------------------------------------------------------------
  263. // terminateInstance
  264. // ---------------------------------------------------------------------------
  265. describe('terminateInstance', () => {
  266. it('should terminate a running instance', async () => {
  267. seedAwsConfig();
  268. const userId = seedUser();
  269. const instId = seedInstance(userId, { status: 'running' });
  270. mockSend.mockResolvedValueOnce({});
  271. await terminateInstance(instId, decrypt);
  272. const db = getDb();
  273. const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
  274. expect(row.status).toBe('terminated');
  275. });
  276. it('should terminate a stopped instance', async () => {
  277. seedAwsConfig();
  278. const userId = seedUser();
  279. const instId = seedInstance(userId, { status: 'stopped' });
  280. mockSend.mockResolvedValueOnce({});
  281. await terminateInstance(instId, decrypt);
  282. const db = getDb();
  283. const row = db.prepare('SELECT status FROM instances WHERE id = ?').get(instId) as any;
  284. expect(row.status).toBe('terminated');
  285. });
  286. it('should throw when instance is already terminated', async () => {
  287. seedAwsConfig();
  288. const userId = seedUser();
  289. const instId = seedInstance(userId, { status: 'terminated' });
  290. await expect(terminateInstance(instId, decrypt)).rejects.toThrow('实例已终止');
  291. });
  292. });
  293. // ---------------------------------------------------------------------------
  294. // getInstanceRdpInfo
  295. // ---------------------------------------------------------------------------
  296. describe('getInstanceRdpInfo', () => {
  297. it('should return decrypted RDP info', () => {
  298. const userId = seedUser();
  299. const instId = seedInstance(userId, {
  300. public_ip: '10.0.0.5',
  301. rdp_username: 'Administrator',
  302. rdp_password_encrypted: encrypt('SecretPass!'),
  303. });
  304. const info = getInstanceRdpInfo(instId, decrypt);
  305. expect(info.publicIp).toBe('10.0.0.5');
  306. expect(info.rdpUsername).toBe('Administrator');
  307. expect(info.rdpPassword).toBe('SecretPass!');
  308. });
  309. it('should throw when instance does not exist', () => {
  310. expect(() => getInstanceRdpInfo(9999, decrypt)).toThrow('实例不存在');
  311. });
  312. it('should return empty password when not set', () => {
  313. const userId = seedUser();
  314. const instId = seedInstance(userId, { rdp_password_encrypted: null });
  315. const info = getInstanceRdpInfo(instId, decrypt);
  316. expect(info.rdpPassword).toBe('');
  317. });
  318. });