@haraka/test-fixtures 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,601 @@
1
+ import config from '@haraka/config'
2
+ import * as constants from '@haraka/constants'
3
+ import ipaddr from 'ipaddr.js'
4
+ import Notes from '@haraka/notes'
5
+ import ResultStore from '@haraka/results'
6
+ import * as utils from '@haraka/utils'
7
+
8
+ import logger from './logger.js'
9
+ import * as transaction from './transaction.js'
10
+
11
+ /** @typedef {import('./logger.js').LogMethod} LogMethod */
12
+
13
+ const states = constants.connection.state
14
+
15
+ // Haraka passes the numeric return codes; their names ('deny', ...) work too
16
+ /** @param {number | string | undefined} retval */
17
+ function to_code(retval) {
18
+ return typeof retval === 'string' ? /** @type {any} */ (constants)[retval.toLowerCase()] : retval
19
+ }
20
+
21
+ export class Connection {
22
+ // installed by logger.add_log_methods(); declared for the types
23
+ /** @type {LogMethod} */ logdata
24
+ /** @type {LogMethod} */ logprotocol
25
+ /** @type {LogMethod} */ logdebug
26
+ /** @type {LogMethod} */ loginfo
27
+ /** @type {LogMethod} */ lognotice
28
+ /** @type {LogMethod} */ logwarn
29
+ /** @type {LogMethod} */ logerror
30
+ /** @type {LogMethod} */ logcrit
31
+ /** @type {LogMethod} */ logalert
32
+ /** @type {LogMethod} */ logemerg
33
+
34
+ constructor(client, server, cfg) {
35
+ this.client = client
36
+ this.server = server
37
+ this.cfg = cfg
38
+
39
+ this.local = {
40
+ ip: null,
41
+ port: null,
42
+ host: 'haraka-test.example.com',
43
+ info: 'Haraka',
44
+ }
45
+ this.remote = {
46
+ ip: '127.0.0.1',
47
+ port: null,
48
+ host: null,
49
+ info: null,
50
+ closed: false,
51
+ is_private: false,
52
+ is_local: false,
53
+ }
54
+ this.hello = {
55
+ host: null,
56
+ verb: null,
57
+ }
58
+ this.tls = {
59
+ enabled: false,
60
+ advertised: false,
61
+ verified: false,
62
+ cipher: {},
63
+ }
64
+ this.proxy = {
65
+ allowed: false,
66
+ ip: null,
67
+ type: null,
68
+ timer: null,
69
+ }
70
+ this.set('tls', 'enabled', !!server.has_tls)
71
+
72
+ this.current_data = null
73
+ this.current_line = null
74
+ this.state = states.PAUSE
75
+ this.encoding = 'utf8'
76
+ this.prev_state = null
77
+ this.loop_code = null
78
+ this.loop_msg = null
79
+ this.uuid = utils.uuid()
80
+ this.notes = new Notes()
81
+ this.notes.tls = {}
82
+ this.transaction = null
83
+ this.tran_count = 0
84
+ this.capabilities = null
85
+ this.ehlo_hello_message = 'Haraka Test is at your service.'
86
+ this.connection_close_message = 'closing test connection.'
87
+ this.banner_includes_uuid = true
88
+ this.deny_includes_uuid = true
89
+ this.early_talker = false
90
+ this.pipelining = false
91
+ this._relaying = false
92
+ this.esmtp = false
93
+ this.last_response = null
94
+ this.hooks_to_run = []
95
+ this.start_time = Date.now()
96
+ this.last_reject = ''
97
+ this.max_bytes = 0
98
+ this.max_mime_parts = 1000
99
+ this.totalbytes = 0
100
+ this.rcpt_count = {
101
+ accept: 0,
102
+ tempfail: 0,
103
+ reject: 0,
104
+ }
105
+ this.msg_count = {
106
+ accept: 0,
107
+ tempfail: 0,
108
+ reject: 0,
109
+ }
110
+ this.max_line_length = 512
111
+ this.max_data_line_length = 992
112
+ this.results = new ResultStore(this)
113
+ this.errors = 0
114
+ this.last_rcpt_msg = null
115
+ this.hook = null
116
+ if (this.cfg.headers.show_version) {
117
+ this.local.info += `/${utils.getVersion(import.meta.dirname)}`
118
+ }
119
+
120
+ logger.add_log_methods(this, 'mock-connection')
121
+ Connection.setupClient(this)
122
+ }
123
+
124
+ static setupClient(self) {
125
+ if (Object.keys(self.client).length === 0) return
126
+ const ip = self.client.remoteAddress
127
+ if (!ip) {
128
+ self.logdebug('setupClient got no IP address for this connection!')
129
+ self.client.destroy()
130
+ return
131
+ }
132
+
133
+ const local_addr = (typeof self.server.address === 'function' && self.server.address()) || {
134
+ address: '127.0.0.1',
135
+ port: 25,
136
+ }
137
+ self.set('local', 'ip', ipaddr.process(self.client.localAddress || local_addr.address).toString())
138
+ self.set('local', 'port', self.client.localPort || local_addr.port)
139
+ self.results.add({ name: 'local' }, self.local)
140
+
141
+ self.set('remote', 'ip', ipaddr.process(ip).toString())
142
+ self.set('remote', 'port', self.client.remotePort)
143
+ self.results.add({ name: 'remote' }, self.remote)
144
+
145
+ self.lognotice('connect', {
146
+ ip: self.remote.ip,
147
+ port: self.remote.port,
148
+ local_ip: self.local.ip,
149
+ local_port: self.local.port,
150
+ })
151
+
152
+ if (!self.client.on) return
153
+
154
+ const log_data = { ip: self.remote.ip }
155
+ if (self.remote.host) log_data.host = self.remote.host
156
+
157
+ self.client.on('end', () => {
158
+ if (self.state >= states.DISCONNECTING) return
159
+ self.remote.closed = true
160
+ self.loginfo('client half closed connection', log_data)
161
+ self.fail()
162
+ })
163
+
164
+ self.client.on('close', () => {
165
+ if (self.state >= states.DISCONNECTING) return
166
+ self.remote.closed = true
167
+ self.loginfo('client dropped connection', log_data)
168
+ self.fail()
169
+ })
170
+
171
+ self.client.on('error', (err) => {
172
+ if (self.state >= states.DISCONNECTING) return
173
+ self.loginfo(`client connection error: ${err}`, log_data)
174
+ self.fail()
175
+ })
176
+
177
+ self.client.on('timeout', () => {
178
+ // FIN has sent, when timeout just destroy socket
179
+ if (self.state >= states.DISCONNECTED) {
180
+ self.client.destroy()
181
+ self.loginfo(`timeout, destroy socket (state:${self.state})`)
182
+ return
183
+ }
184
+ if (self.state >= states.DISCONNECTING) return
185
+ self.respond(421, 'timeout', () => {
186
+ self.fail('client connection timed out', log_data)
187
+ })
188
+ })
189
+
190
+ self.client.on('data', (data) => {
191
+ self.process_data(data)
192
+ })
193
+
194
+ // plugins.run_hooks('connect_init', self)
195
+ }
196
+
197
+ setTLS(obj) {
198
+ this.set('hello', 'host', undefined)
199
+ this.set('tls', 'enabled', true)
200
+ for (const t of ['cipher', 'verified', 'verifyError', 'peerCertificate']) {
201
+ if (obj[t] === undefined) continue
202
+ this.set('tls', t, obj[t])
203
+ }
204
+ }
205
+
206
+ set(prop_str, val) {
207
+ if (arguments.length === 3) {
208
+ prop_str = `${arguments[0]}.${arguments[1]}`
209
+ val = arguments[2]
210
+ }
211
+
212
+ const path_parts = prop_str.split('.')
213
+ let loc = this
214
+ for (let i = 0; i < path_parts.length; i++) {
215
+ const part = path_parts[i]
216
+ if (part === '__proto__' || part === 'constructor') continue
217
+
218
+ // while another part remains
219
+ if (i < path_parts.length - 1) {
220
+ if (loc[part] === undefined) loc[part] = {} // initialize
221
+ loc = loc[part] // descend
222
+ continue
223
+ }
224
+
225
+ // last part, so assign the value
226
+ loc[part] = val
227
+ }
228
+ }
229
+
230
+ get(prop_str) {
231
+ return prop_str.split('.').reduce((prev, curr) => {
232
+ return prev ? prev[curr] : undefined
233
+ }, this)
234
+ }
235
+
236
+ set relaying(val) {
237
+ if (this.transaction) {
238
+ this.transaction._relaying = val
239
+ } else {
240
+ this._relaying = val
241
+ }
242
+ }
243
+
244
+ get relaying() {
245
+ if (this.transaction && '_relaying' in this.transaction) return this.transaction._relaying
246
+ return this._relaying
247
+ }
248
+
249
+ auth_results() {}
250
+
251
+ /**
252
+ * @param {string} [err]
253
+ * @param {object} [err_data]
254
+ */
255
+ fail(err, err_data) {
256
+ if (err) this.logwarn(err, err_data)
257
+ this.hooks_to_run = []
258
+ this.disconnect()
259
+ }
260
+
261
+ /**
262
+ * @param {number} code
263
+ * @param {string | string[]} msg
264
+ * @param {() => any} [func]
265
+ */
266
+ respond(code, msg, func) {
267
+ // Haraka's real respond() does not require a callback; several
268
+ // responders (e.g. the mail_respond accept path) call it with none.
269
+ if (typeof func === 'function') return func()
270
+ }
271
+
272
+ /** @param {() => void} [done] */
273
+ init_transaction(done) {
274
+ this.transaction = transaction.createTransaction(null, this.cfg)
275
+ this.transaction.results = new ResultStore(this)
276
+ if (done) done()
277
+ }
278
+
279
+ /** @param {() => void} [done] */
280
+ reset_transaction(done) {
281
+ if (this.transaction && this.transaction.resetting === false) {
282
+ this.transaction.resetting = true
283
+ } else {
284
+ this.transaction = null
285
+ }
286
+ if (done) done()
287
+ }
288
+
289
+ // SMTP State Machine Methods
290
+ pause() {
291
+ if (this.state >= states.DISCONNECTING) return
292
+ if (this.client && this.client.pause) this.client.pause()
293
+ if (this.state !== states.PAUSE_DATA) this.prev_state = this.state
294
+ this.state = states.PAUSE_DATA
295
+ }
296
+
297
+ resume() {
298
+ if (this.state >= states.DISCONNECTING) return
299
+ if (this.client && this.client.resume) this.client.resume()
300
+ if (this.prev_state && this.state === states.PAUSE_DATA) {
301
+ this.state = this.prev_state
302
+ }
303
+ this.prev_state = null
304
+ setImmediate(() => this._process_data())
305
+ }
306
+
307
+ process_data(data) {
308
+ if (!this.current_data || !this.current_data.length) {
309
+ this.current_data = data
310
+ } else {
311
+ // Data left over in buffer
312
+ const buf = Buffer.concat([this.current_data, data], this.current_data.length + data.length)
313
+ this.current_data = buf
314
+ }
315
+ this._process_data()
316
+ }
317
+
318
+ _process_data() {
319
+ // Prevent processing if disconnecting or paused
320
+ if (this.state >= states.DISCONNECTING) return
321
+ if (this.state === states.PAUSE_DATA) return
322
+
323
+ // Simple line processor: split on \n and emit 'line' events
324
+ if (!this.current_data) return
325
+
326
+ const lines = this.current_data.toString().split('\n')
327
+ if (lines[lines.length - 1] !== '') {
328
+ // Last element is incomplete line, keep in buffer
329
+ this.current_data = Buffer.from(lines.pop() || '')
330
+ } else {
331
+ // All complete lines, clear buffer
332
+ this.current_data = null
333
+ }
334
+
335
+ for (const line of lines) {
336
+ if (line !== '') {
337
+ this.process_line(`${line}\n`)
338
+ }
339
+ }
340
+ }
341
+
342
+ process_line(line) {
343
+ if (this.state >= states.DISCONNECTING) return
344
+ this.current_line = line
345
+ // Stub: plugins/tests can override this or listen to 'line' events
346
+ }
347
+
348
+ disconnect() {
349
+ if (this.state >= states.DISCONNECTING) return
350
+ this.state = states.DISCONNECTING
351
+ if (this.transaction) {
352
+ this.transaction = null
353
+ }
354
+ if (this.client && this.client.destroy) {
355
+ this.client.destroy()
356
+ }
357
+ this.loginfo('disconnect')
358
+ }
359
+
360
+ get_capabilities() {
361
+ const capabilities = ['PIPELINING', '8BITMIME', `SIZE ${this.cfg?.main?.max_bytes || 0}`]
362
+ if (this.cfg?.main?.smtputf8) {
363
+ capabilities.push('SMTPUTF8')
364
+ }
365
+ return capabilities
366
+ }
367
+
368
+ // Hook Responder Methods
369
+ /**
370
+ * @param {number | string} [retval] a return code, or its name ('deny', …)
371
+ * @param {string} [msg]
372
+ */
373
+ mail_respond(retval, msg) {
374
+ retval = to_code(retval)
375
+ if (!this.transaction) {
376
+ this.logerror('mail_respond found no transaction!')
377
+ return
378
+ }
379
+ const sender = this.transaction.mail_from
380
+ const dmsg = `sender ${sender.format()}`
381
+
382
+ const store_results = (action) => {
383
+ let addr = sender.format()
384
+ if (addr.length > 2) {
385
+ addr = addr.slice(1, -1) // trim off < >
386
+ }
387
+ if (this.transaction.results) {
388
+ this.transaction.results.add(
389
+ { name: 'mail_from' },
390
+ {
391
+ action,
392
+ address: addr,
393
+ },
394
+ )
395
+ }
396
+ }
397
+
398
+ switch (retval) {
399
+ case constants.deny:
400
+ this.respond(550, msg || `${dmsg} denied`, () => {
401
+ store_results('reject')
402
+ this.reset_transaction()
403
+ })
404
+ break
405
+ case constants.denydisconnect:
406
+ this.respond(550, msg || `${dmsg} denied`, () => {
407
+ store_results('reject')
408
+ this.disconnect()
409
+ })
410
+ break
411
+ case constants.denysoft:
412
+ this.respond(450, msg || `${dmsg} denied`, () => {
413
+ store_results('tempfail')
414
+ this.reset_transaction()
415
+ })
416
+ break
417
+ case constants.denysoftdisconnect:
418
+ this.respond(450, msg || `${dmsg} denied`, () => {
419
+ store_results('tempfail')
420
+ this.disconnect()
421
+ })
422
+ break
423
+ default:
424
+ store_results('accept')
425
+ this.respond(250, msg || `${dmsg} OK`)
426
+ }
427
+ }
428
+
429
+ /**
430
+ * @param {any} rcpt
431
+ * @param {string} action
432
+ * @param {string} [msg]
433
+ */
434
+ rcpt_incr(rcpt, action, msg) {
435
+ this.transaction.rcpt_count[action]++
436
+ this.rcpt_count[action]++
437
+
438
+ const addr = rcpt.format()
439
+ const recipient = {
440
+ address: addr.slice(1, -1),
441
+ action,
442
+ }
443
+
444
+ if (msg && action !== 'accept') {
445
+ recipient.msg = msg
446
+ }
447
+
448
+ if (this.transaction.results) {
449
+ this.transaction.results.push({ name: 'rcpt_to' }, { recipient })
450
+ }
451
+ }
452
+
453
+ /**
454
+ * @param {number | string} [retval] a return code, or its name ('deny', …)
455
+ * @param {string} [msg]
456
+ */
457
+ rcpt_ok_respond(retval, msg) {
458
+ retval = to_code(retval)
459
+ if (!this.transaction) {
460
+ this.logerror('rcpt_ok_respond found no transaction')
461
+ return
462
+ }
463
+ if (!msg) msg = this.last_rcpt_msg
464
+ const rcpt = this.transaction.rcpt_to[this.transaction.rcpt_to.length - 1]
465
+ const dmsg = `recipient ${rcpt.format()}`
466
+
467
+ switch (retval) {
468
+ case constants.deny:
469
+ this.respond(550, msg || `${dmsg} denied`, () => {
470
+ this.rcpt_incr(rcpt, 'reject', msg, retval)
471
+ this.transaction.rcpt_to.pop()
472
+ })
473
+ break
474
+ case constants.denydisconnect:
475
+ this.respond(550, msg || `${dmsg} denied`, () => {
476
+ this.rcpt_incr(rcpt, 'reject', msg, retval)
477
+ this.disconnect()
478
+ })
479
+ break
480
+ case constants.denysoft:
481
+ this.respond(450, msg || `${dmsg} denied`, () => {
482
+ this.rcpt_incr(rcpt, 'tempfail', msg, retval)
483
+ this.transaction.rcpt_to.pop()
484
+ })
485
+ break
486
+ case constants.denysoftdisconnect:
487
+ this.respond(450, msg || `${dmsg} denied`, () => {
488
+ this.rcpt_incr(rcpt, 'tempfail', msg, retval)
489
+ this.disconnect()
490
+ })
491
+ break
492
+ default:
493
+ this.respond(250, msg || `${dmsg} OK`, () => {
494
+ this.rcpt_incr(rcpt, 'accept', msg, retval)
495
+ })
496
+ }
497
+ }
498
+
499
+ /**
500
+ * @param {number | string} [retval] a return code, or its name ('deny', …)
501
+ * @param {string} [msg]
502
+ */
503
+ rcpt_respond(retval, msg) {
504
+ retval = to_code(retval)
505
+ if (retval === constants.cont && this.relaying) retval = constants.ok
506
+
507
+ if (!this.transaction) {
508
+ this.logerror('rcpt_respond found no transaction')
509
+ return
510
+ }
511
+ const rcpt = this.transaction.rcpt_to[this.transaction.rcpt_to.length - 1]
512
+ const dmsg = `recipient ${rcpt.format()}`
513
+ const rej_msg = `I cannot deliver mail for ${rcpt.format()}`
514
+
515
+ switch (retval) {
516
+ case constants.deny:
517
+ this.respond(550, msg || `${dmsg} denied`, () => {
518
+ this.rcpt_incr(rcpt, 'reject', msg, retval)
519
+ this.transaction.rcpt_to.pop()
520
+ })
521
+ break
522
+ case constants.denydisconnect:
523
+ this.respond(550, msg || `${dmsg} denied`, () => {
524
+ this.rcpt_incr(rcpt, 'reject', msg, retval)
525
+ this.disconnect()
526
+ })
527
+ break
528
+ case constants.denysoft:
529
+ this.respond(450, msg || `${dmsg} denied`, () => {
530
+ this.rcpt_incr(rcpt, 'tempfail', msg, retval)
531
+ this.transaction.rcpt_to.pop()
532
+ })
533
+ break
534
+ case constants.denysoftdisconnect:
535
+ this.respond(450, msg || `${dmsg} denied`, () => {
536
+ this.rcpt_incr(rcpt, 'tempfail', msg, retval)
537
+ this.disconnect()
538
+ })
539
+ break
540
+ case constants.ok:
541
+ this.last_rcpt_msg = msg
542
+ break
543
+ default:
544
+ this.respond(550, rej_msg, () => {
545
+ this.rcpt_incr(rcpt, 'reject', rej_msg, retval)
546
+ this.transaction.rcpt_to.pop()
547
+ })
548
+ }
549
+ }
550
+
551
+ /**
552
+ * @param {number | string} [retval] a return code, or its name ('deny', …)
553
+ * @param {string} [msg]
554
+ */
555
+ data_respond(retval, msg) {
556
+ retval = to_code(retval)
557
+ let cont = 0
558
+ switch (retval) {
559
+ case constants.deny:
560
+ this.respond(554, msg || 'Message denied', () => {
561
+ this.reset_transaction()
562
+ })
563
+ break
564
+ case constants.denydisconnect:
565
+ this.respond(554, msg || 'Message denied', () => {
566
+ this.disconnect()
567
+ })
568
+ break
569
+ case constants.denysoft:
570
+ this.respond(451, msg || 'Message denied', () => {
571
+ this.reset_transaction()
572
+ })
573
+ break
574
+ case constants.denysoftdisconnect:
575
+ this.respond(451, msg || 'Message denied', () => {
576
+ this.disconnect()
577
+ })
578
+ break
579
+ default:
580
+ cont = 1
581
+ }
582
+ if (!cont) return
583
+
584
+ // Accept the message for data
585
+ this.respond(354, 'go ahead, make my day', () => {
586
+ this.state = states.DATA
587
+ if (this.transaction) {
588
+ this.transaction.data_bytes = 0
589
+ }
590
+ })
591
+ }
592
+ }
593
+
594
+ export function createConnection(client = {}, server = {}, cfg = {}) {
595
+ if (!cfg || Object.keys(cfg).length === 0) {
596
+ cfg = config.get('smtp.ini', {
597
+ booleans: ['+main.smtputf8', '+headers.add_received', '+headers.clean_auth_results'],
598
+ })
599
+ }
600
+ return new Connection(client, server, cfg)
601
+ }