google_spec.rb 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. require 'rails_helper'
  2. RSpec.describe ExternalCredential::Google do
  3. let(:token_url) { 'https://accounts.google.com/o/oauth2/token' }
  4. let(:alias_url) { 'https://www.googleapis.com/gmail/v1/users/me/settings/sendAs' }
  5. let(:authorize_url) { "https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=#{client_id}&prompt=consent&redirect_uri=http%3A%2F%2Fzammad.example.com%2Fapi%2Fv1%2Fexternal_credentials%2Fgoogle%2Fcallback&response_type=code&scope=openid+email+profile+https%3A%2F%2Fmail.google.com%2F" }
  6. let(:id_token) { 'eyJhbGciOiJSUzI1NiIsImtpZCI6Inh4eHh4eDkwYmNkNzZhZWIyMDAyNmY2Yjc3MGNhYzIyMTc4MyIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiMTMzNy1jdGYuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIxMzM3LWN0Zi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjAwMDg5MjkxMzM3NDkxMDAwMDAyIiwiaGQiOiJleGFtcGxlLmNvbSIsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhdF9oYXNoIjoibjAwd19fNVdwQ1RGNUcwMDBjbU56QSIsImlhdCI6MTU4NzczMjg5MywiZXhwIjoxNTg3NzM2NDkzfQ==' }
  7. let(:access_token) { '000.0000lvC3gAbjs8CYoKitfqM5LBS5N13374MCg6pNpZ28mxO2HuZvg0000_rsW00aACmFEto1BJeGDuu0000vmV6Esqv78iec-FbEe842ZevQtOOemQyQXjhMs62K1E6g3ehDLPRp6j4vtpSKSb6I-3MuDPfdzdqI23hM0' }
  8. let(:refresh_token) { '1//00000VO1ES0hFCgYIARAAGAkSNwF-L9IraWQNMj5ZTqhB00006DssAYcpEyFks5OuvZ1337wrqX0D7tE5o71FIPzcWEMM5000004' }
  9. let(:request_token) { nil } # not used but required by ExternalCredential API
  10. let(:scope_payload) { 'email profile openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://mail.google.com/' }
  11. let(:scope_stub) { 'https://mail.google.com/ https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid' }
  12. let(:client_id) { '123' }
  13. let(:client_secret) { '345' }
  14. let(:authorization_code) { '567' }
  15. let(:primary_email) { 'test@example.com' }
  16. let(:provider) { 'google' }
  17. let(:token_ttl) { 3599 }
  18. let!(:alias_response_payload) do
  19. {
  20. 'sendAs' => [
  21. {
  22. 'sendAsEmail' => primary_email,
  23. 'displayName' => '',
  24. 'replyToAddress' => '',
  25. 'signature' => '',
  26. 'isPrimary' => true,
  27. 'isDefault' => true
  28. },
  29. {
  30. 'sendAsEmail' => 'alias1@example.com',
  31. 'displayName' => 'alias1',
  32. 'replyToAddress' => '',
  33. 'signature' => '',
  34. 'verificationStatus' => 'accepted',
  35. },
  36. {
  37. 'sendAsEmail' => 'alias2@example.com',
  38. 'displayName' => 'alias2',
  39. 'replyToAddress' => '',
  40. 'signature' => '',
  41. 'verificationStatus' => 'accepted',
  42. },
  43. {
  44. 'sendAsEmail' => 'alias3@example.com',
  45. 'displayName' => 'alias3',
  46. 'replyToAddress' => '',
  47. 'signature' => '',
  48. 'verificationStatus' => 'accepted',
  49. },
  50. ]
  51. }
  52. end
  53. let!(:token_response_payload) do
  54. {
  55. 'access_token' => access_token,
  56. 'expires_in' => token_ttl,
  57. 'refresh_token' => refresh_token,
  58. 'scope' => scope_stub,
  59. 'token_type' => 'Bearer',
  60. 'id_token' => id_token,
  61. 'type' => 'XOAUTH2',
  62. }
  63. end
  64. describe '.link_account' do
  65. let!(:authorization_payload) do
  66. {
  67. code: authorization_code,
  68. scope: scope_payload,
  69. authuser: '4',
  70. hd: 'example.com',
  71. prompt: 'consent',
  72. controller: 'external_credentials',
  73. action: 'callback',
  74. provider: provider
  75. }
  76. end
  77. before do
  78. # we check the TTL of tokens and therefore need freeze the time
  79. freeze_time
  80. end
  81. context 'success' do
  82. let(:request_payload) do
  83. {
  84. 'client_secret' => client_secret,
  85. 'code' => authorization_code,
  86. 'grant_type' => 'authorization_code',
  87. 'client_id' => client_id,
  88. 'redirect_uri' => ExternalCredential.callback_url(provider),
  89. }
  90. end
  91. before do
  92. stub_request(:post, token_url)
  93. .with(body: hash_including(request_payload))
  94. .to_return(status: 200, body: token_response_payload.to_json, headers: {})
  95. stub_request(:get, alias_url).to_return(status: 200, body: alias_response_payload.to_json, headers: {})
  96. create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret } )
  97. end
  98. it 'creates a Channel instance' do
  99. channel = described_class.link_account(request_token, authorization_payload)
  100. expect(channel.options).to match(
  101. a_hash_including(
  102. 'inbound' => a_hash_including(
  103. 'options' => a_hash_including(
  104. 'auth_type' => 'XOAUTH2',
  105. 'host' => 'imap.gmail.com',
  106. 'ssl' => true,
  107. 'user' => primary_email,
  108. )
  109. ),
  110. 'outbound' => a_hash_including(
  111. 'options' => a_hash_including(
  112. 'authentication' => 'xoauth2',
  113. 'host' => 'smtp.gmail.com',
  114. 'port' => 465,
  115. 'ssl' => true,
  116. 'user' => primary_email,
  117. )
  118. ),
  119. 'auth' => a_hash_including(
  120. 'access_token' => access_token,
  121. 'expires_in' => token_ttl,
  122. 'refresh_token' => refresh_token,
  123. 'scope' => scope_stub,
  124. 'token_type' => 'Bearer',
  125. 'id_token' => id_token,
  126. 'created_at' => Time.zone.now,
  127. 'type' => 'XOAUTH2',
  128. 'client_id' => client_id,
  129. 'client_secret' => client_secret,
  130. ),
  131. )
  132. )
  133. end
  134. end
  135. context 'API errors' do
  136. before do
  137. stub_request(:post, token_url).to_return(status: response_status, body: response_payload&.to_json, headers: {})
  138. create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret } )
  139. end
  140. shared_examples 'failed attempt' do
  141. it 'raises an exception' do
  142. expect do
  143. described_class.link_account(request_token, authorization_payload)
  144. end.to raise_error(RuntimeError, exception_message)
  145. end
  146. end
  147. context '404 invalid_client' do
  148. let(:response_status) { 404 }
  149. let(:response_payload) do
  150. {
  151. error: 'invalid_client',
  152. error_description: 'The OAuth client was not found.'
  153. }
  154. end
  155. let(:exception_message) { 'Request failed! ERROR: invalid_client (The OAuth client was not found.)' }
  156. include_examples 'failed attempt'
  157. end
  158. context '500 Internal Server Error' do
  159. let(:response_status) { 500 }
  160. let(:response_payload) { nil }
  161. let(:exception_message) { 'Request failed! (code: 500)' }
  162. include_examples 'failed attempt'
  163. end
  164. end
  165. end
  166. describe '.refresh_token' do
  167. let!(:authorization_payload) do
  168. {
  169. code: authorization_code,
  170. scope: scope_payload,
  171. authuser: '4',
  172. hd: 'example.com',
  173. prompt: 'consent',
  174. controller: 'external_credentials',
  175. action: 'callback',
  176. provider: provider
  177. }
  178. end
  179. let!(:channel) do
  180. stub_request(:post, token_url).to_return(status: 200, body: token_response_payload.to_json, headers: {})
  181. stub_request(:get, alias_url).to_return(status: 200, body: alias_response_payload.to_json, headers: {})
  182. create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret } )
  183. channel = described_class.link_account(request_token, authorization_payload)
  184. # remove stubs and allow new stubbing for tested requests
  185. WebMock.reset!
  186. channel
  187. end
  188. before do
  189. # we check the TTL of tokens and therefore need freeze the time
  190. freeze_time
  191. end
  192. context 'success' do
  193. let!(:expired_at) { channel.options['auth']['created_at'] }
  194. before do
  195. stub_request(:post, token_url).to_return(status: 200, body: response_payload.to_json, headers: {})
  196. end
  197. context 'access_token still valid' do
  198. let(:response_payload) do
  199. {
  200. 'access_token' => access_token,
  201. 'expires_in' => token_ttl,
  202. 'scope' => scope_stub,
  203. 'token_type' => 'Bearer',
  204. 'type' => 'XOAUTH2',
  205. }
  206. end
  207. it 'does not refresh' do
  208. expect do
  209. channel.refresh_xoauth2!
  210. end.not_to change { channel.options['auth']['created_at'] }
  211. end
  212. end
  213. context 'access_token expired' do
  214. let(:refreshed_access_token) { 'some_new_token' }
  215. let(:response_payload) do
  216. {
  217. 'access_token' => refreshed_access_token,
  218. 'expires_in' => token_ttl,
  219. 'scope' => scope_stub,
  220. 'token_type' => 'Bearer',
  221. 'type' => 'XOAUTH2',
  222. }
  223. end
  224. before do
  225. travel 1.hour
  226. end
  227. it 'refreshes token' do
  228. expect do
  229. channel.refresh_xoauth2!
  230. end.to change { channel.options['auth'] }.to a_hash_including(
  231. 'created_at' => Time.zone.now,
  232. 'access_token' => refreshed_access_token,
  233. )
  234. end
  235. end
  236. end
  237. context 'API errors' do
  238. before do
  239. stub_request(:post, token_url).to_return(status: response_status, body: response_payload&.to_json, headers: {})
  240. # invalidate existing token
  241. travel 1.hour
  242. end
  243. shared_examples 'failed attempt' do
  244. it 'raises an exception' do
  245. expect do
  246. channel.refresh_xoauth2!
  247. end.to raise_error(RuntimeError, exception_message)
  248. end
  249. end
  250. context '400 invalid_client' do
  251. let(:response_status) { 400 }
  252. let(:response_payload) do
  253. {
  254. error: 'invalid_client',
  255. error_description: 'The OAuth client was not found.'
  256. }
  257. end
  258. let(:exception_message) { %r{The OAuth client was not found} }
  259. include_examples 'failed attempt'
  260. end
  261. context '500 Internal Server Error' do
  262. let(:response_status) { 500 }
  263. let(:response_payload) { nil }
  264. let(:exception_message) { %r{code: 500} }
  265. include_examples 'failed attempt'
  266. end
  267. end
  268. end
  269. describe '.request_account_to_link' do
  270. it 'generates authorize_url from credentials' do
  271. google = create(:external_credential, name: provider, credentials: { client_id: client_id, client_secret: client_secret } )
  272. request = described_class.request_account_to_link(google.credentials)
  273. expect(request[:authorize_url]).to eq(authorize_url)
  274. end
  275. context 'errors' do
  276. shared_examples 'failed attempt' do
  277. it 'raises an exception' do
  278. expect do
  279. described_class.request_account_to_link(credentials, app_required)
  280. end.to raise_error(Exceptions::UnprocessableEntity, exception_message)
  281. end
  282. end
  283. context 'missing credentials' do
  284. let(:credentials) { nil }
  285. let(:app_required) { true }
  286. let(:exception_message) { 'No Google app configured!' }
  287. include_examples 'failed attempt'
  288. end
  289. context 'missing client_id' do
  290. let(:credentials) do
  291. {
  292. client_secret: client_secret
  293. }
  294. end
  295. let(:app_required) { false }
  296. let(:exception_message) { 'No client_id param!' }
  297. include_examples 'failed attempt'
  298. end
  299. context 'missing client_secret' do
  300. let(:credentials) do
  301. {
  302. client_id: client_id
  303. }
  304. end
  305. let(:app_required) { false }
  306. let(:exception_message) { 'No client_secret param!' }
  307. include_examples 'failed attempt'
  308. end
  309. end
  310. end
  311. describe '.user_aliases' do
  312. let(:response_status) { 200 }
  313. let(:response_payload) { alias_response_payload }
  314. let(:token) do
  315. {
  316. access_token: access_token,
  317. token_type: 'Bearer'
  318. }
  319. end
  320. before do
  321. stub_request(:get, alias_url).to_return(status: response_status, body: response_payload&.to_json, headers: {})
  322. end
  323. it 'returns the google user email aliases' do
  324. result = described_class.user_aliases(token)
  325. expect(result).to eq([
  326. { realname: 'alias1', email: 'alias1@example.com' },
  327. { realname: 'alias2', email: 'alias2@example.com' },
  328. { realname: 'alias3', email: 'alias3@example.com' }
  329. ])
  330. end
  331. context 'API errors' do
  332. context '401 Unauthorized' do
  333. let(:response_status) { 401 }
  334. let(:response_payload) do
  335. {
  336. error: {
  337. code: 401,
  338. message: 'Invalid Credentials',
  339. errors: [
  340. {
  341. locationType: 'header',
  342. domain: 'global',
  343. message: 'Invalid Credentials',
  344. reason: 'authError',
  345. location: 'Authorization'
  346. }
  347. ]
  348. }
  349. }
  350. end
  351. it 'raises an exception' do
  352. expect do
  353. described_class.user_aliases(token)
  354. end.to raise_error(RuntimeError, 'Request failed! ERROR: Invalid Credentials')
  355. end
  356. end
  357. context '500 Internal Server Error' do
  358. let(:response_status) { 500 }
  359. let(:response_payload) { nil }
  360. it 'raises an exception' do
  361. expect do
  362. described_class.user_aliases(token)
  363. end.to raise_error(RuntimeError, 'Request failed! (code: 500)')
  364. end
  365. end
  366. end
  367. end
  368. describe '.generate_authorize_url' do
  369. it 'generates valid URL' do
  370. url = described_class.generate_authorize_url(client_id)
  371. expect(url).to eq(authorize_url)
  372. end
  373. end
  374. describe '.user_info' do
  375. it 'extracts user information from id_token' do
  376. info = described_class.user_info(id_token)
  377. expect(info[:email]).to eq(primary_email)
  378. end
  379. end
  380. end