forked from steelbrain/node-ssh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain-test.ts
More file actions
511 lines (477 loc) · 17.6 KB
/
Copy pathmain-test.ts
File metadata and controls
511 lines (477 loc) · 17.6 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
import invariant from 'assert'
import test, { ExecutionContext } from 'ava'
import ChildProcess from 'child_process'
import fs from 'fs'
import path from 'path'
import { Server } from 'ssh2'
import { NodeSSH } from '../src'
import { PRIVATE_KEY_PATH, exists, wait } from './helpers'
import createServer from './ssh-server'
let ports = 8876
function getFixturePath(fixturePath: string): string {
return path.join(__dirname, 'fixtures', fixturePath)
}
function sshit(
title: string,
callback: (t: ExecutionContext<unknown>, port: number, client: NodeSSH, server: Server) => Promise<void>,
skip = false,
): void {
const testFunc = skip ? test.skip : test
testFunc(title, async function (t) {
ports += 1
const server = createServer()
const client = new NodeSSH()
const port = ports
await new Promise<void>(function (resolve) {
server.listen(port, '127.0.0.1', resolve)
})
try {
await callback(t, port, client, server)
} finally {
client.dispose()
await new Promise(function (resolve) {
server.close(resolve)
})
}
})
}
async function connectWithPassword(port, client) {
await client.connect({
host: '127.0.0.1',
port,
username: 'steel',
password: 'password',
})
}
async function connectWithPrivateKey(port, client) {
await client.connect({
host: '127.0.0.1',
port,
username: 'steel',
privateKeyPath: PRIVATE_KEY_PATH,
})
}
async function connectWithInlinePrivateKey(port, client) {
await client.connect({
host: '127.0.0.1',
port,
username: 'steel',
privateKey: fs.readFileSync(PRIVATE_KEY_PATH, 'utf8'),
})
}
test.after(function () {
ChildProcess.exec(`rm -rf ${getFixturePath('ignored/*')}`)
ChildProcess.exec(`rm -rf ${getFixturePath('ignored-2/*')}`)
})
test.before(function () {
ChildProcess.exec(`rm -rf ${getFixturePath('ignored/*')}`)
ChildProcess.exec(`rm -rf ${getFixturePath('ignored-2/*')}`)
})
sshit('connects to a server with password', async function (t, port, client) {
await t.notThrowsAsync(async function () {
await connectWithPassword(port, client)
})
})
sshit('connects to a server with a private key', async function (t, port, client) {
await t.notThrowsAsync(async function () {
await connectWithPrivateKey(port, client)
})
})
sshit('connects to a server with an inline private key', async function (t, port, client) {
await t.notThrowsAsync(async function () {
await connectWithInlinePrivateKey(port, client)
})
})
sshit(
'requests a shell that works',
async function (t, port, client) {
await connectWithPassword(port, client)
const data: Buffer[] = []
const shell = await client.requestShell()
shell.on('data', function (chunk) {
data.push(chunk)
})
shell.write('ls /\n')
await wait(50)
shell.end()
const joinedData = data.join('')
t.regex(joinedData, /ls \//)
},
true,
)
sshit('creates directories with sftp properly', async function (t, port, client) {
await connectWithPassword(port, client)
t.is(await exists(getFixturePath('ignored/a/b')), false)
await client.mkdir(getFixturePath('ignored/a/b'), 'sftp')
t.is(await exists(getFixturePath('ignored/a/b')), true)
})
sshit('creates directories with exec properly', async function (t, port, client) {
await connectWithPassword(port, client)
t.is(await exists(getFixturePath('ignored/a/b')), false)
await client.mkdir(getFixturePath('ignored/a/b'), 'exec')
t.is(await exists(getFixturePath('ignored/a/b')), true)
})
sshit('throws error when it cant create directories', async function (t, port, client) {
await connectWithPassword(port, client)
try {
await client.mkdir('/etc/passwd/asdasdasd')
t.is(false, true)
} catch (_) {
t.is(_.message.indexOf('ENOTDIR: not a directory') !== -1, true)
}
})
sshit('exec with correct escaped parameters', async function (t, port, client) {
await connectWithPassword(port, client)
const result = await client.exec('echo', ['$some', 'S\\Thing', '"Yo"'])
t.is(result, '$some S\\Thing "Yo"')
})
sshit('exec with correct cwd', async function (t, port, client) {
await connectWithPassword(port, client)
const result = await client.exec('pwd', [], { cwd: '/etc' })
t.is(result, '/etc')
})
sshit('throws if stream is stdout and stuff is written to stderr', async function (t, port, client) {
await connectWithPassword(port, client)
try {
await client.exec('node', ['-e', 'console.error("Test")'])
t.is(false, true)
} catch (_) {
t.is(_.message, 'Test')
}
})
sshit('does not throw if stream is stderr and is written to', async function (t, port, client) {
await connectWithPassword(port, client)
const result = await client.exec('node', ['-e', 'console.error("Test")'], { stream: 'stderr' })
t.is(result, 'Test')
})
sshit('returns both streams if asked to', async function (t, port, client) {
await connectWithPassword(port, client)
const result = await client.exec('node', ['-e', 'console.log("STDOUT"); console.error("STDERR")'], { stream: 'both' })
invariant(typeof result === 'object' && result)
t.is(result.stdout, 'STDOUT')
// STDERR tests are flaky on CI
if (!process.env.CI) {
t.is(result.stderr, 'STDERR')
}
})
sshit('writes to stdin properly', async function (t, port, client) {
await connectWithPassword(port, client)
const result = await client.exec('node', ['-e', 'process.stdin.pipe(process.stdout)'], { stdin: 'Twinkle!\nStars!' })
t.is(result, 'Twinkle!\nStars!')
})
sshit('gets files properly', async function (t, port, client) {
await connectWithPassword(port, client)
const sourceFile = __filename
const targetFile = getFixturePath('ignored/test-get')
t.is(await exists(targetFile), false)
await client.getFile(targetFile, sourceFile)
t.is(await exists(targetFile), true)
t.is(fs.readFileSync(targetFile, 'utf8').trim(), fs.readFileSync(sourceFile, 'utf8').trim())
})
sshit('puts files properly', async function (t, port, client) {
await connectWithPassword(port, client)
const sourceFile = __filename
const targetFile = getFixturePath('ignored/test-get')
t.is(await exists(targetFile), false)
await client.putFile(sourceFile, targetFile)
t.is(await exists(targetFile), true)
t.is(fs.readFileSync(targetFile, 'utf8').trim(), fs.readFileSync(sourceFile, 'utf8').trim())
})
sshit('puts multiple files properly', async function (t, port, client) {
await connectWithPassword(port, client)
const files = [
{ local: getFixturePath('multiple/aa'), remote: getFixturePath('ignored/aa') },
{ local: getFixturePath('multiple/bb'), remote: getFixturePath('ignored/bb') },
{ local: getFixturePath('multiple/cc'), remote: getFixturePath('ignored/cc') },
{ local: getFixturePath('multiple/dd'), remote: getFixturePath('ignored/dd') },
{ local: getFixturePath('multiple/ff'), remote: getFixturePath('ignored/ff') },
{ local: getFixturePath('multiple/gg'), remote: getFixturePath('ignored/gg') },
{ local: getFixturePath('multiple/hh'), remote: getFixturePath('ignored/hh') },
{ local: getFixturePath('multiple/ii'), remote: getFixturePath('ignored/ii') },
{ local: getFixturePath('multiple/jj'), remote: getFixturePath('ignored/jj') },
]
const existsBefore = await Promise.all(files.map((file) => exists(file.remote)))
t.is(existsBefore.every(Boolean), false)
await client.putFiles(files)
const existsAfter = await Promise.all(files.map((file) => exists(file.remote)))
t.is(existsAfter.every(Boolean), true)
})
sshit('puts entire directories at once', async function (t, port, client) {
await connectWithPassword(port, client)
const remoteFiles = [
getFixturePath('ignored/aa'),
getFixturePath('ignored/bb'),
getFixturePath('ignored/cc'),
getFixturePath('ignored/dd'),
getFixturePath('ignored/ee/ff'),
getFixturePath('ignored/ff'),
getFixturePath('ignored/gg'),
getFixturePath('ignored/hh'),
getFixturePath('ignored/ii'),
getFixturePath('ignored/jj'),
getFixturePath('ignored/really/really/really/really/really/more deep files'),
getFixturePath('ignored/really/really/really/really/yes/deep files'),
getFixturePath('ignored/really/really/really/really/deep'),
]
const filesReceived: string[] = []
const existsBefore = await Promise.all(remoteFiles.map((file) => exists(file)))
t.is(existsBefore.every(Boolean), false)
await client.putDirectory(getFixturePath('multiple'), getFixturePath('ignored'), {
tick(local, remote, error) {
t.is(error, null)
t.is(remoteFiles.indexOf(remote) !== -1, true)
filesReceived.push(remote)
},
})
remoteFiles.sort()
filesReceived.sort()
t.deepEqual(remoteFiles, filesReceived)
const existsAfter = await Promise.all(remoteFiles.map((file) => exists(file)))
t.is(existsAfter.every(Boolean), true)
})
sshit('gets entire directories at once', async function (t, port, client) {
await connectWithPassword(port, client)
const localFiles = [
getFixturePath('ignored-2/aa'),
getFixturePath('ignored-2/bb'),
getFixturePath('ignored-2/cc'),
getFixturePath('ignored-2/dd'),
getFixturePath('ignored-2/ee/ff'),
getFixturePath('ignored-2/ff'),
getFixturePath('ignored-2/gg'),
getFixturePath('ignored-2/hh'),
getFixturePath('ignored-2/ii'),
getFixturePath('ignored-2/jj'),
getFixturePath('ignored-2/really/really/really/really/really/more deep files'),
getFixturePath('ignored-2/really/really/really/really/yes/deep files'),
getFixturePath('ignored-2/really/really/really/really/deep'),
]
const filesReceived: string[] = []
const existsBefore = await Promise.all(localFiles.map((file) => exists(file)))
t.is(existsBefore.every(Boolean), false)
await client.getDirectory(getFixturePath('ignored-2'), getFixturePath('multiple'), {
tick(local, remote, error) {
t.is(error, null)
t.is(localFiles.indexOf(local) !== -1, true)
filesReceived.push(local)
},
})
localFiles.sort()
filesReceived.sort()
t.deepEqual(localFiles, filesReceived)
const existsAfter = await Promise.all(localFiles.map((file) => exists(file)))
t.is(existsAfter.every(Boolean), true)
})
sshit('allows stream callbacks on exec', async function (t, port, client) {
await connectWithPassword(port, client)
const outputFromCallbacks = { stdout: [] as Buffer[], stderr: [] as Buffer[] }
await client.exec('node', [getFixturePath('test-program')], {
stream: 'both',
onStderr(chunk) {
outputFromCallbacks.stderr.push(chunk)
},
onStdout(chunk) {
outputFromCallbacks.stdout.push(chunk)
},
})
t.is(outputFromCallbacks.stdout.join('').trim(), 'STDOUT')
// STDERR tests are flaky on CI
if (!process.env.CI) {
t.is(outputFromCallbacks.stderr.join('').trim(), 'STDERR')
}
})
sshit('allows stream callbacks on execCommand', async function (t, port, client) {
await connectWithPassword(port, client)
const outputFromCallbacks = { stdout: [] as Buffer[], stderr: [] as Buffer[] }
await client.execCommand(`node ${getFixturePath('test-program')}`, {
onStderr(chunk) {
outputFromCallbacks.stderr.push(chunk)
},
onStdout(chunk) {
outputFromCallbacks.stdout.push(chunk)
},
})
t.is(outputFromCallbacks.stdout.join('').trim(), 'STDOUT')
// STDERR tests are flaky on CI
if (!process.env.CI) {
t.is(outputFromCallbacks.stderr.join('').trim(), 'STDERR')
}
})
sshit('forwards an outbound TCP/IP connection from client', async function (t, port, client, server) {
const SRC_IP = '127.0.0.1'
const SRC_PORT = 1212
const DEST_IP = '127.0.0.2'
const DEST_PORT = 2424
await new Promise((resolve) => {
server.on('connection', async (connection) => {
connection.once('ready', async () => {
const channel = await client.forwardOut(SRC_IP, SRC_PORT, DEST_IP, DEST_PORT)
t.true(channel.readable)
resolve(undefined)
})
// Approve first TCP/IP request.
connection.once('tcpip', (accept, reject, info) => {
t.is(info.destIP, DEST_IP)
t.is(info.destPort, DEST_PORT)
t.is(info.srcIP, SRC_IP)
t.is(info.srcPort, SRC_PORT)
accept()
})
})
connectWithPassword(port, client)
})
})
sshit('forwards an inbound TCP/IP connection to client', async function (t, port, client, server) {
const IP = '127.0.0.1'
const PORT = 1212
const REMOTE_IP = '127.0.0.2'
const REMOTE_PORT = 2424
await new Promise((resolve) => {
server.on('connection', async (connection) => {
connection.once('ready', async () => {
// Wait for a connection.
const { port: forwardPort, dispose } = await client.forwardIn(IP, PORT, (details) => {
t.is(details.destIP, IP)
t.is(details.destPort, PORT)
t.is(details.srcIP, REMOTE_IP)
t.is(details.srcPort, REMOTE_PORT)
// Expect to get an unforward request on server.
connection.once('request', (accept, reject, name, info) => {
t.is(name, 'cancel-tcpip-forward')
t.is(info.bindAddr, IP)
t.is(info.bindPort, PORT)
accept()
resolve(undefined)
})
setTimeout(() => dispose(), 100)
})
t.truthy(dispose)
t.is(forwardPort, PORT)
})
// Expect to get a request on server.
connection.once('request', (accept, reject, name, info) => {
t.is(name, 'tcpip-forward')
t.is(info.bindAddr, IP)
t.is(info.bindPort, PORT)
accept?.(PORT)
// Simulate a connection
connection.forwardOut(info.bindAddr, info.bindPort, REMOTE_IP, REMOTE_PORT, () => {
// Nothing more to be done here.
})
})
})
connectWithPassword(port, client)
})
})
sshit('forwards an outbound UNIX socket connection from client', async function (t, port, client, server) {
const PATH = '/run/test.sock'
await new Promise((resolve) => {
server.on('connection', async (connection) => {
connection.once('ready', async () => {
const channel = await client.forwardOutStreamLocal(PATH)
t.true(channel.readable)
resolve(undefined)
})
// Approve first UNIX socket request.
connection.once('openssh.streamlocal', (accept, reject, info) => {
t.is(info.socketPath, PATH)
accept()
})
})
connectWithPassword(port, client)
})
})
sshit('forwards an inbound UNIX socket connection to client', async function (t, port, client, server) {
const PATH = '/run/test.sock'
await new Promise((resolve) => {
server.on('connection', async (connection) => {
connection.once('ready', async () => {
// Wait for a connection.
const { dispose } = await client.forwardInStreamLocal(PATH, (details) => {
t.is(details.socketPath, PATH)
// Expect to get an unforward request on server.
connection.once('request', (accept, reject, name, info) => {
t.is(name, 'cancel-streamlocal-forward@openssh.com')
t.is(info.socketPath, PATH)
accept()
resolve(undefined)
})
setTimeout(() => dispose(), 100)
})
t.truthy(dispose)
})
// Expect to get a request on server.
connection.once('request', (accept, reject, name, info) => {
t.is(name, 'streamlocal-forward@openssh.com')
t.is(info.socketPath, PATH)
accept?.()
// Simulate a connection
connection.openssh_forwardOutStreamLocal(PATH, () => {
// Nothing more to be done here.
})
})
})
connectWithPassword(port, client)
})
})
sshit('forwards an inbound TCP/IP connection to client with automatically assigned port', async function (
t,
port,
client,
server,
) {
const IP = '127.0.0.1'
const PORT = 1212
const REMOTE_IP = '127.0.0.2'
const REMOTE_PORT = 2424
await new Promise((resolve) => {
server.on('connection', async (connection) => {
connection.once('ready', async () => {
// Wait for a connection.
const { port: forwardPort, dispose } = await client.forwardIn(IP, 0, (details) => {
t.is(details.destIP, IP)
t.is(details.destPort, PORT)
t.is(details.srcIP, REMOTE_IP)
t.is(details.srcPort, REMOTE_PORT)
// Expect to get an unforward request on server.
connection.once('request', (accept, reject, name, info) => {
t.is(name, 'cancel-tcpip-forward')
t.is(info.bindAddr, IP)
t.is(info.bindPort, PORT)
accept()
resolve(undefined)
})
setTimeout(() => dispose(), 100)
})
t.truthy(dispose)
t.is(forwardPort, PORT)
})
// Expect to get a request on server.
connection.once('request', (accept, reject, name, info) => {
t.is(name, 'tcpip-forward')
t.is(info.bindAddr, IP)
// Port equal to 0 -> server chooses the port dynamically.
t.is(info.bindPort, 0)
accept?.(PORT)
// Simulate a connection
connection.forwardOut(info.bindAddr, PORT, REMOTE_IP, REMOTE_PORT, () => {
// Nothing more to be done here.
})
})
})
connectWithPassword(port, client)
})
})
sshit('has a working noTrim option', async function (t, port, client) {
await connectWithPassword(port, client)
const resultWithTrim = await client.exec('echo', ["\nhello\n\n\n\n"], {stream: 'stdout'})
t.is(resultWithTrim, 'hello')
const resultWithoutTrim = await client.exec('echo', ['\n\n\nhi\n\n\n'], {stream: 'stdout', noTrim: true})
t.is(resultWithoutTrim, '\n\n\nhi\n\n\n\n')
const commandResult = await client.execCommand(
'node -e "process.stdout.write(\'\\nstdout\\n\\n\'); process.stderr.write(\'\\nstderr\\n\\n\')"',
{ noTrim: true },
)
t.is(commandResult.stdout, '\nstdout\n\n')
t.is(commandResult.stderr, '\nstderr\n\n')
})