@haraka/test-fixtures 0.0.0-stage → 2.0.0

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