microsoft365_spec.rb 12 KB

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