imap_spec.rb 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 'without sort capability' do
  131. before do
  132. allow_any_instance_of(Net::IMAP).to receive(:capabilities).and_return(%w[ID IDLE IMAP4REV1 MOVE STARTTLS UIDPLUS UNSELECT])
  133. end
  134. it 'fetches mails without problems' do
  135. imap.append(folder, email1, [], Time.zone.now)
  136. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  137. end
  138. end
  139. context 'with keep_on_server flag' do
  140. let(:inbound_options) do
  141. {
  142. adapter: 'imap',
  143. options: {
  144. host: ENV['MAIL_SERVER'],
  145. user: ENV['MAIL_ADDRESS'],
  146. password: server_password,
  147. ssl: true,
  148. ssl_verify: false,
  149. folder: folder,
  150. keep_on_server: true,
  151. }
  152. }
  153. end
  154. it 'handles messages correctly' do # rubocop:disable RSpec/ExampleLength
  155. imap.append(folder, email1, [], Time.zone.now)
  156. # verify if message is still on server
  157. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  158. expect(message_ids.count).to be(1)
  159. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  160. expect(message_meta['FLAGS']).not_to include(:Seen)
  161. # fetch messages - will import
  162. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  163. # verify if message is still on server
  164. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  165. expect(message_ids.count).to be(1)
  166. # message now has :seen flag
  167. message_meta = imap.fetch(1, ['RFC822.HEADER', 'FLAGS'])[0].attr
  168. expect(message_meta['FLAGS']).to include(:Seen)
  169. # fetch messages - will not import
  170. expect { channel.fetch(true) }.not_to change(Ticket::Article, :count)
  171. # verify if message is still on server
  172. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  173. expect(message_ids.count).to be(1)
  174. # put unseen message in it
  175. imap.append(folder, email2, [], Time.zone.now)
  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']).not_to include(:Seen)
  180. # fetch messages - will import new
  181. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  182. # verify if message is still on server
  183. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  184. expect(message_ids.count).to be(2)
  185. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  186. expect(message_meta['FLAGS']).to include(:Seen)
  187. message_meta = imap.fetch(2, ['FLAGS'])[0].attr
  188. expect(message_meta['FLAGS']).to include(:Seen)
  189. # set messages to not seen
  190. imap.store(1, '-FLAGS', [:Seen])
  191. imap.store(2, '-FLAGS', [:Seen])
  192. # fetch messages - will still not import
  193. expect { channel.fetch(true) }.not_to change(Ticket::Article, :count)
  194. end
  195. end
  196. context 'without keep_on_server flag' do
  197. it 'handles messages correctly' do
  198. imap.append(folder, email1, [], Time.zone.now)
  199. # verify if message is still on server
  200. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  201. expect(message_ids.count).to be(1)
  202. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  203. expect(message_meta['FLAGS']).not_to include(:Seen)
  204. # fetch messages - will import
  205. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  206. # verify if message is still on server
  207. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  208. expect(message_ids.count).to be(1)
  209. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  210. expect(message_meta['FLAGS']).to include(:Seen, :Deleted)
  211. # put unseen message in it
  212. imap.append(folder, email2, [], Time.zone.now)
  213. # verify if message is still on server
  214. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  215. expect(message_ids.count).to be(1)
  216. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  217. expect(message_meta['FLAGS']).not_to include(:Seen)
  218. # fetch messages - will import
  219. expect { channel.fetch(true) }.to change(Ticket::Article, :count)
  220. # verify if message is still on server
  221. message_ids = imap.sort(['DATE'], ['ALL'], 'US-ASCII')
  222. expect(message_ids.count).to be(1)
  223. message_meta = imap.fetch(1, ['FLAGS'])[0].attr
  224. expect(message_meta['FLAGS']).to include(:Seen)
  225. end
  226. end
  227. end
  228. context 'when fetching oversized emails' do
  229. let(:sender_email_address) { ENV['MAIL_ADDRESS'] }
  230. let(:cid) { SecureRandom.uuid.tr('-', '.') }
  231. let(:oversized_email) do
  232. <<~OVERSIZED_EMAIL.gsub(%r{\n}, "\r\n")
  233. Subject: Oversized Email Message
  234. From: Max Mustermann <#{sender_email_address}>
  235. To: shugo@example.com
  236. Message-ID: <#{cid}@zammad.test.com>
  237. Oversized Email Message Body #{'#' * 120_000}
  238. OVERSIZED_EMAIL
  239. end
  240. let(:oversized_email_md5) { Digest::MD5.hexdigest(oversized_email) }
  241. let(:oversized_email_size) { format('%<MB>.2f', MB: oversized_email.size.to_f / 1024 / 1024) }
  242. let(:fetch_oversized_email) do
  243. imap.append(folder, oversized_email, [], Time.zone.now)
  244. channel.fetch(true)
  245. end
  246. context 'with email reply' do
  247. before do
  248. Setting.set('postmaster_max_size', 0.1)
  249. fetch_oversized_email
  250. end
  251. let(:oversized_email_reply) do
  252. imap.select('inbox')
  253. 5.times do |i|
  254. sleep i
  255. msg = imap.sort(['DATE'], ['ALL'], 'US-ASCII').first
  256. if msg
  257. return imap.fetch(msg, 'RFC822')[0].attr['RFC822']
  258. end
  259. end
  260. nil
  261. end
  262. let(:parsed_oversized_email_reply) do
  263. Channel::EmailParser.new.parse(oversized_email_reply)
  264. end
  265. it 'creates email reply correctly' do
  266. # verify that a postmaster response email has been sent to the sender
  267. expect(oversized_email_reply).to be_present
  268. # parse the reply mail and verify the various headers
  269. expect(parsed_oversized_email_reply).to include(
  270. {
  271. from_email: email_address.email,
  272. subject: '[undeliverable] Message too large',
  273. 'references' => "<#{cid}@zammad.test.com>",
  274. 'in-reply-to' => "<#{cid}@zammad.test.com>",
  275. }
  276. )
  277. # verify the reply mail body content
  278. 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)
  279. # check if original mail got removed
  280. imap.select(folder)
  281. expect(imap.sort(['DATE'], ['ALL'], 'US-ASCII')).to be_empty
  282. end
  283. end
  284. context 'without email reply' do
  285. before do
  286. Setting.set('postmaster_max_size', 0.1)
  287. Setting.set('postmaster_send_reject_if_mail_too_large', false)
  288. fetch_oversized_email
  289. end
  290. it 'does not create email reply' do
  291. # verify that no postmaster response email has been sent
  292. imap.select('inbox')
  293. sleep 1
  294. expect(imap.sort(['DATE'], ['ALL'], 'US-ASCII').count).to be_zero
  295. # check that original mail is still there
  296. imap.select(folder)
  297. expect(imap.sort(['DATE'], ['ALL'], 'US-ASCII').count).to be(1)
  298. end
  299. end
  300. end
  301. end
  302. describe '.fetch_message_body_key' do
  303. context 'with icloud mail server' do
  304. let(:host) { 'imap.mail.me.com' }
  305. it 'fetches mails with BODY field' do
  306. expect(described_class.new.fetch_message_body_key({ 'host' => host })).to eq('BODY[]')
  307. end
  308. end
  309. context 'with another mail server' do
  310. let(:host) { 'any.server.com' }
  311. it 'fetches mails with RFC822 field' do
  312. expect(described_class.new.fetch_message_body_key({ 'host' => host })).to eq('RFC822')
  313. end
  314. end
  315. end
  316. end