1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe GraphqlController do
include GraphqlHelpers
# two days is enough to make timezones irrelevant
let_it_be(:last_activity_on) { 2.days.ago.to_date }
describe 'rescue_from' do
let_it_be(:message) { 'green ideas sleep furiously' }
it 'handles ArgumentError' do
allow(subject).to receive(:execute) do
raise Gitlab::Graphql::Errors::ArgumentError, message
end
post :execute
expect(json_response).to include(
'errors' => include(a_hash_including('message' => message))
)
end
it 'handles a timeout nicely' do
allow(subject).to receive(:execute) do
raise ActiveRecord::QueryCanceled, '**taps wristwatch**'
end
post :execute
expect(json_response).to include(
'errors' => include(a_hash_including('message' => /Request timed out/))
)
end
it 'handles StandardError' do
allow(subject).to receive(:execute) do
raise StandardError, message
end
post :execute
expect(json_response).to include(
'errors' => include(a_hash_including('message' => /Internal server error/,
'raisedAt' => /graphql_controller_spec.rb/))
)
end
end
describe 'POST #execute' do
context 'when user is logged in' do
let(:user) { create(:user, last_activity_on: last_activity_on) }
before do
sign_in(user)
end
it 'sets feature category in ApplicationContext from request' do
request.headers["HTTP_X_GITLAB_FEATURE_CATEGORY"] = "web_ide"
post :execute
expect(::Gitlab::ApplicationContext.current_context_attribute(:feature_category)).to eq('web_ide')
end
it 'returns 200 when user can access API' do
post :execute
expect(response).to have_gitlab_http_status(:ok)
end
it 'executes a simple query with no errors' do
post :execute, params: { query: '{ __typename }' }
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).to eq({ 'data' => { '__typename' => 'Query' } })
end
it 'executes a simple multiplexed query with no errors' do
multiplex = [{ query: '{ __typename }' }] * 2
post :execute, params: { _json: multiplex }
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).to eq(
[
{ 'data' => { '__typename' => 'Query' } },
{ 'data' => { '__typename' => 'Query' } }
])
end
it 'sets a limit on the total query size' do
graphql_query = "{#{(['__typename'] * 1000).join(' ')}}"
post :execute, params: { query: graphql_query }
expect(response).to have_gitlab_http_status(:unprocessable_entity)
expect(json_response).to eq({ 'errors' => [{ 'message' => 'Query too large' }] })
end
it 'sets a limit on the total query size for multiplex queries' do
graphql_query = "{#{(['__typename'] * 200).join(' ')}}"
multiplex = [{ query: graphql_query }] * 5
post :execute, params: { _json: multiplex }
expect(response).to have_gitlab_http_status(:unprocessable_entity)
expect(json_response).to eq({ 'errors' => [{ 'message' => 'Query too large' }] })
end
it 'returns forbidden when user cannot access API' do
# User cannot access API in a couple of cases
# * When user is internal(like ghost users)
# * When user is blocked
expect(Ability).to receive(:allowed?).with(user, :log_in, :global).and_call_original
expect(Ability).to receive(:allowed?).with(user, :access_api, :global).and_return(false)
post :execute
expect(response).to have_gitlab_http_status(:forbidden)
expect(json_response).to include(
'errors' => include(a_hash_including('message' => /API not accessible/))
)
end
it 'updates the users last_activity_on field' do
expect { post :execute }.to change { user.reload.last_activity_on }
end
it "sets context's sessionless value as false" do
post :execute
expect(assigns(:context)[:is_sessionless_user]).to be false
end
it 'calls the track api when trackable method' do
agent = 'vs-code-gitlab-workflow/3.11.1 VSCode/1.52.1 Node.js/12.14.1 (darwin; x64)'
request.env['HTTP_USER_AGENT'] = agent
expect(Gitlab::UsageDataCounters::VSCodeExtensionActivityUniqueCounter)
.to receive(:track_api_request_when_trackable).with(user_agent: agent, user: user)
post :execute
end
it 'calls the track jetbrains api when trackable method' do
agent = 'gitlab-jetbrains-plugin/0.0.1 intellij-idea/2021.2.4 java/11.0.13 mac-os-x/aarch64/12.1'
request.env['HTTP_USER_AGENT'] = agent
expect(Gitlab::UsageDataCounters::JetBrainsPluginActivityUniqueCounter)
.to receive(:track_api_request_when_trackable).with(user_agent: agent, user: user)
post :execute
end
it 'calls the track gitlab cli when trackable method' do
agent = 'GLab - GitLab CLI'
request.env['HTTP_USER_AGENT'] = agent
expect(Gitlab::UsageDataCounters::GitLabCliActivityUniqueCounter)
.to receive(:track_api_request_when_trackable).with(user_agent: agent, user: user)
post :execute
end
it "assigns username in ApplicationContext" do
post :execute
expect(Gitlab::ApplicationContext.current).to include('meta.user' => user.username)
end
end
context 'when 2FA is required for the user' do
let(:user) { create(:user, last_activity_on: last_activity_on) }
before do
group = create(:group, require_two_factor_authentication: true)
group.add_developer(user)
sign_in(user)
end
it 'does not redirect if 2FA is enabled' do
expect(controller).not_to receive(:redirect_to)
post :execute
expect(response).to have_gitlab_http_status(:unauthorized)
expected_message = "Authentication error: " \
"enable 2FA in your profile settings to continue using GitLab: %{mfa_help_page}" %
{ mfa_help_page: EnforcesTwoFactorAuthentication::MFA_HELP_PAGE }
expect(json_response).to eq({ 'errors' => [{ 'message' => expected_message }] })
end
end
context 'when user uses an API token' do
let(:user) { create(:user, last_activity_on: last_activity_on) }
let(:token) { create(:personal_access_token, user: user, scopes: [:api]) }
let(:query) { '{ __typename }' }
subject { post :execute, params: { query: query, access_token: token.token } }
context 'when the user is a project bot' do
let(:user) { create(:user, :project_bot, last_activity_on: last_activity_on) }
it 'updates the users last_activity_on field' do
expect { subject }.to change { user.reload.last_activity_on }
end
it "sets context's sessionless value as true" do
subject
expect(assigns(:context)[:is_sessionless_user]).to be true
end
it 'executes a simple query with no errors' do
subject
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).to eq({ 'data' => { '__typename' => 'Query' } })
end
it 'can access resources the project_bot has access to' do
project_a, project_b = create_list(:project, 2, :private)
project_a.add_developer(user)
post :execute, params: { query: <<~GQL, access_token: token.token }
query {
a: project(fullPath: "#{project_a.full_path}") { name }
b: project(fullPath: "#{project_b.full_path}") { name }
}
GQL
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).to eq({ 'data' => { 'a' => { 'name' => project_a.name }, 'b' => nil } })
end
end
it 'updates the users last_activity_on field' do
expect { subject }.to change { user.reload.last_activity_on }
end
it "sets context's sessionless value as true" do
subject
expect(assigns(:context)[:is_sessionless_user]).to be true
end
it "assigns username in ApplicationContext" do
subject
expect(Gitlab::ApplicationContext.current).to include('meta.user' => user.username)
end
it 'calls the track api when trackable method' do
agent = 'vs-code-gitlab-workflow/3.11.1 VSCode/1.52.1 Node.js/12.14.1 (darwin; x64)'
request.env['HTTP_USER_AGENT'] = agent
expect(Gitlab::UsageDataCounters::VSCodeExtensionActivityUniqueCounter)
.to receive(:track_api_request_when_trackable).with(user_agent: agent, user: user)
subject
end
it 'calls the track jetbrains api when trackable method' do
agent = 'gitlab-jetbrains-plugin/0.0.1 intellij-idea/2021.2.4 java/11.0.13 mac-os-x/aarch64/12.1'
request.env['HTTP_USER_AGENT'] = agent
expect(Gitlab::UsageDataCounters::JetBrainsPluginActivityUniqueCounter)
.to receive(:track_api_request_when_trackable).with(user_agent: agent, user: user)
subject
end
it 'calls the track gitlab cli when trackable method' do
agent = 'GLab - GitLab CLI'
request.env['HTTP_USER_AGENT'] = agent
expect(Gitlab::UsageDataCounters::GitLabCliActivityUniqueCounter)
.to receive(:track_api_request_when_trackable).with(user_agent: agent, user: user)
subject
end
end
context 'when user is not logged in' do
it 'returns 200' do
post :execute
expect(response).to have_gitlab_http_status(:ok)
end
it "sets context's sessionless value as false" do
post :execute
expect(assigns(:context)[:is_sessionless_user]).to be false
end
it "does not assign a username in ApplicationContext" do
subject
expect(Gitlab::ApplicationContext.current.key?('meta.user')).to be false
end
end
it 'includes request object in context' do
post :execute
expect(assigns(:context)[:request]).to eq request
end
end
describe 'Admin Mode' do
let(:admin) { create(:admin) }
let(:project) { create(:project) }
let(:graphql_query) { graphql_query_for('project', { 'fullPath' => project.full_path }, %w(id name)) }
before do
sign_in(admin)
end
context 'when admin mode enabled' do
before do
Gitlab::Session.with_session(controller.session) do
controller.current_user_mode.request_admin_mode!
controller.current_user_mode.enable_admin_mode!(password: admin.password)
end
end
it 'can query project data' do
post :execute, params: { query: graphql_query }
expect(controller.current_user_mode.admin_mode?).to be(true)
expect(json_response['data']['project']['name']).to eq(project.name)
end
end
context 'when admin mode disabled' do
it 'cannot query project data' do
post :execute, params: { query: graphql_query }
expect(controller.current_user_mode.admin_mode?).to be(false)
expect(json_response['data']['project']).to be_nil
end
context 'when admin is member of the project' do
before do
project.add_developer(admin)
end
it 'can query project data' do
post :execute, params: { query: graphql_query }
expect(controller.current_user_mode.admin_mode?).to be(false)
expect(json_response['data']['project']['name']).to eq(project.name)
end
end
end
end
describe '#append_info_to_payload' do
let(:query_1) { { query: graphql_query_for('project', { 'fullPath' => 'foo' }, %w(id name), 'getProject_1') } }
let(:query_2) { { query: graphql_query_for('project', { 'fullPath' => 'bar' }, %w(id), 'getProject_2') } }
let(:graphql_queries) { [query_1, query_2] }
let(:log_payload) { {} }
let(:expected_logs) do
[
{
operation_name: 'getProject_1',
complexity: 3,
depth: 2,
used_deprecated_fields: [],
used_fields: ['Project.id', 'Project.name', 'Query.project'],
variables: '{}'
},
{
operation_name: 'getProject_2',
complexity: 2,
depth: 2,
used_deprecated_fields: [],
used_fields: ['Project.id', 'Query.project'],
variables: '{}'
}
]
end
before do
RequestStore.clear!
allow(controller).to receive(:append_info_to_payload).and_wrap_original do |method, *|
method.call(log_payload)
end
end
it 'appends metadata for logging' do
post :execute, params: { _json: graphql_queries }
expect(controller).to have_received(:append_info_to_payload)
expect(log_payload.dig(:metadata, :graphql)).to match_array(expected_logs)
end
it 'appends the exception in case of errors' do
exception = StandardError.new('boom')
expect(controller).to receive(:execute).and_raise(exception)
post :execute, params: { _json: graphql_queries }
expect(controller).to have_received(:append_info_to_payload)
expect(log_payload.dig(:exception_object)).to eq(exception)
end
end
end
|