imap_spec.rb 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rails_helper'
  3. RSpec.describe Channel::Driver::Imap, integration: true, required_envs: %w[MAIL_SERVER MAIL_ADDRESS MAIL_PASS MAIL_ADDRESS_ASCII MAIL_PASS_ASCII] do
  4. # https://github.com/zammad/zammad/issues/2964
  5. context 'when connecting with a ASCII 8-Bit password' do
  6. it 'succeeds' do
  7. params = {
  8. host: ENV['MAIL_SERVER'],
  9. user: ENV['MAIL_ADDRESS_ASCII'],
  10. password: ENV['MAIL_PASS_ASCII'],
  11. ssl_verify: false,
  12. }
  13. result = described_class.new.fetch(params, nil, 'check')
  14. expect(result[:result]).to eq 'ok'
  15. end
  16. end
  17. describe '.parse_rfc822_headers' do
  18. it 'parses simple header' do
  19. expect(described_class.parse_rfc822_headers('Key: Value')).to have_key('Key').and(have_value('Value'))
  20. end
  21. it 'parses header with no white space' do
  22. expect(described_class.parse_rfc822_headers('Key:Value')).to have_key('Key').and(have_value('Value'))
  23. end
  24. it 'parses multiline header' do
  25. expect(described_class.parse_rfc822_headers("Key: Value\r\n2nd-key: 2nd-value"))
  26. .to have_key('Key').and(have_value('Value')).and(have_key('2nd-key')).and(have_value('2nd-value'))
  27. end
  28. it 'parses value with semicolons' do
  29. expect(described_class.parse_rfc822_headers('Key: Val:ue')).to have_key('Key').and(have_value('Val:ue'))
  30. end
  31. it 'parses key-only lines' do
  32. expect(described_class.parse_rfc822_headers('Key')).to have_key('Key')
  33. end
  34. it 'handles empty line' do
  35. expect { described_class.parse_rfc822_headers("Key: Value\r\n") }.not_to raise_error
  36. end
  37. it 'handles tabbed value' do
  38. expect(described_class.parse_rfc822_headers("Key: \r\n\tValue")).to have_key('Key').and(have_value('Value'))
  39. end
  40. end
  41. describe '.extract_rfc822_headers' do
  42. it 'extracts header' do
  43. object = Net::IMAP::FetchData.new :id, { 'RFC822.HEADER' => 'Key: Value' }
  44. expect(described_class.extract_rfc822_headers(object)).to have_key('Key').and(have_value('Value'))
  45. end
  46. it 'returns nil when header attribute is missing' do
  47. object = Net::IMAP::FetchData.new :id, { 'Another' => 'Key: Value' }
  48. expect(described_class.extract_rfc822_headers(object)).to be_nil
  49. end
  50. it 'does not raise error when given nil' do
  51. expect { described_class.extract_rfc822_headers(nil) }.not_to raise_error
  52. end
  53. end
  54. describe '.fetch', :aggregate_failures do
  55. let(:folder) { "imap_spec-#{SecureRandom.uuid}" }
  56. let(:server_address) { ENV['MAIL_SERVER'] }
  57. let(:server_login) { ENV['MAIL_ADDRESS'] }
  58. let(:server_password) { ENV['MAIL_PASS'] }
  59. let(:email_address) { create(:email_address, name: 'Zammad Helpdesk', email: "some-zammad-#{ENV['MAIL_ADDRESS']}") }
  60. let(:group) { create(:group, email_address: email_address) }
  61. let(:inbound_options) do
  62. {
  63. adapter: 'imap',
  64. options: {
  65. host: ENV['MAIL_SERVER'],
  66. user: ENV['MAIL_ADDRESS'],
  67. password: server_password,
  68. ssl: true,
  69. ssl_verify: false,
  70. folder: folder,
  71. keep_on_server: false,
  72. }
  73. }
  74. end
  75. let(:outbound_options) do
  76. {
  77. adapter: 'smtp',
  78. options: {
  79. host: server_address,
  80. port: 25,
  81. start_tls: true,
  82. ssl_verify: false,
  83. user: server_login,
  84. password: server_password,
  85. email: email_address.email
  86. },
  87. }
  88. end
  89. let(:channel) do
  90. create(:email_channel, group: group, inbound: inbound_options, outbound: outbound_options).tap do |channel|
  91. email_address.channel = channel
  92. email_address.save!
  93. end
  94. end
  95. let(:imap) { Net::IMAP.new(server_address, port: 993, ssl: { verify_mode: OpenSSL::SSL::VERIFY_NONE }).tap { |imap| imap.login(server_login, server_password) } }
  96. let(:purge_inbox) do
  97. imap.select('inbox')
  98. imap.sort(['DATE'], ['ALL'], 'US-ASCII').each do |msg|
  99. imap.store(msg, '+FLAGS', [:Deleted])
  100. end
  101. imap.expunge
  102. end
  103. before do
  104. purge_inbox
  105. imap.create(folder)
  106. imap.select(folder)
  107. end
  108. after do
  109. imap.delete(folder)
  110. end
  111. context 'when fetching regular emails' do
  112. let(:email1) do
  113. <<~EMAIL.gsub(%r{\n}, "\r\n")
  114. Subject: hello1
  115. From: shugo@example.com
  116. To: shugo@example.com
  117. Message-ID: <some1@example_keep_on_server>
  118. hello world
  119. EMAIL
  120. end
  121. let(:email2) do
  122. <<~EMAIL.gsub(%r{\n}, "\r\n")
  123. Subject: hello2
  124. From: shugo@example.com
  125. To: shugo@example.com
  126. Message-ID: <some2@example_keep_on_server>
  127. hello world
  128. EMAIL
  129. end
  130. context 'with keep_on_server flag' do
  131. let(:inbound_options) do
  132. {
  133. adapter: 'imap',
  134. options: {
  135. host: ENV['MAIL_SERVER'],
  136. user: ENV['MAIL_ADDRESS'],
  137. password: server_password,
  138. ssl: true,
  139. ssl_verify: false,
  140. folder: folder,
  141. keep_on_server: true,
  142. }
  143. }
  144. end
  145. it 'handles messages correctly' do # rubocop:disable RSpec/ExampleLength
  146. imap.append(folder, email1, [], Time.zone.now)
  147. # verify if message is still on server
  148. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  149. expect(message_ids.count).to be(1)
  150. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  151. expect(message_meta['FLAGS']).not_to include(:Seen)
  152. # fetch messages - will import
  153. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  154. # verify if message is still on server
  155. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  156. expect(message_ids.count).to be(1)
  157. # message now has :seen flag
  158. message_meta = imap.fetch(1, ['RFC822.HEADER', 'FLAGS'])[0].attr
  159. expect(message_meta['FLAGS']).to include(:Seen)
  160. # fetch messages - will not import
  161. expect { channel.fetch(true) }.not_to change(Ticket::Article, :count)
  162. # verify if message is still on server
  163. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  164. expect(message_ids.count).to be(1)
  165. # put unseen message in it
  166. imap.append(folder, email2, [], Time.zone.now)
  167. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  168. expect(message_meta['FLAGS']).to include(:Seen)
  169. message_meta = imap.fetch(2, ['FLAGS'])[0].attr
  170. expect(message_meta['FLAGS']).not_to include(:Seen)
  171. # fetch messages - will import new
  172. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  173. # verify if message is still on server
  174. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  175. expect(message_ids.count).to be(2)
  176. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  177. expect(message_meta['FLAGS']).to include(:Seen)
  178. message_meta = imap.fetch(2, ['FLAGS'])[0].attr
  179. expect(message_meta['FLAGS']).to include(:Seen)
  180. # set messages to not seen
  181. imap.store(1, '-FLAGS', [:Seen])
  182. imap.store(2, '-FLAGS', [:Seen])
  183. # fetch messages - will still not import
  184. expect { channel.fetch(true) }.not_to change(Ticket::Article, :count)
  185. end
  186. end
  187. context 'without keep_on_server flag' do
  188. it 'handles messages correctly' do
  189. imap.append(folder, email1, [], Time.zone.now)
  190. # verify if message is still on server
  191. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  192. expect(message_ids.count).to be(1)
  193. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  194. expect(message_meta['FLAGS']).not_to include(:Seen)
  195. # fetch messages - will import
  196. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  197. # verify if message is still on server
  198. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  199. expect(message_ids.count).to be(1)
  200. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  201. expect(message_meta['FLAGS']).to include(:Seen, :Deleted)
  202. # put unseen message in it
  203. imap.append(folder, email2, [], Time.zone.now)
  204. # verify if message is still on server
  205. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  206. expect(message_ids.count).to be(1)
  207. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  208. expect(message_meta['FLAGS']).not_to include(:Seen)
  209. # fetch messages - will import
  210. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  211. # verify if message is still on server
  212. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  213. expect(message_ids.count).to be(1)
  214. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  215. expect(message_meta['FLAGS']).to include(:Seen)
  216. end
  217. end
  218. end
  219. context 'when fetching oversized emails' do
  220. let(:sender_email_address) { ENV['MAIL_ADDRESS'] }
  221. let(:cid) { SecureRandom.uuid.tr('-', '.') }
  222. let(:oversized_email) do
  223. <<~OVERSIZED_EMAIL.gsub(%r{\n}, "\r\n")
  224. Subject: Oversized Email Message
  225. From: Max Mustermann <#{sender_email_address}>
  226. To: shugo@example.com
  227. Message-ID: <#{cid}@zammad.test.com>
  228. Oversized Email Message Body #{'#' * 120_000}
  229. OVERSIZED_EMAIL
  230. end
  231. let(:oversized_email_md5) { Digest::MD5.hexdigest(oversized_email) }
  232. let(:oversized_email_size) { format('%<MB>.2f', MB: oversized_email.size.to_f / 1024 / 1024) }
  233. let(:fetch_oversized_email) do
  234. imap.append(folder, oversized_email, [], Time.zone.now)
  235. channel.fetch(true)
  236. end
  237. context 'with email reply' do
  238. before do
  239. Setting.set('postmaster_max_size', 0.1)
  240. fetch_oversized_email
  241. end
  242. let(:oversized_email_reply) do
  243. imap.select('inbox')
  244. 5.times do |i|
  245. sleep i
  246. msg = imap.sort(['DATE'], ['ALL'], 'US-ASCII').first
  247. if msg
  248. return imap.fetch(msg, 'RFC822')[0].attr['RFC822']
  249. end
  250. end
  251. nil
  252. end
  253. let(:parsed_oversized_email_reply) do
  254. Channel::EmailParser.new.parse(oversized_email_reply)
  255. end
  256. it 'creates email reply correctly' do
  257. # verify that a postmaster response email has been sent to the sender
  258. expect(oversized_email_reply).to be_present
  259. # parse the reply mail and verify the various headers
  260. expect(parsed_oversized_email_reply).to include(
  261. {
  262. from_email: email_address.email,
  263. subject: '[undeliverable] Message too large',
  264. 'references' => "<#{cid}@zammad.test.com>",
  265. 'in-reply-to' => "<#{cid}@zammad.test.com>",
  266. }
  267. )
  268. # verify the reply mail body content
  269. expect(parsed_oversized_email_reply[:body]).to match(%r{^Dear Max Mustermann.*Oversized Email Message.*#{oversized_email_size} MB.*0.1 MB.*#{Setting.get('fqdn')}}sm)
  270. # check if original mail got removed
  271. imap.select(folder)
  272. expect(imap.sort(['DATE'], ['ALL'], 'US-ASCII')).to be_empty
  273. end
  274. end
  275. context 'without email reply' do
  276. before do
  277. Setting.set('postmaster_max_size', 0.1)
  278. Setting.set('postmaster_send_reject_if_mail_too_large', false)
  279. fetch_oversized_email
  280. end
  281. it 'does not create email reply' do
  282. # verify that no postmaster response email has been sent
  283. imap.select('inbox')
  284. sleep 1
  285. expect(imap.sort(['DATE'], ['ALL'], 'US-ASCII').count).to be_zero
  286. # check that original mail is still there
  287. imap.select(folder)
  288. expect(imap.sort(['DATE'], ['ALL'], 'US-ASCII').count).to be(1)
  289. end
  290. end
  291. end
  292. end
  293. describe '.fetch_message_body_key' do
  294. context 'with icloud mail server' do
  295. let(:host) { 'imap.mail.me.com' }
  296. it 'fetches mails with BODY field' do
  297. expect(described_class.new.fetch_message_body_key({ 'host' => host })).to eq('BODY[]')
  298. end
  299. end
  300. context 'with another mail server' do
  301. let(:host) { 'any.server.com' }
  302. it 'fetches mails with RFC822 field' do
  303. expect(described_class.new.fetch_message_body_key({ 'host' => host })).to eq('RFC822')
  304. end
  305. end
  306. end
  307. end