external_credentials_spec.rb 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. require 'rails_helper'
  2. RSpec.describe 'External Credentials', type: :request do
  3. let(:admin) { create(:admin) }
  4. context 'without authentication' do
  5. describe '#index' do
  6. it 'returns 403 Forbidden' do
  7. get '/api/v1/external_credentials', as: :json
  8. expect(response).to have_http_status(:forbidden)
  9. expect(json_response).to include('error' => 'Authentication required')
  10. end
  11. end
  12. describe '#app_verify' do
  13. it 'returns 403 Forbidden' do
  14. post '/api/v1/external_credentials/facebook/app_verify', as: :json
  15. expect(response).to have_http_status(:forbidden)
  16. expect(json_response).to include('error' => 'Authentication required')
  17. end
  18. end
  19. describe '#link_account' do
  20. it 'returns 403 Forbidden' do
  21. get '/api/v1/external_credentials/facebook/link_account', as: :json
  22. expect(response).to have_http_status(:forbidden)
  23. expect(json_response).to include('error' => 'Authentication required')
  24. end
  25. end
  26. describe '#callback' do
  27. it 'returns 403 Forbidden' do
  28. get '/api/v1/external_credentials/facebook/callback', as: :json
  29. expect(response).to have_http_status(:forbidden)
  30. expect(json_response).to include('error' => 'Authentication required')
  31. end
  32. end
  33. end
  34. context 'authenticated as admin' do
  35. before { authenticated_as(admin, via: :browser) }
  36. describe '#index' do
  37. it 'responds with an array of ExternalCredential records' do
  38. get '/api/v1/external_credentials', as: :json
  39. expect(response).to have_http_status(:ok)
  40. expect(json_response).to eq([])
  41. end
  42. context 'with expand=true URL parameters' do
  43. it 'responds with an array of ExternalCredential records and their association data' do
  44. get '/api/v1/external_credentials?expand=true', as: :json
  45. expect(response).to have_http_status(:ok)
  46. expect(json_response).to eq([])
  47. end
  48. end
  49. end
  50. context 'for Facebook' do
  51. let(:invalid_credentials) do
  52. { application_id: 123, application_secret: 123 }
  53. end
  54. describe '#app_verify' do
  55. describe 'failure cases' do
  56. context 'when permission for Facebook channel is deactivated' do
  57. before { Permission.find_by(name: 'admin.channel_facebook').update(active: false) }
  58. it 'returns 403 Forbidden with internal (Zammad) error' do
  59. post '/api/v1/external_credentials/facebook/app_verify', as: :json
  60. expect(response).to have_http_status(:forbidden)
  61. expect(json_response).to include('error' => 'Not authorized (user)!')
  62. end
  63. end
  64. context 'with no credentials' do
  65. it 'returns 200 with internal (Zammad) error' do
  66. post '/api/v1/external_credentials/facebook/app_verify', as: :json
  67. expect(response).to have_http_status(:ok)
  68. expect(json_response).to include('error' => 'No application_id param!')
  69. end
  70. end
  71. context 'with invalid credentials, via request params' do
  72. it 'returns 200 with remote (Facebook auth) error', :use_vcr do
  73. post '/api/v1/external_credentials/facebook/app_verify', params: invalid_credentials, as: :json
  74. expect(response).to have_http_status(:ok)
  75. expect(json_response).to include('error' => 'type: OAuthException, code: 101, message: Error validating application. Cannot get application info due to a system error. [HTTP 400]')
  76. end
  77. end
  78. context 'with invalid credentials, via ExternalCredential record' do
  79. before { create(:facebook_credential, credentials: invalid_credentials) }
  80. it 'returns 200 with remote (Facebook auth) error', :use_vcr do
  81. post '/api/v1/external_credentials/facebook/app_verify', as: :json
  82. expect(response).to have_http_status(:ok)
  83. expect(json_response).to include('error' => 'type: OAuthException, code: 101, message: Error validating application. Cannot get application info due to a system error. [HTTP 400]')
  84. end
  85. end
  86. end
  87. end
  88. describe '#link_account' do
  89. describe 'failure cases' do
  90. context 'with no credentials' do
  91. it 'returns 422 unprocessable entity with internal (Zammad) error' do
  92. get '/api/v1/external_credentials/facebook/link_account', as: :json
  93. expect(response).to have_http_status(:unprocessable_entity)
  94. expect(json_response).to include('error' => 'No facebook app configured!')
  95. end
  96. end
  97. context 'with invalid credentials, via request params' do
  98. it 'returns 422 unprocessable entity with internal (Zammad) error' do
  99. get '/api/v1/external_credentials/facebook/link_account', params: invalid_credentials, as: :json
  100. expect(response).to have_http_status(:unprocessable_entity)
  101. expect(json_response).to include('error' => 'No facebook app configured!')
  102. end
  103. end
  104. context 'with invalid credentials, via ExternalCredential record' do
  105. before { create(:facebook_credential, credentials: invalid_credentials) }
  106. it 'returns 500 with remote (Facebook auth) error', :use_vcr do
  107. get '/api/v1/external_credentials/facebook/link_account', as: :json
  108. expect(response).to have_http_status(:internal_server_error)
  109. expect(json_response).to include('error' => 'type: OAuthException, code: 101, message: Error validating application. Cannot get application info due to a system error. [HTTP 400]')
  110. end
  111. end
  112. end
  113. end
  114. describe '#callback' do
  115. describe 'failure cases' do
  116. context 'with no credentials' do
  117. it 'returns 422 unprocessable entity with internal (Zammad) error' do
  118. get '/api/v1/external_credentials/facebook/callback', as: :json
  119. expect(response).to have_http_status(:unprocessable_entity)
  120. expect(json_response).to include('error' => 'No facebook app configured!')
  121. end
  122. end
  123. context 'with invalid credentials, via request params' do
  124. it 'returns 422 unprocessable entity with internal (Zammad) error' do
  125. get '/api/v1/external_credentials/facebook/callback', params: invalid_credentials, as: :json
  126. expect(response).to have_http_status(:unprocessable_entity)
  127. expect(json_response).to include('error' => 'No facebook app configured!')
  128. end
  129. end
  130. context 'with invalid credentials, via ExternalCredential record' do
  131. before { create(:facebook_credential, credentials: invalid_credentials) }
  132. it 'returns 500 with remote (Facebook auth) error', :use_vcr do
  133. get '/api/v1/external_credentials/facebook/callback', as: :json
  134. expect(response).to have_http_status(:internal_server_error)
  135. expect(json_response).to include('error' => 'type: OAuthException, code: 101, message: Error validating application. Cannot get application info due to a system error. [HTTP 400]')
  136. end
  137. end
  138. end
  139. end
  140. end
  141. context 'for Twitter', :use_vcr do
  142. shared_context 'for callback URL configuration' do
  143. # NOTE: When recording a new VCR cassette for these tests,
  144. # the URL below must match the callback URL
  145. # registered with developer.twitter.com.
  146. before do
  147. Setting.set('http_type', 'https')
  148. Setting.set('fqdn', 'zammad.example.com')
  149. end
  150. end
  151. shared_examples 'for failure cases' do
  152. it 'responds with the appropriate status and error message' do
  153. send(*endpoint, as: :json, params: try(:params) || {})
  154. expect(response).to have_http_status(status)
  155. expect(json_response).to include('error' => error_message)
  156. end
  157. end
  158. let(:valid_credentials) { attributes_for(:twitter_credential)[:credentials] }
  159. let(:invalid_credentials) { attributes_for(:twitter_credential, :invalid)[:credentials] }
  160. describe 'POST /api/v1/external_credentials/twitter/app_verify' do
  161. let(:endpoint) { [:post, '/api/v1/external_credentials/twitter/app_verify'] }
  162. context 'when permission for Twitter channel is deactivated' do
  163. before { Permission.find_by(name: 'admin.channel_twitter').update(active: false) }
  164. include_examples 'for failure cases' do
  165. let(:status) { :forbidden }
  166. let(:error_message) { 'Not authorized (user)!' }
  167. end
  168. end
  169. context 'with no credentials' do
  170. include_examples 'for failure cases' do
  171. let(:status) { :ok }
  172. let(:error_message) { 'No consumer_key param!' }
  173. end
  174. end
  175. context 'with invalid credential params' do
  176. let(:params) { invalid_credentials }
  177. include_examples 'for failure cases' do
  178. let(:status) { :ok }
  179. let(:error_message) { <<~ERR.chomp }
  180. 401 Authorization Required (Invalid credentials may be to blame.)
  181. ERR
  182. end
  183. end
  184. context 'with valid credential params but misconfigured callback URL' do
  185. let(:params) { valid_credentials }
  186. include_examples 'for failure cases' do
  187. let(:status) { :ok }
  188. let(:error_message) { <<~ERR.chomp }
  189. 403 Forbidden (Your app's callback URL configuration on developer.twitter.com may be to blame.)
  190. ERR
  191. end
  192. end
  193. context 'with valid credential params and callback URL but no dev env registered' do
  194. let(:params) { valid_credentials }
  195. include_context 'for callback URL configuration'
  196. include_examples 'for failure cases' do
  197. let(:status) { :ok }
  198. let(:error_message) { <<~ERR.chomp }
  199. Forbidden. Are you sure you created a development environment on developer.twitter.com?
  200. ERR
  201. end
  202. end
  203. context 'with valid credential params and callback URL but wrong dev env label' do
  204. let(:params) { valid_credentials.merge(env: 'foo') }
  205. include_context 'for callback URL configuration'
  206. include_examples 'for failure cases' do
  207. let(:status) { :ok }
  208. let(:error_message) { <<~ERR.chomp }
  209. Dev Environment Label invalid. Please use an existing one ["zammad"], or create a new one.
  210. ERR
  211. end
  212. end
  213. context 'with valid credential params, callback URL, and dev env label' do
  214. let(:env_name) { valid_credentials[:env] }
  215. include_context 'for callback URL configuration'
  216. shared_examples 'for successful webhook connection' do
  217. let(:webhook_id) { '1241980494134145024' }
  218. it 'responds 200 OK with the new webhook ID' do
  219. send(*endpoint, as: :json, params: valid_credentials)
  220. expect(response).to have_http_status(:ok)
  221. expect(json_response).to match('attributes' => hash_including('webhook_id' => webhook_id))
  222. end
  223. end
  224. context 'with no existing webhooks' do
  225. let(:webhook_url) { "#{Setting.get('http_type')}://#{Setting.get('fqdn')}#{Rails.configuration.api_path}/channels_twitter_webhook" }
  226. include_examples 'for successful webhook connection'
  227. it 'registers a new webhook' do
  228. send(*endpoint, as: :json, params: valid_credentials)
  229. expect(WebMock)
  230. .to have_requested(:post, "https://api.twitter.com/1.1/account_activity/all/#{env_name}/webhooks.json")
  231. .with(body: "url=#{CGI.escape(webhook_url)}" )
  232. end
  233. end
  234. context 'with an existing webhook registered to another app' do
  235. include_examples 'for successful webhook connection'
  236. it 'deletes all existing webhooks first' do
  237. send(*endpoint, as: :json, params: valid_credentials)
  238. expect(WebMock)
  239. .to have_requested(:delete, "https://api.twitter.com/1.1/account_activity/all/#{env_name}/webhooks/1241981813595049984.json")
  240. end
  241. end
  242. context 'with an existing, invalid webhook registered to Zammad' do
  243. include_examples 'for successful webhook connection'
  244. it 'revalidates by manually triggering a challenge-response check' do
  245. send(*endpoint, as: :json, params: valid_credentials)
  246. expect(WebMock)
  247. .to have_requested(:put, "https://api.twitter.com/1.1/account_activity/all/#{env_name}/webhooks/1241980494134145024.json")
  248. end
  249. end
  250. context 'with an existing, valid webhook registered to Zammad' do
  251. include_examples 'for successful webhook connection'
  252. it 'uses the existing webhook' do
  253. send(*endpoint, as: :json, params: valid_credentials)
  254. expect(WebMock)
  255. .not_to have_requested(:post, "https://api.twitter.com/1.1/account_activity/all/#{env_name}/webhooks.json")
  256. end
  257. end
  258. end
  259. end
  260. describe 'GET /api/v1/external_credentials/twitter/link_account' do
  261. let(:endpoint) { [:get, '/api/v1/external_credentials/twitter/link_account'] }
  262. context 'with no Twitter app' do
  263. include_examples 'for failure cases' do
  264. let(:status) { :unprocessable_entity }
  265. let(:error_message) { 'No twitter app configured!' }
  266. end
  267. end
  268. context 'with invalid Twitter app (configured with invalid credentials)' do
  269. let!(:twitter_credential) { create(:twitter_credential, :invalid) }
  270. include_examples 'for failure cases' do
  271. let(:status) { :internal_server_error }
  272. let(:error_message) { <<~ERR.chomp }
  273. 401 Authorization Required (Invalid credentials may be to blame.)
  274. ERR
  275. end
  276. end
  277. context 'with a valid Twitter app but misconfigured callback URL' do
  278. let!(:twitter_credential) { create(:twitter_credential) }
  279. include_examples 'for failure cases' do
  280. let(:status) { :internal_server_error }
  281. let(:error_message) { <<~ERR.chomp }
  282. 403 Forbidden (Your app's callback URL configuration on developer.twitter.com may be to blame.)
  283. ERR
  284. end
  285. end
  286. context 'with a valid Twitter app and callback URL' do
  287. let!(:twitter_credential) { create(:twitter_credential) }
  288. include_context 'for callback URL configuration'
  289. it 'requests OAuth request token from Twitter API' do
  290. send(*endpoint, as: :json)
  291. expect(WebMock)
  292. .to have_requested(:post, 'https://api.twitter.com/oauth/request_token')
  293. .with(headers: { 'Authorization' => %r{oauth_consumer_key="#{twitter_credential.credentials[:consumer_key]}"} } )
  294. end
  295. it 'redirects to Twitter authorization URL' do
  296. send(*endpoint, as: :json)
  297. expect(response).to redirect_to(%r{^https://api.twitter.com/oauth/authorize\?oauth_token=\w+$})
  298. end
  299. it 'saves request token to session hash' do
  300. send(*endpoint, as: :json)
  301. expect(session[:request_token]).to be_a(OAuth::RequestToken)
  302. end
  303. end
  304. end
  305. describe 'GET /api/v1/external_credentials/twitter/callback' do
  306. let(:endpoint) { [:get, '/api/v1/external_credentials/twitter/callback'] }
  307. context 'with no Twitter app' do
  308. include_examples 'for failure cases' do
  309. let(:status) { :unprocessable_entity }
  310. let(:error_message) { 'No twitter app configured!' }
  311. end
  312. end
  313. context 'with valid Twitter app but no request token' do
  314. let!(:twitter_credential) { create(:twitter_credential) }
  315. include_examples 'for failure cases' do
  316. let(:status) { :unprocessable_entity }
  317. let(:error_message) { 'No request_token for session found!' }
  318. end
  319. end
  320. context 'with valid Twitter app and request token but non-matching OAuth token (via params)' do
  321. include_context 'for callback URL configuration'
  322. let!(:twitter_credential) { create(:twitter_credential) }
  323. before { get '/api/v1/external_credentials/twitter/link_account', as: :json }
  324. include_examples 'for failure cases' do
  325. let(:status) { :unprocessable_entity }
  326. let(:error_message) { 'Invalid oauth_token given!' }
  327. end
  328. end
  329. # NOTE: Want to delete/regenerate the VCR cassettes for these examples?
  330. # It's gonna be messy--each one is actually two cassettes merged into one.
  331. #
  332. # Why? The OAuth flow can't be fully reproduced in a request spec:
  333. #
  334. # 1. User clicks "Add Twitter account" in Zammad.
  335. # Zammad asks Twitter for request token, saves it to session,
  336. # and redirects user to Twitter.
  337. # 2. User clicks "Authorize app" on Twitter.
  338. # Twitter generates temporary OAuth credentials
  339. # and redirects user back to this endpoint (with creds in URL query string).
  340. # 3. Zammad asks Twitter for an access token
  341. # (using request token from Step 1 + OAuth creds from Step 2).
  342. #
  343. # In these tests (Step 2), the user hits this endpoint
  344. # with parameters that ONLY the Twitter OAuth server can generate.
  345. # In the VCR cassette for Step 3,
  346. # Zammad sends these parameters back to Twitter for validation.
  347. # Without valid credentials in Step 2, Step 3 will always fail.
  348. #
  349. # Instead, we have to record the VCR cassette in a live development instance
  350. # and stitch the cassette together with a cassette for Step 1.
  351. #
  352. # tl;dr A feature spec might have made more sense here.
  353. context 'with valid Twitter app, request token, and matching OAuth token (via params)' do
  354. include_context 'for callback URL configuration'
  355. let!(:twitter_credential) { create(:twitter_credential) }
  356. # For illustrative purposes only.
  357. # These parameters cannot be used to record a new VCR cassette (see note above).
  358. let(:params) { { oauth_token: oauth_token, oauth_verifier: oauth_verifier } }
  359. let(:oauth_token) { 'DyhnyQAAAAAA9CNXAAABcSxAexs' }
  360. let(:oauth_verifier) { '15DOeRkjP4JkOSVqULkTKA1SCuIPP105' }
  361. before { get '/api/v1/external_credentials/twitter/link_account', as: :json }
  362. context 'if Twitter account has already been added' do
  363. let!(:channel) { create(:twitter_channel, custom_options: channel_options) }
  364. let(:channel_options) do
  365. {
  366. user: {
  367. id: '1205290247124217856',
  368. screen_name: 'pennbrooke1',
  369. }
  370. }
  371. end
  372. it 'uses the existing channel' do
  373. expect { send(*endpoint, as: :json, params: params) }
  374. .not_to change(Channel, :count)
  375. end
  376. it 'updates channel properties' do
  377. expect { send(*endpoint, as: :json, params: params) }
  378. .to change { channel.reload.options[:user][:name] }
  379. .and change { channel.reload.options[:auth][:external_credential_id] }
  380. .and change { channel.reload.options[:auth][:oauth_token] }
  381. .and change { channel.reload.options[:auth][:oauth_token_secret] }
  382. end
  383. it 'subscribes to webhooks' do
  384. send(*endpoint, as: :json, params: params)
  385. expect(WebMock)
  386. .to have_requested(:post, "https://api.twitter.com/1.1/account_activity/all/#{twitter_credential.credentials[:env]}/subscriptions.json")
  387. expect(channel.reload.options['subscribed_to_webhook_id'])
  388. .to eq(twitter_credential.credentials[:webhook_id])
  389. end
  390. end
  391. it 'creates a new channel' do
  392. expect { send(*endpoint, as: :json, params: params) }
  393. .to change(Channel, :count).by(1)
  394. expect(Channel.last.options)
  395. .to include('adapter' => 'twitter')
  396. .and include('user' => hash_including('id', 'screen_name', 'name'))
  397. .and include('auth' => hash_including('external_credential_id', 'oauth_token', 'oauth_token_secret'))
  398. end
  399. it 'redirects to the newly created channel' do
  400. send(*endpoint, as: :json, params: params)
  401. expect(response).to redirect_to(%r{/#channels/twitter/#{Channel.last.id}$})
  402. end
  403. it 'clears the :request_token session variable' do
  404. send(*endpoint, as: :json, params: params)
  405. expect(session[:request_token]).to be(nil)
  406. end
  407. it 'subscribes to webhooks' do
  408. send(*endpoint, as: :json, params: params)
  409. expect(WebMock)
  410. .to have_requested(:post, "https://api.twitter.com/1.1/account_activity/all/#{twitter_credential.credentials[:env]}/subscriptions.json")
  411. expect(Channel.last.options['subscribed_to_webhook_id'])
  412. .to eq(twitter_credential.credentials[:webhook_id])
  413. end
  414. end
  415. end
  416. end
  417. end
  418. end