microsoft365_spec.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # Copyright (C) 2012-2022 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) { 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImtnMkxZczJ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oUEjVihdyrJjAbdtHFKdOjrw' }
  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' 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. end
  98. end
  99. context 'API errors' do
  100. before do
  101. stub_request(:post, token_url).to_return(status: response_status, body: response_payload&.to_json, headers: {})
  102. create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret })
  103. end
  104. shared_examples 'failed attempt' do
  105. it 'raises an exception' do
  106. expect do
  107. described_class.link_account(request_token, authorization_payload)
  108. end.to raise_error(RuntimeError, exception_message)
  109. end
  110. end
  111. context '404 invalid_client' do
  112. let(:response_status) { 404 }
  113. let(:response_payload) do
  114. {
  115. error: 'invalid_client',
  116. error_description: 'The OAuth client was not found.'
  117. }
  118. end
  119. let(:exception_message) { 'Request failed! ERROR: invalid_client (The OAuth client was not found.)' }
  120. include_examples 'failed attempt'
  121. end
  122. context '500 Internal Server Error' do
  123. let(:response_status) { 500 }
  124. let(:response_payload) { nil }
  125. let(:exception_message) { 'Request failed! (code: 500)' }
  126. include_examples 'failed attempt'
  127. end
  128. end
  129. end
  130. describe '.refresh_token' do
  131. let!(:authorization_payload) do
  132. {
  133. code: authorization_code,
  134. scope: scope_payload,
  135. authuser: '4',
  136. hd: 'example.com',
  137. prompt: 'consent',
  138. controller: 'external_credentials',
  139. action: 'callback',
  140. provider: provider
  141. }
  142. end
  143. let!(:channel) do
  144. stub_request(:post, token_url).to_return(status: 200, body: token_response_payload.to_json, headers: {})
  145. create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret })
  146. channel = described_class.link_account(request_token, authorization_payload)
  147. # remove stubs and allow new stubbing for tested requests
  148. WebMock.reset!
  149. channel
  150. end
  151. before do
  152. # we check the TTL of tokens and therefore need freeze the time
  153. freeze_time
  154. end
  155. context 'success' do
  156. let!(:expired_at) { channel.options['auth']['created_at'] }
  157. before do
  158. stub_request(:post, token_url).to_return(status: 200, body: response_payload.to_json, headers: {})
  159. end
  160. context 'access_token still valid' do
  161. let(:response_payload) do
  162. {
  163. 'access_token' => access_token,
  164. 'expires_in' => token_ttl,
  165. 'scope' => scope_stub,
  166. 'token_type' => 'Bearer',
  167. 'type' => 'XOAUTH2',
  168. }
  169. end
  170. it 'does not refresh' do
  171. expect do
  172. channel.refresh_xoauth2!
  173. end.not_to change { channel.options['auth']['created_at'] }
  174. end
  175. end
  176. context 'access_token expired' do
  177. let(:refreshed_access_token) { 'some_new_token' }
  178. let(:response_payload) do
  179. {
  180. 'access_token' => refreshed_access_token,
  181. 'expires_in' => token_ttl,
  182. 'scope' => scope_stub,
  183. 'token_type' => 'Bearer',
  184. 'type' => 'XOAUTH2',
  185. }
  186. end
  187. before do
  188. travel 1.hour
  189. end
  190. it 'refreshes token' do
  191. expect do
  192. channel.refresh_xoauth2!
  193. end.to change { channel.options['auth'] }.to include(
  194. 'created_at' => Time.zone.now,
  195. 'access_token' => refreshed_access_token,
  196. )
  197. end
  198. end
  199. end
  200. context 'API errors' do
  201. before do
  202. stub_request(:post, token_url).to_return(status: response_status, body: response_payload&.to_json, headers: {})
  203. # invalidate existing token
  204. travel 1.hour
  205. end
  206. shared_examples 'failed attempt' do
  207. it 'raises an exception' do
  208. expect do
  209. channel.refresh_xoauth2!
  210. end.to raise_error(RuntimeError, exception_message)
  211. end
  212. end
  213. context '400 invalid_client' do
  214. let(:response_status) { 400 }
  215. let(:response_payload) do
  216. {
  217. error: 'invalid_client',
  218. error_description: 'The OAuth client was not found.'
  219. }
  220. end
  221. let(:exception_message) { %r{The OAuth client was not found} }
  222. include_examples 'failed attempt'
  223. end
  224. context '500 Internal Server Error' do
  225. let(:response_status) { 500 }
  226. let(:response_payload) { nil }
  227. let(:exception_message) { %r{code: 500} }
  228. include_examples 'failed attempt'
  229. end
  230. end
  231. end
  232. describe '.request_account_to_link' do
  233. it 'generates authorize_url from credentials' do
  234. microsoft365 = create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret })
  235. request = described_class.request_account_to_link(microsoft365.credentials)
  236. expect(request[:authorize_url]).to eq(authorize_url)
  237. end
  238. context 'errors' do
  239. shared_examples 'failed attempt' do
  240. it 'raises an exception' do
  241. expect do
  242. described_class.request_account_to_link(credentials, app_required)
  243. end.to raise_error(Exceptions::UnprocessableEntity, exception_message)
  244. end
  245. end
  246. context 'missing credentials' do
  247. let(:credentials) { nil }
  248. let(:app_required) { true }
  249. let(:exception_message) { 'No Microsoft 365 app configured!' }
  250. include_examples 'failed attempt'
  251. end
  252. context 'missing client_id' do
  253. let(:credentials) do
  254. {
  255. client_secret: client_secret
  256. }
  257. end
  258. let(:app_required) { false }
  259. let(:exception_message) { "The required parameter 'client_id' is missing." }
  260. include_examples 'failed attempt'
  261. end
  262. context 'missing client_secret' do
  263. let(:credentials) do
  264. {
  265. client_id: client_id
  266. }
  267. end
  268. let(:app_required) { false }
  269. let(:exception_message) { "The required parameter 'client_secret' is missing." }
  270. include_examples 'failed attempt'
  271. end
  272. end
  273. end
  274. describe '.generate_authorize_url' do
  275. it 'generates valid URL' do
  276. url = described_class.generate_authorize_url(client_id: client_id)
  277. expect(url).to eq(authorize_url)
  278. end
  279. it 'generates valid URL with tenant' do
  280. url = described_class.generate_authorize_url(client_id: client_id, client_tenant: 'tenant')
  281. expect(url).to eq(authorize_url_with_tenant)
  282. end
  283. end
  284. describe '.user_info' do
  285. it 'extracts user information from id_token' do
  286. info = described_class.user_info(id_token)
  287. expect(info[:email]).to eq(email_address)
  288. end
  289. end
  290. end