Repository navigation
Expand file tree
/
Copy pathtest.js
More file actions
1317 lines (1159 loc) · 46.2 KB
/
Copy pathtest.js
File metadata and controls
1317 lines (1159 loc) · 46.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* LambVNC — Handoff Test Suite
*
* Single-file test suite using Node 22's built-in test runner (node:test).
* No test framework dependencies required.
*
* Run: node --test test.js
* Requires: Node 22 (current). node:test, EventTarget, and CustomEvent are
* all stable at this version with no experimental flags needed.
*
* Organisation:
* 1. Security Contract Tests — cryptographic correctness, auth enforcement,
* network binding. These must pass before any
* other review. A failure here is a critical bug.
* 2. Data Integrity Tests — profile persistence, backup on write, audit log
* schema and WAL, config validation.
* 3. Integration Smoke Tests — full server subprocess: login flow, route auth,
* WebSocket upgrade gating, health endpoint, CSP.
* 4. Event Bus Contract Tests — CustomEvent shape, detail payload, emitter/
* listener wiring via jsdom (no browser required).
*
* The tests are intentionally written against module interfaces and the live
* server process — not mocked internals. The goal is to catch seam failures
* (the bugs that live between modules) not to achieve line coverage.
*/
'use strict';
const { test, describe, before, after, beforeEach } = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const net = require('node:net');
const http = require('node:http');
const { spawn } = require('node:child_process');
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Resolve a path relative to the project root.
* Tests live at project root alongside server/ and client/.
*/
const root = (...p) => path.join(__dirname, ...p);
/**
* Make an HTTP request and return { status, headers, body }.
*/
function request(options, body = null) {
return new Promise((resolve, reject) => {
const req = http.request(options, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve({
status: res.statusCode,
headers: res.headers,
body: data
}));
});
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
/**
* Attempt a WebSocket upgrade and return the response status code.
* Does not complete the handshake — only checks whether the upgrade
* was accepted (101) or rejected (401/403).
*/
function wsUpgradeStatus(options) {
return new Promise((resolve, reject) => {
const key = crypto.randomBytes(16).toString('base64');
const req = http.request({
...options,
headers: {
...options.headers,
'Connection': 'Upgrade',
'Upgrade': 'websocket',
'Sec-WebSocket-Key': key,
'Sec-WebSocket-Version': '13',
}
});
req.on('upgrade', (res) => { resolve(101); req.destroy(); });
req.on('response', (res) => { resolve(res.statusCode); });
req.on('error', reject);
req.end();
});
}
/**
* Attempt a raw TCP connection to host:port.
* Resolves true if connection succeeds, false if refused.
*/
function tcpConnectable(host, port) {
return new Promise((resolve) => {
const sock = net.createConnection(port, host);
sock.on('connect', () => { sock.destroy(); resolve(true); });
sock.on('error', () => resolve(false));
setTimeout(() => { sock.destroy(); resolve(false); }, 1000);
});
}
/**
* Spawn the LambVNC server as a subprocess and wait for it to signal ready.
* The server must emit a line containing "LambVNC listening" to stdout.
* Returns { process, port, kill }.
*/
function startServer(configOverrides = {}) {
return new Promise((resolve, reject) => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lambvnc-test-'));
const configPath = path.join(tmpDir, 'config.json');
const config = {
serverPort: 0, // OS-assigned port
sshPort: 0,
basePort: 59100,
tls: false,
sessionTtl: 60,
fadeDuration: 15,
reconnectInterval: 5,
reconnectRetries: 3,
maxHosts: 12,
rateLimitWindow: 900,
rateLimitMax: 100, // relaxed for tests
auditRetentionDays: 90,
...configOverrides,
_testMode: true, // disables first-run password prompt; uses TEST_PASSWORD env
_dataDir: tmpDir,
};
fs.writeFileSync(configPath, JSON.stringify(config));
const proc = spawn('node', [root('server', 'index.js'), '--config', configPath], {
env: {
...process.env,
LAMBVNC_TEST_PASSWORD: 'test-password-correct-horse',
},
stdio: ['ignore', 'pipe', 'pipe']
});
let stdout = '';
let port = null;
let sshPort = null;
let resolved = false;
proc.stdout.on('data', (chunk) => {
stdout += chunk.toString();
// Capture SSH port: "SSH server listening on port XXXX"
const sshMatch = stdout.match(/SSH server listening on port (\d+)/);
if (sshMatch && !sshPort) {
sshPort = parseInt(sshMatch[1], 10);
}
// Capture HTTP port: "LambVNC listening on port XXXX"
const match = stdout.match(/LambVNC listening on port (\d+)/);
if (match && !port) {
port = parseInt(match[1], 10);
}
// Resolve only when both ports are known
if (port && sshPort && !resolved) {
resolved = true;
resolve({
process: proc,
port,
sshPort,
dataDir: tmpDir,
kill: () => new Promise(res => { proc.kill(); proc.on('exit', res); })
});
}
});
proc.on('error', reject);
proc.on('exit', (code) => {
if (!resolved) reject(new Error(`Server exited early (code ${code})\n${stdout}`));
});
setTimeout(() => {
if (!resolved) {
proc.kill();
reject(new Error(`Server did not signal ready within 5s\n${stdout}`));
}
}, 5000);
});
}
/**
* Login to the test server and return the Set-Cookie header value.
*/
async function login(port, password = 'test-password-correct-horse') {
const res = await request({
hostname: '127.0.0.1',
port,
path: '/login',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}, JSON.stringify({ password }));
assert.equal(res.status, 200, `Login failed: ${res.body}`);
return res.headers['set-cookie']?.[0];
}
// ---------------------------------------------------------------------------
// 1. SECURITY CONTRACT TESTS
// These test specific failure modes identified in ARCHITECTURE.md as
// catastrophic. Each maps to a named pitfall in the document.
// ---------------------------------------------------------------------------
describe('Security: AES-256-GCM implementation', () => {
// Load crypto module directly — tests module in isolation
let lambCrypto;
before(() => { lambCrypto = require(root('server', 'crypto.js')); });
test('encrypt then decrypt recovers original plaintext', () => {
const password = 'hunter2-campus-vnc';
const encrypted = lambCrypto.encryptPassword(password);
const recovered = lambCrypto.decryptPassword(encrypted);
assert.equal(recovered, password);
});
test('IV is unique across encryptions — never reused (§6.2)', () => {
// ARCHITECTURE §6.2: "GCM's security model mathematically collapses if
// an IV is ever reused with the same key."
const results = Array.from({ length: 20 }, () =>
lambCrypto.encryptPassword('same-password')
);
const ivs = results.map(r => r.iv);
const unique = new Set(ivs);
assert.equal(unique.size, ivs.length, 'Duplicate IV detected — GCM nonce reuse');
});
test('stored fields are base64 strings, not raw binary (§6.2)', () => {
// ARCHITECTURE §6.2: "The most common AES-GCM implementation failure in
// Node.js... UTF-8 encoding replaces invalid bytes with U+FFFD."
const stored = lambCrypto.encryptPassword('test-password');
const base64Re = /^[A-Za-z0-9+/]+=*$/;
assert.match(stored.iv, base64Re, 'iv is not valid base64');
assert.match(stored.encrypted, base64Re, 'encrypted is not valid base64');
assert.match(stored.tag, base64Re, 'tag is not valid base64');
// Confirm round-trip still works after JSON serialisation
const json = JSON.stringify(stored);
const parsed = JSON.parse(json);
assert.equal(lambCrypto.decryptPassword(parsed), 'test-password');
});
test('tampered ciphertext throws — auth tag is verified, not ignored (§6.2)', () => {
// ARCHITECTURE §6.2: GCM "guarantees both confidentiality and integrity.
// If stored ciphertext is tampered with, decryption fails cryptographically."
const stored = lambCrypto.encryptPassword('precious-password');
// Flip one byte in the ciphertext
const raw = Buffer.from(stored.encrypted, 'base64');
raw[0] ^= 0xff;
const tampered = { ...stored, encrypted: raw.toString('base64') };
assert.throws(
() => lambCrypto.decryptPassword(tampered),
/auth|tag|integrity|bad decrypt/i,
'Tampered ciphertext should throw, not return garbage'
);
});
test('tampered auth tag throws — tag corruption is caught (§6.2)', () => {
const stored = lambCrypto.encryptPassword('precious-password');
const rawTag = Buffer.from(stored.tag, 'base64');
rawTag[0] ^= 0xff;
const tampered = { ...stored, tag: rawTag.toString('base64') };
assert.throws(
() => lambCrypto.decryptPassword(tampered),
/auth|tag|integrity|bad decrypt/i,
'Tampered auth tag should throw'
);
});
});
describe('Security: Network binding — bridges must be localhost-only (§3.4)', () => {
let server;
before(async () => { server = await startServer(); });
after(async () => { await server.kill(); });
test('bridge ports are NOT reachable on 0.0.0.0', async () => {
// ARCHITECTURE §3.4: "Each bridge is bound exclusively to 127.0.0.1 —
// never to the LAN interface."
// We cannot test the actual LAN IP in CI, but we can confirm the port
// is not listening on the wildcard address by connecting to 0.0.0.0.
// Note: on localhost, 0.0.0.0 resolves to the wildcard — if the bridge
// were bound to 0.0.0.0 this would succeed.
const basePort = 5910; // default first bridge port
const reachable = await tcpConnectable('0.0.0.0', basePort);
assert.equal(reachable, false,
`Bridge port ${basePort} is reachable on 0.0.0.0 — should be localhost-only`);
});
test('dashboard port IS reachable on 127.0.0.1', async () => {
const reachable = await tcpConnectable('127.0.0.1', server.port);
assert.equal(reachable, true, 'Dashboard port should be reachable on localhost');
});
});
describe('Security: WebSocket upgrade auth gating (§6.1)', () => {
let server;
before(async () => { server = await startServer(); });
after(async () => { await server.kill(); });
test('upgrade to /ws/:hostId without cookie is rejected 401', async () => {
// ARCHITECTURE §6.1: "No WebSocket connection reaches a bridge without
// passing through this authenticated proxy layer."
const status = await wsUpgradeStatus({
hostname: '127.0.0.1',
port: server.port,
path: '/ws/lab-01',
});
assert.equal(status, 401, `Expected 401 without auth, got ${status}`);
});
test('upgrade to /ws/:hostId with valid cookie is accepted', async () => {
const cookie = await login(server.port);
// Create a host first so the WS path resolves
const createRes = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/api/hosts',
method: 'POST',
headers: { Cookie: cookie, 'Content-Type': 'application/json' },
}, JSON.stringify({
label: 'WS Test', ip: '127.0.0.1', vncPort: 5900,
password: 'test', sshPublicKey: 'ssh-ed25519 AAAA test',
alertTier: 'medium', fadeEnabled: true
}));
const { hostId } = JSON.parse(createRes.body);
// Now attempt upgrade — should get 101 since host exists and has a bridge
const status = await wsUpgradeStatus({
hostname: '127.0.0.1',
port: server.port,
path: `/ws/${hostId}`,
headers: { Cookie: cookie },
});
assert.equal(status, 101, `Expected 101 with valid auth, got ${status}`);
});
test('upgrade with invalid JWT is rejected 401', async () => {
const status = await wsUpgradeStatus({
hostname: '127.0.0.1',
port: server.port,
path: '/ws/lab-01',
headers: { Cookie: 'token=this.is.not.a.valid.jwt' },
});
assert.equal(status, 401);
});
test('/control WebSocket upgrade without cookie is rejected 401', async () => {
const status = await wsUpgradeStatus({
hostname: '127.0.0.1',
port: server.port,
path: '/control',
});
assert.equal(status, 401);
});
});
describe('Security: Authentication — bcrypt + rate limiting (§6.1)', () => {
let server;
before(async () => { server = await startServer({ rateLimitMax: 3, rateLimitWindow: 60 }); });
after(async () => { await server.kill(); });
test('correct password returns 200 and sets cookie', async () => {
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/login',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}, JSON.stringify({ password: 'test-password-correct-horse' }));
assert.equal(res.status, 200);
assert.ok(res.headers['set-cookie']?.[0]?.includes('token='),
'Expected token cookie in response');
});
test('wrong password returns 401', async () => {
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/login',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}, JSON.stringify({ password: 'wrong-password' }));
assert.equal(res.status, 401);
});
test('cookie is httpOnly (§6.1)', async () => {
const cookie = (await request({
hostname: '127.0.0.1',
port: server.port,
path: '/login',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}, JSON.stringify({ password: 'test-password-correct-horse' }))).headers['set-cookie']?.[0];
assert.ok(cookie?.toLowerCase().includes('httponly'),
'JWT cookie must be HttpOnly');
});
test('rate limiter triggers after rateLimitMax failed attempts', async () => {
// Exhaust the limit (set to 3 above)
for (let i = 0; i < 3; i++) {
await request({
hostname: '127.0.0.1',
port: server.port,
path: '/login',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}, JSON.stringify({ password: 'wrong' }));
}
// Next attempt should be rate limited (429)
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/login',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
}, JSON.stringify({ password: 'wrong' }));
assert.equal(res.status, 429, 'Expected 429 after rate limit exceeded');
});
});
describe('Security: Content Security Policy (§4.1)', () => {
let server;
before(async () => { server = await startServer(); });
after(async () => { await server.kill(); });
test('dashboard response includes connect-src CSP header', async () => {
const cookie = await login(server.port);
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/',
headers: { Cookie: cookie },
});
const csp = res.headers['content-security-policy'] ?? '';
assert.ok(csp.includes('connect-src'), 'CSP header must include connect-src');
assert.ok(
csp.includes('ws://localhost') || csp.includes('wss://localhost'),
'connect-src must explicitly allow WebSocket connections to localhost'
);
});
});
// ---------------------------------------------------------------------------
// 2. DATA INTEGRITY TESTS
// ---------------------------------------------------------------------------
describe('Data: profiles.json — backup on write (§10.1)', () => {
let profiles;
let tmpDir;
before(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lambvnc-profiles-'));
profiles = require(root('server', 'profiles.js'));
profiles._setDataDir(tmpDir); // test seam: override data dir
});
test('backup file is created before first write', () => {
const initial = { hosts: {}, monitoringProfiles: {} };
profiles.save(initial);
profiles.save({ hosts: { 'lab-01': { label: 'Test' } }, monitoringProfiles: {} });
const backupExists = fs.existsSync(path.join(tmpDir, 'profiles.json.bak'));
assert.ok(backupExists, 'profiles.json.bak must exist after second write');
});
test('backup contains previous content, not current', () => {
const first = { hosts: { 'original': {} }, monitoringProfiles: {} };
const second = { hosts: { 'updated': {} }, monitoringProfiles: {} };
profiles.save(first);
profiles.save(second);
const bak = JSON.parse(
fs.readFileSync(path.join(tmpDir, 'profiles.json.bak'), 'utf8')
);
assert.ok('original' in bak.hosts, 'Backup should contain the previous write');
assert.ok(!('updated' in bak.hosts), 'Backup must not contain the current write');
});
test('profiles.json structure matches documented schema (§17.1)', () => {
const host = {
label: 'Lab 01',
ip: '192.168.1.101',
vncPort: 5900,
encryptedPassword: 'abc=',
passwordIv: 'def=',
passwordTag: 'ghi=',
sshPublicKey: 'ssh-ed25519 AAAA test',
tunnelPort: 5910,
alertTier: 'medium',
fadeEnabled: true,
};
const data = { hosts: { 'lab-01': host }, monitoringProfiles: {} };
profiles.save(data);
const loaded = profiles.load();
const h = loaded.hosts['lab-01'];
// Assert all documented fields are present and correctly typed
assert.equal(typeof h.label, 'string');
assert.equal(typeof h.ip, 'string');
assert.equal(typeof h.vncPort, 'number');
assert.equal(typeof h.encryptedPassword, 'string');
assert.equal(typeof h.passwordIv, 'string');
assert.equal(typeof h.passwordTag, 'string');
assert.equal(typeof h.sshPublicKey, 'string');
assert.equal(typeof h.tunnelPort, 'number');
assert.ok(['low', 'medium', 'high', 'none'].includes(h.alertTier));
assert.equal(typeof h.fadeEnabled, 'boolean');
});
});
describe('Data: Audit log — SQLite WAL, schema, no-JSON-race (§10.2, §17.2)', () => {
let audit;
let tmpDir;
before(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lambvnc-audit-'));
audit = require(root('server', 'audit.js'));
audit._setDataDir(tmpDir);
audit._init(); // create tables and enable WAL
});
test('WAL mode is enabled', () => {
const mode = audit._getJournalMode();
assert.equal(mode, 'wal', 'SQLite journal_mode must be WAL');
});
test('sessions table has correct columns', () => {
const cols = audit._getColumns('sessions');
const names = cols.map(c => c.name);
assert.ok(names.includes('id'));
assert.ok(names.includes('token_hash'));
assert.ok(names.includes('ip'));
assert.ok(names.includes('logged_in'));
assert.ok(names.includes('logged_out'));
});
test('connections table has correct columns', () => {
const cols = audit._getColumns('connections');
const names = cols.map(c => c.name);
assert.ok(names.includes('id'));
assert.ok(names.includes('session_id'));
assert.ok(names.includes('host_id'));
assert.ok(names.includes('connected'));
assert.ok(names.includes('disconnected'));
});
test('token_hash stores SHA-256 digest, not the raw JWT', () => {
// ARCHITECTURE §17.2: "token_hash stores a SHA-256 digest of the JWT
// rather than the token itself."
const fakeJwt = 'header.payload.signature';
const sessionId = audit.logLogin(fakeJwt, '127.0.0.1');
const row = audit._getSession(sessionId);
assert.notEqual(row.token_hash, fakeJwt, 'Raw JWT must not be stored');
const expectedHash = crypto.createHash('sha256').update(fakeJwt).digest('hex');
assert.equal(row.token_hash, expectedHash, 'token_hash must be SHA-256 of JWT');
});
test('concurrent writes do not corrupt the log', async () => {
// Fire 20 concurrent audit writes and confirm all are recorded
const sessionId = audit.logLogin('concurrent-test-jwt', '127.0.0.1');
await Promise.all(
Array.from({ length: 20 }, (_, i) =>
Promise.resolve(audit.logConnection(sessionId, `host-${i}`))
)
);
const count = audit._countConnections(sessionId);
assert.equal(count, 20, `Expected 20 connection records, got ${count}`);
});
});
describe('Data: Config validation — fail loud at startup (§15)', () => {
let validateConfig;
before(() => { validateConfig = require(root('server', 'index.js'))._validateConfig; });
const validConfig = {
serverPort: 3000, sshPort: 2222, basePort: 5910,
tls: false, sessionTtl: 28800, fadeDuration: 15,
reconnectInterval: 5, reconnectRetries: 3, maxHosts: 12,
rateLimitWindow: 900, rateLimitMax: 10, auditRetentionDays: 90,
};
test('valid config passes without throwing', () => {
assert.doesNotThrow(() => validateConfig(validConfig));
});
test('fadeDuration as string throws with field name in message', () => {
assert.throws(
() => validateConfig({ ...validConfig, fadeDuration: 'fifteen' }),
/fadeDuration/,
'Error must identify the invalid field'
);
});
test('sshPort below 1024 throws', () => {
assert.throws(
() => validateConfig({ ...validConfig, sshPort: 80 }),
/sshPort/
);
});
test('maxHosts above 12 throws', () => {
assert.throws(
() => validateConfig({ ...validConfig, maxHosts: 13 }),
/maxHosts/
);
});
test('tls: true without tlsCert throws', () => {
assert.throws(
() => validateConfig({ ...validConfig, tls: true, tlsKey: '/path/key.pem' }),
/tlsCert/
);
});
test('missing optional fields use defaults', () => {
const minimal = { ...validConfig };
delete minimal.fadeDuration;
const result = validateConfig(minimal);
assert.equal(result.fadeDuration, 15, 'fadeDuration should default to 15');
});
});
// ---------------------------------------------------------------------------
// 3. INTEGRATION SMOKE TESTS
// Full server subprocess. Tests the paths that cross module boundaries.
// ---------------------------------------------------------------------------
describe('Integration: Route auth surface (§18)', () => {
let server;
before(async () => { server = await startServer(); });
after(async () => { await server.kill(); });
const protectedRoutes = [
['GET', '/api/hosts'],
['GET', '/api/profiles'],
['GET', '/health'],
];
for (const [method, path] of protectedRoutes) {
test(`${method} ${path} without auth returns 401`, async () => {
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path,
method,
});
assert.equal(res.status, 401, `${method} ${path} should require auth`);
});
}
test('GET /login returns 200 without auth', async () => {
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/login',
});
assert.equal(res.status, 200);
});
test('full login → authenticated request flow', async () => {
const cookie = await login(server.port);
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/api/hosts',
headers: { Cookie: cookie },
});
assert.equal(res.status, 200);
const body = JSON.parse(res.body);
assert.ok('hosts' in body, 'GET /api/hosts should return hosts key');
});
test('POST /logout clears cookie', async () => {
const cookie = await login(server.port);
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/logout',
method: 'POST',
headers: { Cookie: cookie },
});
assert.equal(res.status, 200);
const setCookie = res.headers['set-cookie']?.[0] ?? '';
// Cookie should be cleared (Max-Age=0 or Expires in the past)
assert.ok(
setCookie.includes('Max-Age=0') || setCookie.includes('Expires=Thu, 01 Jan 1970'),
'Logout must clear the token cookie'
);
});
});
describe('Integration: Host profile CRUD → health reflection (§16, §18)', () => {
let server;
let cookie;
before(async () => {
server = await startServer();
cookie = await login(server.port);
});
after(async () => { await server.kill(); });
const testHost = {
label: 'Integration Test Machine',
ip: '192.168.1.200',
vncPort: 5900,
password: 'test-vnc-password',
sshPublicKey: 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA test@integration',
alertTier: 'medium',
fadeEnabled: true,
};
test('POST /api/hosts creates a host and returns hostId', async () => {
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/api/hosts',
method: 'POST',
headers: { Cookie: cookie, 'Content-Type': 'application/json' },
}, JSON.stringify(testHost));
assert.equal(res.status, 201);
const body = JSON.parse(res.body);
assert.ok(body.hostId, 'Response must include hostId');
// Store for subsequent tests
this.hostId = body.hostId;
});
test('VNC password is stored encrypted, not plaintext (§6.2)', async () => {
// Read profiles.json directly and confirm password is not plaintext
const profilesPath = path.join(server.dataDir, 'profiles.json');
const profiles = JSON.parse(fs.readFileSync(profilesPath, 'utf8'));
const hostIds = Object.keys(profiles.hosts);
assert.ok(hostIds.length > 0, 'Host should have been persisted');
const host = profiles.hosts[hostIds[0]];
assert.ok(host.encryptedPassword, 'encryptedPassword field must exist');
assert.ok(host.passwordIv, 'passwordIv field must exist');
assert.ok(host.passwordTag, 'passwordTag field must exist');
assert.ok(
!JSON.stringify(profiles).includes(testHost.password),
'Plaintext VNC password must not appear anywhere in profiles.json'
);
});
test('GET /health returns valid structure after host added', async () => {
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/health',
headers: { Cookie: cookie },
});
assert.equal(res.status, 200);
const body = JSON.parse(res.body);
assert.equal(body.status, 'ok', 'health.status must be ok');
assert.ok(Array.isArray(body.tunnels), 'health.tunnels must be an array');
assert.equal(typeof body.uptime, 'number', 'health.uptime must be a number');
assert.equal(typeof body.activeSessions, 'number', 'health.activeSessions must be a number');
assert.equal(typeof body.auditLogSize, 'number', 'health.auditLogSize must be a number');
});
test('profiles.json.bak exists after host creation', () => {
const bakPath = path.join(server.dataDir, 'profiles.json.bak');
assert.ok(fs.existsSync(bakPath), 'profiles.json.bak must exist after write');
});
test('DELETE /api/hosts/:hostId removes host', async () => {
// Use hostId from first test (stored on this — may need to re-fetch)
const listRes = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/api/hosts',
headers: { Cookie: cookie },
});
const { hosts } = JSON.parse(listRes.body);
const hostId = Object.keys(hosts)[0];
const delRes = await request({
hostname: '127.0.0.1',
port: server.port,
path: `/api/hosts/${hostId}`,
method: 'DELETE',
headers: { Cookie: cookie },
});
assert.equal(delRes.status, 200);
const afterRes = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/api/hosts',
headers: { Cookie: cookie },
});
const after = JSON.parse(afterRes.body);
assert.ok(!(hostId in after.hosts), 'Deleted host must not appear in subsequent GET');
});
});
describe('Integration: Port collision — fail loud at startup (§3.5, §15)', () => {
test('server exits non-zero if a bridge port is already bound', async () => {
// Pre-occupy the base port
const blocker = net.createServer();
await new Promise(res => blocker.listen(5910, '127.0.0.1', res));
try {
await assert.rejects(
() => startServer({ basePort: 5910 }),
/exited early|port.*in use|EADDRINUSE/i,
'Server must fail loud when bridge port is already bound'
);
} finally {
await new Promise(res => blocker.close(res));
}
});
});
// ---------------------------------------------------------------------------
// 5. SSH SENDER AUTHENTICATION TESTS
// Uses ssh2 Client (already a project dependency) to test the actual
// SSH public key authentication path end-to-end.
// ---------------------------------------------------------------------------
describe('Security: SSH sender authentication (§3.7)', () => {
const { Client, utils: sshUtils } = require('ssh2');
let server;
let cookie;
let registeredHostId;
let testKeyPair;
before(async () => {
testKeyPair = sshUtils.generateKeyPairSync('ed25519');
server = await startServer();
cookie = await login(server.port);
// Register a host with the generated public key
const res = await request({
hostname: '127.0.0.1',
port: server.port,
path: '/api/hosts',
method: 'POST',
headers: { Cookie: cookie, 'Content-Type': 'application/json' },
}, JSON.stringify({
label: 'SSH Test Sender',
ip: '127.0.0.1',
vncPort: 5900,
password: 'irrelevant',
sshPublicKey: testKeyPair.public,
alertTier: 'medium',
fadeEnabled: true,
}));
registeredHostId = JSON.parse(res.body).hostId;
});
after(async () => { await server.kill(); });
test('sender with registered key is authenticated and port forward accepted', async () => {
// Fetch the tunnel port assigned to this host
const hostsRes = await request({
hostname: '127.0.0.1', port: server.port,
path: '/api/hosts', headers: { Cookie: cookie }
});
const { hosts } = JSON.parse(hostsRes.body);
const tunnelPort = hosts[registeredHostId].tunnelPort;
await new Promise((resolve, reject) => {
const client = new Client();
client.on('ready', () => {
client.forwardIn('127.0.0.1', tunnelPort, (err) => {
client.end();
if (err) reject(new Error(`Port forward rejected: ${err.message}`));
else resolve();
});
});
client.on('error', (err) => {
reject(new Error(`SSH auth failed — key comparison broken: ${err.message}`));
});
client.connect({
host: '127.0.0.1',
port: server.sshPort,
username: 'sender',
privateKey: testKeyPair.private,
});
});
});
test('sender with unregistered key is rejected', async () => {
const foreignKey = sshUtils.generateKeyPairSync('ed25519');
await new Promise((resolve, reject) => {
const client = new Client();
client.on('ready', () => {
client.end();
reject(new Error('Unregistered key should have been rejected'));
});
client.on('error', () => {
// Expected — unregistered key must be refused
resolve();
});
client.connect({
host: '127.0.0.1',
port: server.sshPort,
username: 'sender',
privateKey: foreignKey.private,
});
});
});
test('port forward to wrong port is rejected', async () => {
await new Promise((resolve, reject) => {
const client = new Client();
client.on('ready', () => {
// Try to forward on a port that doesn't match the host's tunnelPort
client.forwardIn('127.0.0.1', 9999, (err) => {
client.end();
if (err) resolve(); // Expected: rejected
else reject(new Error('Port forward to wrong port should have been rejected'));
});
});
client.on('error', (err) => {
reject(new Error(`SSH connection failed: ${err.message}`));
});
client.connect({
host: '127.0.0.1',
port: server.sshPort,
username: 'sender',
privateKey: testKeyPair.private,
});
});
});
test('tunnel port is bound and data flows end-to-end after port forward (§3.6)', async () => {
// This test catches the bug where tcpip-forward is accept()ed but no TCP
// socket is actually bound on the server, causing ECONNREFUSED when the
// proxy attempts to connect to the tunnel port.
// 1. Fake "VNC server" on the sender side — echoes anything it receives.
const echoServer = net.createServer((sock) => { sock.pipe(sock); });
const echoPort = await new Promise(res =>
echoServer.listen(0, '127.0.0.1', () => res(echoServer.address().port))
);
// 2. Look up tunnel port assigned to the registered host.
const hostsRes = await request({
hostname: '127.0.0.1', port: server.port,
path: '/api/hosts', headers: { Cookie: cookie }
});
const { hosts } = JSON.parse(hostsRes.body);
const tunnelPort = hosts[registeredHostId].tunnelPort;
try {
await new Promise((resolve, reject) => {
const sshClient = new Client();
sshClient.on('ready', () => {
// 3. Ask the server to listen on the tunnel port (SSH -R).
sshClient.forwardIn('127.0.0.1', tunnelPort, (err) => {
if (err) return reject(new Error(`forwardIn rejected: ${err.message}`));
// forwardIn accepted — now verify the port is actually bound by
// attempting a real TCP connection from outside.
// Give the server a tick to finish binding.
setTimeout(() => {
const probe = net.createConnection(tunnelPort, '127.0.0.1');
probe.on('error', (err) => {
sshClient.end();
reject(new Error(`Tunnel port not bound after forwardIn: ${err.message}`));
});
probe.on('connect', () => {
probe.destroy();
sshClient.end();
resolve();
});
setTimeout(() => {
probe.destroy();
sshClient.end();
reject(new Error('Probe connection to tunnel port timed out'));
}, 2000);
}, 100);
});
});
// 4. When the server sends a forwarded connection over the SSH channel,
// pipe it to the local echo server (simulating TightVNC).