db.test.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import { describe, it, expect, afterEach } from 'vitest';
  2. import bcrypt from 'bcrypt';
  3. import { initDb, getDb, closeDb } from './db';
  4. describe('Database Module', () => {
  5. afterEach(() => {
  6. closeDb();
  7. });
  8. it('should initialize an in-memory database', () => {
  9. const db = initDb(':memory:');
  10. expect(db).toBeDefined();
  11. expect(db.open).toBe(true);
  12. });
  13. it('should create all tables', () => {
  14. const db = initDb(':memory:');
  15. const tables = db
  16. .prepare(
  17. "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
  18. )
  19. .all() as { name: string }[];
  20. const tableNames = tables.map((t) => t.name).sort();
  21. expect(tableNames).toEqual([
  22. 'aws_config',
  23. 'instance_logs',
  24. 'instances',
  25. 'invitation_codes',
  26. 'rdp_sessions',
  27. 'system_settings',
  28. 'user_machine_guids',
  29. 'users',
  30. ]);
  31. });
  32. it('should create default admin user on first init', () => {
  33. const db = initDb(':memory:');
  34. const admin = db
  35. .prepare("SELECT * FROM users WHERE username = 'admin'")
  36. .get() as any;
  37. expect(admin).toBeDefined();
  38. expect(admin.username).toBe('admin');
  39. expect(admin.role).toBe('admin');
  40. expect(bcrypt.compareSync('admin123', admin.password_hash)).toBe(true);
  41. });
  42. it('should not create duplicate admin on re-init', () => {
  43. const db = initDb(':memory:');
  44. // Simulate re-init by calling seedDefaultAdmin logic again
  45. // We can't re-init the same in-memory db, but we can verify
  46. // that calling initDb on a db that already has an admin doesn't duplicate
  47. const countBefore = (
  48. db.prepare("SELECT COUNT(*) as cnt FROM users WHERE role = 'admin'").get() as any
  49. ).cnt;
  50. // Manually call the seed logic again by re-running initDb tables + seed
  51. // Since the tables already exist (IF NOT EXISTS), this is safe
  52. db.exec(`
  53. CREATE TABLE IF NOT EXISTS users (
  54. id INTEGER PRIMARY KEY AUTOINCREMENT,
  55. username TEXT NOT NULL UNIQUE,
  56. password_hash TEXT NOT NULL,
  57. role TEXT NOT NULL CHECK(role IN ('admin', 'user')),
  58. created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
  59. );
  60. `);
  61. const adminExists = db
  62. .prepare("SELECT id FROM users WHERE role = 'admin' LIMIT 1")
  63. .get();
  64. // Admin already exists, so no new insert should happen
  65. expect(adminExists).toBeDefined();
  66. const countAfter = (
  67. db.prepare("SELECT COUNT(*) as cnt FROM users WHERE role = 'admin'").get() as any
  68. ).cnt;
  69. expect(countAfter).toBe(countBefore);
  70. });
  71. it('getDb should throw if not initialized', () => {
  72. expect(() => getDb()).toThrow('Database not initialized');
  73. });
  74. it('getDb should return the initialized database', () => {
  75. initDb(':memory:');
  76. const db = getDb();
  77. expect(db).toBeDefined();
  78. expect(db.open).toBe(true);
  79. });
  80. it('should enforce foreign key constraints on instances table', () => {
  81. const db = initDb(':memory:');
  82. expect(() => {
  83. db.prepare(
  84. "INSERT INTO instances (user_id, status) VALUES (9999, 'pending')"
  85. ).run();
  86. }).toThrow();
  87. });
  88. it('should enforce status check constraint on instances', () => {
  89. const db = initDb(':memory:');
  90. const admin = db.prepare("SELECT id FROM users WHERE username = 'admin'").get() as any;
  91. expect(() => {
  92. db.prepare(
  93. "INSERT INTO instances (user_id, status) VALUES (?, 'invalid_status')"
  94. ).run(admin.id);
  95. }).toThrow();
  96. });
  97. it('should enforce role check constraint on users', () => {
  98. const db = initDb(':memory:');
  99. expect(() => {
  100. db.prepare(
  101. "INSERT INTO users (username, password_hash, role) VALUES ('test', 'hash', 'superadmin')"
  102. ).run();
  103. }).toThrow();
  104. });
  105. it('should enforce unique username constraint', () => {
  106. const db = initDb(':memory:');
  107. expect(() => {
  108. db.prepare(
  109. "INSERT INTO users (username, password_hash, role) VALUES ('admin', 'hash', 'user')"
  110. ).run();
  111. }).toThrow();
  112. });
  113. it('should enforce unique invitation code constraint', () => {
  114. const db = initDb(':memory:');
  115. db.prepare("INSERT INTO invitation_codes (code) VALUES ('CODE1')").run();
  116. expect(() => {
  117. db.prepare("INSERT INTO invitation_codes (code) VALUES ('CODE1')").run();
  118. }).toThrow();
  119. });
  120. it('should seed default guacamole_host and guacamole_port settings', () => {
  121. const db = initDb(':memory:');
  122. const host = db
  123. .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_host'")
  124. .get() as any;
  125. const port = db
  126. .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_port'")
  127. .get() as any;
  128. expect(host).toBeDefined();
  129. expect(host.value).toBe('127.0.0.1');
  130. expect(port).toBeDefined();
  131. expect(port.value).toBe('4822');
  132. });
  133. it('should not overwrite existing guacamole settings on re-init', () => {
  134. const db = initDb(':memory:');
  135. // Update the values to something custom
  136. db.prepare("UPDATE system_settings SET value = '10.0.0.1' WHERE key = 'guacamole_host'").run();
  137. db.prepare("UPDATE system_settings SET value = '9999' WHERE key = 'guacamole_port'").run();
  138. // Re-run the seed (INSERT OR IGNORE should not overwrite)
  139. db.prepare("INSERT OR IGNORE INTO system_settings (key, value) VALUES ('guacamole_host', '127.0.0.1')").run();
  140. db.prepare("INSERT OR IGNORE INTO system_settings (key, value) VALUES ('guacamole_port', '4822')").run();
  141. const host = db
  142. .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_host'")
  143. .get() as any;
  144. const port = db
  145. .prepare("SELECT value FROM system_settings WHERE key = 'guacamole_port'")
  146. .get() as any;
  147. expect(host.value).toBe('10.0.0.1');
  148. expect(port.value).toBe('9999');
  149. });
  150. it('closeDb should close the database connection', () => {
  151. initDb(':memory:');
  152. closeDb();
  153. expect(() => getDb()).toThrow('Database not initialized');
  154. });
  155. });