microsoft365_spec.rb 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rails_helper'
  3. RSpec.describe ExternalCredential::Microsoft365 do
  4. let(:token_url) { 'https://login.microsoftonline.com/common/oauth2/v2.0/token' }
  5. let(:token_url_with_tenant) { 'https://login.microsoftonline.com/tenant/oauth2/v2.0/token' }
  6. let(:authorize_url) { "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?access_type=offline&client_id=#{client_id}&prompt=login&redirect_uri=http%3A%2F%2Fzammad.example.com%2Fapi%2Fv1%2Fexternal_credentials%2Fmicrosoft365%2Fcallback&response_type=code&scope=https%3A%2F%2Foutlook.office.com%2FIMAP.AccessAsUser.All+https%3A%2F%2Foutlook.office.com%2FSMTP.Send+offline_access+openid+profile+email" }
  7. let(:authorize_url_with_tenant) { "https://login.microsoftonline.com/tenant/oauth2/v2.0/authorize?access_type=offline&client_id=#{client_id}&prompt=login&redirect_uri=http%3A%2F%2Fzammad.example.com%2Fapi%2Fv1%2Fexternal_credentials%2Fmicrosoft365%2Fcallback&response_type=code&scope=https%3A%2F%2Foutlook.office.com%2FIMAP.AccessAsUser.All+https%3A%2F%2Foutlook.office.com%2FSMTP.Send+offline_access+openid+profile+email" }
  8. let(:id_token) { 'eyJ0eXAiOiJKV1QiLCJhbGciOiJS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YeDZVcp_Fpw9XR7J0UlyPqLtoUEjVihdyrJjAbdtHFKdOjrw' }
  9. let(:access_token) { '000.0000lvC3gAbjs8CYoKitfqM5LBS5N13374MCg6pNpZ28mxO2HuZvg0000_rsW00aACmFEto1BJeGDuu0000vmV6Esqv78iec-FbEe842ZevQtOOemQyQXjhMs62K1E6g3ehDLPRp6j4vtpSKSb6I-3MuDPfdzdqI23hM0' }
  10. let(:refresh_token) { '1//00000VO1ES0hFCgYIARAAGAkSNwF-L9IraWQNMj5ZTqhB00006DssAYcpEyFks5OuvZ1337wrqX0D7tE5o71FIPzcWEMM5000004' }
  11. let(:request_token) { nil } # not used but required by ExternalCredential API
  12. let(:scope_payload) { 'https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send offline_access openid profile email' }
  13. let(:scope_stub) { scope_payload }
  14. let(:client_id) { '123' }
  15. let(:client_secret) { '345' }
  16. let(:client_tenant) { 'tenant' }
  17. let(:authorization_code) { '567' }
  18. let(:email_address) { 'test@example.com' }
  19. let(:provider) { 'microsoft365' }
  20. let(:token_ttl) { 3599 }
  21. let!(:token_response_payload) do
  22. {
  23. 'access_token' => access_token,
  24. 'expires_in' => token_ttl,
  25. 'refresh_token' => refresh_token,
  26. 'scope' => scope_stub,
  27. 'token_type' => 'Bearer',
  28. 'id_token' => id_token,
  29. 'type' => 'XOAUTH2',
  30. }
  31. end
  32. describe '.link_account' do
  33. let!(:authorization_payload) do
  34. {
  35. code: authorization_code,
  36. scope: scope_payload,
  37. authuser: '4',
  38. hd: 'example.com',
  39. prompt: 'consent',
  40. controller: 'external_credentials',
  41. action: 'callback',
  42. provider: provider
  43. }
  44. end
  45. before do
  46. # we check the TTL of tokens and therefore need freeze the time
  47. freeze_time
  48. end
  49. context 'success' do
  50. let(:request_payload) do
  51. {
  52. 'client_secret' => client_secret,
  53. 'code' => authorization_code,
  54. 'grant_type' => 'authorization_code',
  55. 'client_id' => client_id,
  56. 'redirect_uri' => ExternalCredential.callback_url(provider),
  57. }
  58. end
  59. before do
  60. stub_request(:post, token_url)
  61. .with(body: hash_including(request_payload))
  62. .to_return(status: 200, body: token_response_payload.to_json, headers: {})
  63. create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret })
  64. end
  65. it 'creates a Channel instance', :aggregate_failures do
  66. channel = described_class.link_account(request_token, authorization_payload)
  67. expect(channel.options).to include(
  68. 'inbound' => include(
  69. 'options' => include(
  70. 'auth_type' => 'XOAUTH2',
  71. 'host' => 'outlook.office365.com',
  72. 'ssl' => 'ssl',
  73. 'user' => email_address,
  74. )
  75. ),
  76. 'outbound' => include(
  77. 'options' => include(
  78. 'authentication' => 'xoauth2',
  79. 'host' => 'smtp.office365.com',
  80. 'port' => 587,
  81. 'user' => email_address,
  82. )
  83. ),
  84. 'auth' => include(
  85. 'access_token' => access_token,
  86. 'expires_in' => token_ttl,
  87. 'refresh_token' => refresh_token,
  88. 'scope' => scope_stub,
  89. 'token_type' => 'Bearer',
  90. 'id_token' => id_token,
  91. 'created_at' => Time.zone.now,
  92. 'type' => 'XOAUTH2',
  93. 'client_id' => client_id,
  94. 'client_secret' => client_secret,
  95. ),
  96. )
  97. channel.options[:inbound][:options][:keep_on_server] = true
  98. channel.save
  99. channel = described_class.link_account(request_token, authorization_payload.merge(channel_id: channel.id))
  100. expect(channel.reload.options[:inbound][:options][:keep_on_server]).to be(true)
  101. end
  102. context 'when users do not match', :aggregate_failures do
  103. let(:existing_channel) do
  104. ENV['MICROSOFT365_USER'] = 'zammad@outlook.com'
  105. ENV['MICROSOFT365_CLIENT_ID'] = 'xxx'
  106. ENV['MICROSOFT365_CLIENT_SECRET'] = 'xxx'
  107. ENV['MICROSOFT365_CLIENT_TENANT'] = 'xxx'
  108. create(:microsoft365_channel)
  109. end
  110. it 'generates a link to an error dialog & does not update the channel' do
  111. link_account_response = described_class.link_account(request_token, authorization_payload.merge(channel_id: existing_channel.id))
  112. expect(link_account_response).to eq("#{Setting.get('http_type')}://#{Setting.get('fqdn')}/#channels/microsoft365/error/user_mismatch")
  113. expect(existing_channel.reload.options.dig(:inbound, :options, :user)).to eq('zammad@outlook.com')
  114. expect(existing_channel.reload.options.dig(:outbound, :options, :user)).to eq('zammad@outlook.com')
  115. end
  116. end
  117. end
  118. context 'API errors' do
  119. before do
  120. stub_request(:post, token_url).to_return(status: response_status, body: response_payload&.to_json, headers: {})
  121. create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret })
  122. end
  123. shared_examples 'failed attempt' do
  124. it 'raises an exception' do
  125. expect do
  126. described_class.link_account(request_token, authorization_payload)
  127. end.to raise_error(RuntimeError, exception_message)
  128. end
  129. end
  130. context '404 invalid_client' do
  131. let(:response_status) { 404 }
  132. let(:response_payload) do
  133. {
  134. error: 'invalid_client',
  135. error_description: 'The OAuth client was not found.'
  136. }
  137. end
  138. let(:exception_message) { 'Request failed! ERROR: invalid_client (The OAuth client was not found.)' }
  139. include_examples 'failed attempt'
  140. end
  141. context '500 Internal Server Error' do
  142. let(:response_status) { 500 }
  143. let(:response_payload) { nil }
  144. let(:exception_message) { 'Request failed! (code: 500)' }
  145. include_examples 'failed attempt'
  146. end
  147. end
  148. end
  149. describe '.refresh_token' do
  150. let!(:authorization_payload) do
  151. {
  152. code: authorization_code,
  153. scope: scope_payload,
  154. authuser: '4',
  155. hd: 'example.com',
  156. prompt: 'consent',
  157. controller: 'external_credentials',
  158. action: 'callback',
  159. provider: provider
  160. }
  161. end
  162. let!(:channel) do
  163. stub_request(:post, token_url).to_return(status: 200, body: token_response_payload.to_json, headers: {})
  164. create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret })
  165. channel = described_class.link_account(request_token, authorization_payload)
  166. # remove stubs and allow new stubbing for tested requests
  167. WebMock.reset!
  168. channel
  169. end
  170. before do
  171. # we check the TTL of tokens and therefore need freeze the time
  172. freeze_time
  173. end
  174. context 'success' do
  175. let!(:expired_at) { channel.options['auth']['created_at'] }
  176. before do
  177. stub_request(:post, token_url).to_return(status: 200, body: response_payload.to_json, headers: {})
  178. end
  179. context 'access_token still valid' do
  180. let(:response_payload) do
  181. {
  182. 'access_token' => access_token,
  183. 'expires_in' => token_ttl,
  184. 'scope' => scope_stub,
  185. 'token_type' => 'Bearer',
  186. 'type' => 'XOAUTH2',
  187. }
  188. end
  189. it 'does not refresh' do
  190. expect do
  191. channel.refresh_xoauth2!
  192. end.not_to change { channel.options['auth']['created_at'] }
  193. end
  194. end
  195. context 'access_token expired' do
  196. let(:refreshed_access_token) { 'some_new_token' }
  197. let(:response_payload) do
  198. {
  199. 'access_token' => refreshed_access_token,
  200. 'expires_in' => token_ttl,
  201. 'scope' => scope_stub,
  202. 'token_type' => 'Bearer',
  203. 'type' => 'XOAUTH2',
  204. }
  205. end
  206. before do
  207. travel 1.hour
  208. end
  209. it 'refreshes token' do
  210. expect do
  211. channel.refresh_xoauth2!
  212. end.to change { channel.options['auth'] }.to include(
  213. 'created_at' => Time.zone.now,
  214. 'access_token' => refreshed_access_token,
  215. )
  216. end
  217. end
  218. end
  219. context 'API errors' do
  220. before do
  221. stub_request(:post, token_url).to_return(status: response_status, body: response_payload&.to_json, headers: {})
  222. # invalidate existing token
  223. travel 1.hour
  224. end
  225. shared_examples 'failed attempt' do
  226. it 'raises an exception' do
  227. expect do
  228. channel.refresh_xoauth2!
  229. end.to raise_error(RuntimeError, exception_message)
  230. end
  231. end
  232. context '400 invalid_client' do
  233. let(:response_status) { 400 }
  234. let(:response_payload) do
  235. {
  236. error: 'invalid_client',
  237. error_description: 'The OAuth client was not found.'
  238. }
  239. end
  240. let(:exception_message) { %r{The OAuth client was not found} }
  241. include_examples 'failed attempt'
  242. end
  243. context '500 Internal Server Error' do
  244. let(:response_status) { 500 }
  245. let(:response_payload) { nil }
  246. let(:exception_message) { %r{code: 500} }
  247. include_examples 'failed attempt'
  248. end
  249. end
  250. end
  251. describe '.request_account_to_link' do
  252. it 'generates authorize_url from credentials' do
  253. microsoft365 = create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret })
  254. request = described_class.request_account_to_link(microsoft365.credentials)
  255. expect(request[:authorize_url]).to eq(authorize_url)
  256. end
  257. context 'errors' do
  258. shared_examples 'failed attempt' do
  259. it 'raises an exception' do
  260. expect do
  261. described_class.request_account_to_link(credentials, app_required)
  262. end.to raise_error(Exceptions::UnprocessableEntity, exception_message)
  263. end
  264. end
  265. context 'missing credentials' do
  266. let(:credentials) { nil }
  267. let(:app_required) { true }
  268. let(:exception_message) { 'No Microsoft 365 app configured!' }
  269. include_examples 'failed attempt'
  270. end
  271. context 'missing client_id' do
  272. let(:credentials) do
  273. {
  274. client_secret: client_secret
  275. }
  276. end
  277. let(:app_required) { false }
  278. let(:exception_message) { "The required parameter 'client_id' is missing." }
  279. include_examples 'failed attempt'
  280. end
  281. context 'missing client_secret' do
  282. let(:credentials) do
  283. {
  284. client_id: client_id
  285. }
  286. end
  287. let(:app_required) { false }
  288. let(:exception_message) { "The required parameter 'client_secret' is missing." }
  289. include_examples 'failed attempt'
  290. end
  291. end
  292. end
  293. describe '.generate_authorize_url' do
  294. it 'generates valid URL' do
  295. url = described_class.generate_authorize_url(client_id: client_id)
  296. expect(url).to eq(authorize_url)
  297. end
  298. it 'generates valid URL with tenant' do
  299. url = described_class.generate_authorize_url(client_id: client_id, client_tenant: 'tenant')
  300. expect(url).to eq(authorize_url_with_tenant)
  301. end
  302. end
  303. describe '.user_info' do
  304. it 'extracts user information from id_token' do
  305. info = described_class.user_info(id_token)
  306. expect(info[:email]).to eq(email_address)
  307. end
  308. end
  309. end