Module: API::Helpers
- Includes:
- Caching, Pagination, PaginationStrategies, Gitlab::Ci::Artifacts::Logger, Gitlab::RackLoadBalancingHelpers, Gitlab::Utils, Gitlab::Utils::StrongMemoize
- Defined in:
- lib/api/helpers.rb,
lib/api/helpers/caching.rb,
lib/api/helpers/unidiff.rb,
lib/api/helpers/version.rb,
lib/api/helpers/open_api.rb,
lib/api/helpers/pagination.rb,
lib/api/helpers/award_emoji.rb,
lib/api/helpers/presentable.rb,
lib/api/helpers/packages/npm.rb,
lib/api/helpers/rate_limiter.rb,
lib/api/helpers/label_helpers.rb,
lib/api/helpers/notes_helpers.rb,
lib/api/helpers/users_helpers.rb,
lib/api/helpers/wikis_helpers.rb,
lib/api/helpers/authentication.rb,
lib/api/helpers/badges_helpers.rb,
lib/api/helpers/common_helpers.rb,
lib/api/helpers/events_helpers.rb,
lib/api/helpers/groups_helpers.rb,
lib/api/helpers/issues_helpers.rb,
lib/api/helpers/packages/maven.rb,
lib/api/helpers/search_helpers.rb,
lib/api/helpers/graphql_helpers.rb,
lib/api/helpers/headers_helpers.rb,
lib/api/helpers/members_helpers.rb,
lib/api/helpers/internal_helpers.rb,
lib/api/helpers/packages_helpers.rb,
lib/api/helpers/projects_helpers.rb,
lib/api/helpers/settings_helpers.rb,
lib/api/helpers/snippets_helpers.rb,
lib/api/helpers/custom_attributes.rb,
lib/api/helpers/variables_helpers.rb,
lib/api/helpers/web_hooks_helpers.rb,
lib/api/helpers/discussions_helpers.rb,
lib/api/helpers/file_upload_helpers.rb,
lib/api/helpers/integrations_helpers.rb,
lib/api/helpers/pagination_strategies.rb,
lib/api/helpers/merge_requests_helpers.rb,
lib/api/helpers/protected_tags_helpers.rb,
lib/api/helpers/remote_mirrors_helpers.rb,
lib/api/helpers/performance_bar_helpers.rb,
lib/api/helpers/resource_events_helpers.rb,
lib/api/helpers/kubernetes/agent_helpers.rb,
lib/api/helpers/project_snapshots_helpers.rb,
lib/api/helpers/related_resources_helpers.rb,
lib/api/helpers/container_registry_helpers.rb,
lib/api/helpers/packages/conan/api_helpers.rb,
lib/api/helpers/protected_branches_helpers.rb,
lib/api/helpers/packages/basic_auth_helpers.rb,
lib/api/helpers/personal_access_tokens_helpers.rb,
lib/api/helpers/packages_manager_clients_helpers.rb,
lib/api/helpers/packages/dependency_proxy_helpers.rb,
lib/api/helpers/packages/maven/basic_auth_helpers.rb,
lib/api/helpers/project_stats_refresh_conflicts_helpers.rb
Defined Under Namespace
Modules: Authentication, AwardEmoji, BadgesHelpers, Caching, CommonHelpers, ContainerRegistryHelpers, CustomAttributes, DiscussionsHelpers, EventsHelpers, FileUploadHelpers, GraphqlHelpers, GroupsHelpers, HeadersHelpers, IntegrationsHelpers, InternalHelpers, IssuesHelpers, Kubernetes, LabelHelpers, MembersHelpers, MergeRequestsHelpers, NotesHelpers, OpenApi, Packages, PackagesHelpers, PackagesManagerClientsHelpers, Pagination, PaginationStrategies, PerformanceBarHelpers, PersonalAccessTokensHelpers, Presentable, ProjectSnapshotsHelpers, ProjectStatsRefreshConflictsHelpers, ProjectsHelpers, ProtectedBranchesHelpers, ProtectedTagsHelpers, RateLimiter, RelatedResourcesHelpers, RemoteMirrorsHelpers, ResourceEventsHelpers, SearchHelpers, SettingsHelpers, SnippetsHelpers, Unidiff, UsersHelpers, VariablesHelpers, WebHooksHelpers, WikisHelpers
Classes: Version
Constant Summary
collapse
"HTTP_SUDO"
"Gitlab-Shared-Secret"
"Gitlab-Shell-Api-Request"
- GITLAB_SHELL_JWT_ISSUER =
"gitlab-shell"
- SUDO_PARAM =
:sudo
- API_USER_ENV =
'gitlab.api.user'
- API_TOKEN_ENV =
'gitlab.api.token'
- API_EXCEPTION_ENV =
'gitlab.api.exception'
- API_RESPONSE_STATUS_CODE =
'gitlab.api.response_status_code'
- INTEGER_ID_REGEX =
/^-?\d+$/
Constants included
from Caching
Caching::DEFAULT_CACHE_OPTIONS, Caching::PAGINATION_HEADERS
Gitlab::Cache::Helpers::DEFAULT_EXPIRY
Instance Method Summary
collapse
-
#accepted! ⇒ Object
-
#attributes_for_keys(keys, custom_params = nil) ⇒ Object
-
#authenticate! ⇒ Object
-
#authenticate_by_gitlab_shell_token! ⇒ Object
-
#authenticate_non_get! ⇒ Object
-
#authenticated_as_admin! ⇒ Object
-
#authenticated_with_can_read_all_resources! ⇒ Object
-
#authorize!(action, subject = :global, reason = nil) ⇒ Object
-
#authorize_admin_group ⇒ Object
-
#authorize_admin_project ⇒ Object
-
#authorize_admin_tag ⇒ Object
-
#authorize_destroy_artifacts! ⇒ Object
-
#authorize_push_project ⇒ Object
-
#authorize_read_build_trace!(build) ⇒ Object
-
#authorize_read_builds! ⇒ Object
-
#authorize_read_code! ⇒ Object
-
#authorize_read_job_artifacts!(build) ⇒ Object
-
#authorize_update_builds! ⇒ Object
-
#authorized_project_scope?(project) ⇒ Boolean
-
#available_labels_for(label_parent, params = { include_ancestor_groups: true, only_group_labels: true }) ⇒ Object
-
#bad_request!(reason = nil) ⇒ Object
-
#bad_request_missing_attribute!(attribute) ⇒ Object
-
#can?(object, action, subject = :global) ⇒ Boolean
-
#cdn_fronted_url(file) ⇒ Object
-
#check_group_access(group) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord.
-
#check_namespace_access(namespace) ⇒ Object
-
#check_pipeline_access(pipeline) ⇒ Object
-
#check_sha_param!(params, merge_request) ⇒ Object
-
#check_unmodified_since!(last_modified) ⇒ Object
-
#conflict!(message = nil) ⇒ Object
-
#created! ⇒ Object
-
#current_authenticated_job ⇒ Object
Returns the job associated with the token provided for authentication, if any.
-
#current_user ⇒ Object
rubocop:disable Gitlab/ModuleWithInstanceVariables We can’t rewrite this with StrongMemoize because ‘sudo!` would actually write to `@current_user`, and `sudo?` would immediately call `current_user` again which reads from `@current_user`.
-
#declared_params(options = {}) ⇒ Object
-
#destroy_conditionally!(resource, last_updated: nil) ⇒ Object
-
#file_too_large! ⇒ Object
-
#filter_by_iid(items, iid) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#filter_by_search(items, text) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord.
-
#filter_by_title(items, title) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#find_branch!(branch_name) ⇒ Object
-
#find_build!(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord.
-
#find_group(id) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#find_group!(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord.
-
#find_group_by_full_path!(full_path) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#find_job!(id) ⇒ Object
-
#find_merge_request_with_access(iid, access_level = :read_merge_request) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#find_namespace(id) ⇒ Object
find_namespace returns the namespace regardless of user access level on the namespace rubocop: disable CodeReuse/ActiveRecord.
-
#find_namespace!(id) ⇒ Object
find_namespace! returns the namespace if the current user can read the given namespace Otherwise, returns a not_found! error.
-
#find_namespace_by_path(path) ⇒ Object
-
#find_namespace_by_path!(path) ⇒ Object
-
#find_pipeline(id) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#find_pipeline!(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord.
-
#find_project(id) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#find_project!(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord.
-
#find_project_commit(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord.
-
#find_project_issue(iid, project_id = nil) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#find_project_merge_request(iid) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#find_tag!(tag_name) ⇒ Object
-
#find_user(id) ⇒ Object
-
#forbidden!(reason = nil) ⇒ Object
-
#handle_api_exception(exception) ⇒ Object
-
#increment_counter(event_name) ⇒ Object
-
#increment_unique_values(event_name, values) ⇒ Object
-
#job_token_authentication? ⇒ Boolean
-
#logger ⇒ Object
-
#model_errors(model) ⇒ Object
-
#no_content! ⇒ Object
-
#not_acceptable! ⇒ Object
-
#not_allowed!(message = nil) ⇒ Object
-
#not_found!(resource = nil) ⇒ Object
-
#not_modified! ⇒ Object
-
#order_by_similarity?(allow_unauthorized: true) ⇒ Boolean
-
#order_options_with_tie_breaker ⇒ Object
-
#present_artifacts_file!(file, **args) ⇒ Object
-
#present_carrierwave_file!(file, supports_direct_download: true) ⇒ Object
-
#present_disk_file!(path, filename, content_type = 'application/octet-stream') ⇒ Object
-
#process_create_params(args) ⇒ Object
-
#process_update_params(args) ⇒ Object
-
#project_finder_params ⇒ Object
rubocop: enable CodeReuse/ActiveRecord.
-
#read_project_ability ⇒ Object
-
#redirect!(location_url) ⇒ Object
An error is raised to interrupt user’s request and redirect them to the right route.
-
#render_api_error!(message, status) ⇒ Object
-
#render_api_error_with_reason!(status, message, reason) ⇒ Object
-
#render_structured_api_error!(hash, status) ⇒ Object
-
#render_validation_error!(model, status = 400) ⇒ Object
-
#reorder_projects(projects) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord.
-
#require_gitlab_workhorse! ⇒ Object
-
#require_pages_config_enabled! ⇒ Object
-
#require_pages_enabled! ⇒ Object
-
#require_repository_enabled!(subject = :global) ⇒ Object
-
#required_attributes!(keys) ⇒ Object
Checks the occurrences of required attributes, each attribute must be present in the params hash or a Bad Request error is invoked.
-
#save_current_token_in_env ⇒ Object
-
#save_current_user_in_env(user) ⇒ Object
rubocop:enable Gitlab/ModuleWithInstanceVariables.
-
#service_unavailable!(message = nil) ⇒ Object
-
#set_status_code_in_env(status) ⇒ Object
-
#sudo? ⇒ Boolean
-
#too_many_requests!(message = nil, retry_after: 1.minute) ⇒ Object
-
#track_event(event_name, user:, namespace_id: nil, project_id: nil) ⇒ Object
-
#unauthorized!(reason = nil) ⇒ Object
-
#unprocessable_entity!(message = nil) ⇒ Object
-
#user_group ⇒ Object
-
#user_project ⇒ Object
-
#validate_params_for_multiple_files(snippet) ⇒ Object
-
#verify_workhorse_api! ⇒ Object
#load_balancer_stick_request
#log_artifacts_context, #log_artifacts_filesize, #log_build_dependencies, log_created, log_deleted
#paginate_with_strategies, #paginator
Methods included from Pagination
#paginate
Methods included from Caching
#cache_action, #cache_action_if, #cache_action_unless, #present_cached
#cache, #render_cached
Instance Method Details
#accepted! ⇒ Object
557
558
559
|
# File 'lib/api/helpers.rb', line 557
def accepted!
render_api_error!('202 Accepted', 202)
end
|
#attributes_for_keys(keys, custom_params = nil) ⇒ Object
437
438
439
440
441
442
443
444
445
446
447
|
# File 'lib/api/helpers.rb', line 437
def attributes_for_keys(keys, custom_params = nil)
params_hash = custom_params || params
attrs = {}
keys.each do |key|
if params_hash[key].present? || (params_hash.key?(key) && params_hash[key] == false)
attrs[key] = params_hash[key]
end
end
permitted_attrs = ActionController::Parameters.new(attrs).permit!
permitted_attrs.to_h
end
|
#authenticate! ⇒ Object
324
325
326
|
# File 'lib/api/helpers.rb', line 324
def authenticate!
unauthorized! unless current_user
end
|
#authenticate_by_gitlab_shell_token! ⇒ Object
#authenticate_non_get! ⇒ Object
328
329
330
|
# File 'lib/api/helpers.rb', line 328
def authenticate_non_get!
authenticate! unless %w[GET HEAD].include?(route.request_method)
end
|
#authenticated_as_admin! ⇒ Object
345
346
347
348
|
# File 'lib/api/helpers.rb', line 345
def authenticated_as_admin!
authenticate!
forbidden! unless current_user.can_admin_all_resources?
end
|
#authenticated_with_can_read_all_resources! ⇒ Object
340
341
342
343
|
# File 'lib/api/helpers.rb', line 340
def authenticated_with_can_read_all_resources!
authenticate!
forbidden! unless current_user.can_read_all_resources?
end
|
#authorize!(action, subject = :global, reason = nil) ⇒ Object
350
351
352
|
# File 'lib/api/helpers.rb', line 350
def authorize!(action, subject = :global, reason = nil)
forbidden!(reason) unless can?(current_user, action, subject)
end
|
#authorize_admin_group ⇒ Object
366
367
368
|
# File 'lib/api/helpers.rb', line 366
def authorize_admin_group
authorize! :admin_group, user_group
end
|
#authorize_admin_project ⇒ Object
362
363
364
|
# File 'lib/api/helpers.rb', line 362
def authorize_admin_project
authorize! :admin_project, user_project
end
|
#authorize_admin_tag ⇒ Object
358
359
360
|
# File 'lib/api/helpers.rb', line 358
def authorize_admin_tag
authorize! :admin_tag, user_project
end
|
#authorize_destroy_artifacts! ⇒ Object
386
387
388
|
# File 'lib/api/helpers.rb', line 386
def authorize_destroy_artifacts!
authorize! :destroy_artifacts, user_project
end
|
#authorize_push_project ⇒ Object
354
355
356
|
# File 'lib/api/helpers.rb', line 354
def authorize_push_project
authorize! :push_code, user_project
end
|
#authorize_read_build_trace!(build) ⇒ Object
378
379
380
|
# File 'lib/api/helpers.rb', line 378
def authorize_read_build_trace!(build)
authorize! :read_build_trace, build
end
|
#authorize_read_builds! ⇒ Object
370
371
372
|
# File 'lib/api/helpers.rb', line 370
def authorize_read_builds!
authorize! :read_build, user_project
end
|
#authorize_read_code! ⇒ Object
374
375
376
|
# File 'lib/api/helpers.rb', line 374
def authorize_read_code!
authorize! :read_code, user_project
end
|
#authorize_read_job_artifacts!(build) ⇒ Object
382
383
384
|
# File 'lib/api/helpers.rb', line 382
def authorize_read_job_artifacts!(build)
authorize! :read_job_artifacts, build
end
|
#authorize_update_builds! ⇒ Object
390
391
392
|
# File 'lib/api/helpers.rb', line 390
def authorize_update_builds!
authorize! :update_build, user_project
end
|
#authorized_project_scope?(project) ⇒ Boolean
178
179
180
181
182
183
184
|
# File 'lib/api/helpers.rb', line 178
def authorized_project_scope?(project)
return true unless job_token_authentication?
return true unless route_authentication_setting[:job_token_scope] == :project
::Feature.enabled?(:ci_job_token_scope, project) &&
current_authenticated_job.project == project
end
|
#available_labels_for(label_parent, params = { include_ancestor_groups: true, only_group_labels: true }) ⇒ Object
125
126
127
128
129
130
131
132
133
134
|
# File 'lib/api/helpers.rb', line 125
def available_labels_for(label_parent, params = { include_ancestor_groups: true, only_group_labels: true })
if label_parent.is_a?(Project)
params.delete(:only_group_labels)
params[:project_id] = label_parent.id
else
params[:group_id] = label_parent.id
end
LabelsFinder.new(current_user, params).execute
end
|
#bad_request!(reason = nil) ⇒ Object
490
491
492
|
# File 'lib/api/helpers.rb', line 490
def bad_request!(reason = nil)
render_api_error_with_reason!(400, '400 Bad request', reason)
end
|
#bad_request_missing_attribute!(attribute) ⇒ Object
494
495
496
|
# File 'lib/api/helpers.rb', line 494
def bad_request_missing_attribute!(attribute)
bad_request!("\"#{attribute}\" not given")
end
|
#can?(object, action, subject = :global) ⇒ Boolean
422
423
424
|
# File 'lib/api/helpers.rb', line 422
def can?(object, action, subject = :global)
Ability.allowed?(object, action, subject)
end
|
#cdn_fronted_url(file) ⇒ Object
677
678
679
680
681
682
683
684
685
|
# File 'lib/api/helpers.rb', line 677
def cdn_fronted_url(file)
if file.respond_to?(:cdn_enabled_url)
result = file.cdn_enabled_url(ip_address)
Gitlab::ApplicationContext.push(artifact_used_cdn: result.used_cdn)
result.url
else
file.url
end
end
|
#check_group_access(group) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord
232
233
234
235
236
237
|
# File 'lib/api/helpers.rb', line 232
def check_group_access(group)
return group if can?(current_user, :read_group, group)
return unauthorized! if authenticate_non_public?
not_found!('Group')
end
|
#check_namespace_access(namespace) ⇒ Object
239
240
241
242
243
|
# File 'lib/api/helpers.rb', line 239
def check_namespace_access(namespace)
return namespace if can?(current_user, :read_namespace_via_membership, namespace)
not_found!('Namespace')
end
|
#check_pipeline_access(pipeline) ⇒ Object
201
202
203
204
205
206
207
208
|
# File 'lib/api/helpers.rb', line 201
def check_pipeline_access(pipeline)
return forbidden! unless authorized_project_scope?(pipeline&.project)
return pipeline if can?(current_user, :read_pipeline, pipeline)
return unauthorized! if authenticate_non_public?
not_found!('Pipeline')
end
|
#check_sha_param!(params, merge_request) ⇒ Object
505
506
507
508
509
|
# File 'lib/api/helpers.rb', line 505
def check_sha_param!(params, merge_request)
if params[:sha] && merge_request.diff_head_sha != params[:sha]
render_api_error!("SHA does not match HEAD of source branch: #{merge_request.diff_head_sha}", 409)
end
end
|
#check_unmodified_since!(last_modified) ⇒ Object
33
34
35
36
37
38
39
40
41
42
43
|
# File 'lib/api/helpers.rb', line 33
def check_unmodified_since!(last_modified)
if_unmodified_since = begin
Time.parse(['If-Unmodified-Since'])
rescue StandardError
nil
end
if if_unmodified_since && last_modified && last_modified > if_unmodified_since
render_api_error!('412 Precondition Failed', 412)
end
end
|
#conflict!(message = nil) ⇒ Object
527
528
529
|
# File 'lib/api/helpers.rb', line 527
def conflict!(message = nil)
render_api_error!(message || '409 Conflict', 409)
end
|
#created! ⇒ Object
553
554
555
|
# File 'lib/api/helpers.rb', line 553
def created!
render_api_error!('201 Created', 201)
end
|
#current_authenticated_job ⇒ Object
Returns the job associated with the token provided for authentication, if any
66
67
68
69
70
71
72
|
# File 'lib/api/helpers.rb', line 66
def current_authenticated_job
if try(:namespace_inheritable, :authentication)
ci_build_from_namespace_inheritable
else
@current_authenticated_job end
end
|
#current_user ⇒ Object
rubocop:disable Gitlab/ModuleWithInstanceVariables We can’t rewrite this with StrongMemoize because ‘sudo!` would actually write to `@current_user`, and `sudo?` would immediately call `current_user` again which reads from `@current_user`. We should rewrite this in a way that using StrongMemoize is possible
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
# File 'lib/api/helpers.rb', line 79
def current_user
return @current_user if defined?(@current_user)
@current_user = initial_current_user
Gitlab::I18n.locale = @current_user&.preferred_language
sudo!
validate_access_token!(scopes: scopes_registered_for_endpoint) unless sudo?
save_current_user_in_env(@current_user) if @current_user
save_current_token_in_env
if @current_user
load_balancer_stick_request(::ApplicationRecord, :user, @current_user.id)
end
@current_user
end
|
#declared_params(options = {}) ⇒ Object
28
29
30
31
|
# File 'lib/api/helpers.rb', line 28
def declared_params(options = {})
options = { include_parent_namespaces: false }.merge(options)
declared(params, options).to_h.symbolize_keys
end
|
#destroy_conditionally!(resource, last_updated: nil) ⇒ Object
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/api/helpers.rb', line 45
def destroy_conditionally!(resource, last_updated: nil)
last_updated ||= resource.updated_at
check_unmodified_since!(last_updated)
status 204
body false
if block_given?
yield resource
else
resource.destroy
end
end
|
#file_too_large! ⇒ Object
535
536
537
|
# File 'lib/api/helpers.rb', line 535
def file_too_large!
render_api_error!('413 Request Entity Too Large', 413)
end
|
#filter_by_iid(items, iid) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
450
451
452
|
# File 'lib/api/helpers.rb', line 450
def filter_by_iid(items, iid)
items.where(iid: iid)
end
|
#filter_by_search(items, text) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord
461
462
463
|
# File 'lib/api/helpers.rb', line 461
def filter_by_search(items, text)
items.search(text)
end
|
#filter_by_title(items, title) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
456
457
458
|
# File 'lib/api/helpers.rb', line 456
def filter_by_title(items, title)
items.where(title: title)
end
|
#find_branch!(branch_name) ⇒ Object
270
271
272
273
274
275
276
|
# File 'lib/api/helpers.rb', line 270
def find_branch!(branch_name)
if Gitlab::GitRefValidator.validate(branch_name)
user_project.repository.find_branch(branch_name) || not_found!('Branch')
else
render_api_error!('The branch refname is invalid', 400)
end
end
|
#find_build!(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord
316
317
318
|
# File 'lib/api/helpers.rb', line 316
def find_build!(id)
user_project.builds.find(id.to_i)
end
|
#find_group(id) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
#find_group!(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord
220
221
222
223
|
# File 'lib/api/helpers.rb', line 220
def find_group!(id)
group = find_group(id)
check_group_access(group)
end
|
#find_group_by_full_path!(full_path) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
226
227
228
229
|
# File 'lib/api/helpers.rb', line 226
def find_group_by_full_path!(full_path)
group = Group.find_by_full_path(full_path)
check_group_access(group)
end
|
#find_job!(id) ⇒ Object
320
321
322
|
# File 'lib/api/helpers.rb', line 320
def find_job!(id)
user_project.processables.find(id.to_i)
end
|
#find_merge_request_with_access(iid, access_level = :read_merge_request) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
309
310
311
312
313
|
# File 'lib/api/helpers.rb', line 309
def find_merge_request_with_access(iid, access_level = :read_merge_request)
merge_request = user_project.merge_requests.find_by!(iid: iid)
authorize! access_level, merge_request
merge_request
end
|
#find_namespace(id) ⇒ Object
find_namespace returns the namespace regardless of user access level on the namespace rubocop: disable CodeReuse/ActiveRecord
247
248
249
250
251
252
253
|
# File 'lib/api/helpers.rb', line 247
def find_namespace(id)
if id.to_s =~ INTEGER_ID_REGEX
Namespace.without_project_namespaces.find_by(id: id)
else
find_namespace_by_path(id)
end
end
|
#find_namespace!(id) ⇒ Object
find_namespace! returns the namespace if the current user can read the given namespace Otherwise, returns a not_found! error
258
259
260
|
# File 'lib/api/helpers.rb', line 258
def find_namespace!(id)
check_namespace_access(find_namespace(id))
end
|
#find_namespace_by_path(path) ⇒ Object
262
263
264
|
# File 'lib/api/helpers.rb', line 262
def find_namespace_by_path(path)
Namespace.without_project_namespaces.find_by_full_path(path)
end
|
#find_namespace_by_path!(path) ⇒ Object
266
267
268
|
# File 'lib/api/helpers.rb', line 266
def find_namespace_by_path!(path)
check_namespace_access(find_namespace_by_path(path))
end
|
#find_pipeline(id) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
187
188
189
190
191
192
193
|
# File 'lib/api/helpers.rb', line 187
def find_pipeline(id)
return unless id
if id.to_s =~ INTEGER_ID_REGEX
::Ci::Pipeline.find_by(id: id)
end
end
|
#find_pipeline!(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord
196
197
198
199
|
# File 'lib/api/helpers.rb', line 196
def find_pipeline!(id)
pipeline = find_pipeline(id)
check_pipeline_access(pipeline)
end
|
#find_project(id) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
141
142
143
144
145
146
147
148
149
150
151
|
# File 'lib/api/helpers.rb', line 141
def find_project(id)
return unless id
projects = Project.without_deleted.not_hidden
if id.is_a?(Integer) || id =~ INTEGER_ID_REGEX
projects.find_by(id: id)
elsif id.include?("/")
projects.find_by_full_path(id, follow_redirects: Feature.enabled?(:api_redirect_moved_projects))
end
end
|
#find_project!(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
|
# File 'lib/api/helpers.rb', line 154
def find_project!(id)
project = find_project(id)
return forbidden! unless authorized_project_scope?(project)
unless can?(current_user, read_project_ability, project)
return unauthorized! if authenticate_non_public?
return not_found!('Project')
end
if project_moved?(id, project)
return not_allowed!('Non GET methods are not allowed for moved projects') unless request.get?
return redirect!(url_with_project_id(project))
end
project
end
|
#find_project_commit(id) ⇒ Object
rubocop: enable CodeReuse/ActiveRecord
304
305
306
|
# File 'lib/api/helpers.rb', line 304
def find_project_commit(id)
user_project.commit_by(oid: id)
end
|
#find_project_issue(iid, project_id = nil) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
287
288
289
290
291
292
293
294
295
|
# File 'lib/api/helpers.rb', line 287
def find_project_issue(iid, project_id = nil)
project = project_id ? find_project!(project_id) : user_project
::IssuesFinder.new(
current_user,
project_id: project.id,
issue_types: WorkItems::Type.allowed_types_for_issues
).find_by!(iid: iid)
end
|
#find_project_merge_request(iid) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
299
300
301
|
# File 'lib/api/helpers.rb', line 299
def find_project_merge_request(iid)
MergeRequestsFinder.new(current_user, project_id: user_project.id).find_by!(iid: iid)
end
|
#find_tag!(tag_name) ⇒ Object
278
279
280
281
282
283
284
|
# File 'lib/api/helpers.rb', line 278
def find_tag!(tag_name)
if Gitlab::GitRefValidator.validate(tag_name)
user_project.repository.find_tag(tag_name) || not_found!('Tag')
else
render_api_error!('The tag refname is invalid', 400)
end
end
|
#forbidden!(reason = nil) ⇒ Object
486
487
488
|
# File 'lib/api/helpers.rb', line 486
def forbidden!(reason = nil)
render_api_error_with_reason!(403, '403 Forbidden', reason)
end
|
#handle_api_exception(exception) ⇒ Object
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
|
# File 'lib/api/helpers.rb', line 595
def handle_api_exception(exception)
if report_exception?(exception)
define_params_for_grape_middleware
Gitlab::ApplicationContext.push(user: current_user, remote_ip: request.ip)
Gitlab::ErrorTracking.track_exception(exception)
end
env[API_EXCEPTION_ENV] = exception
trace = exception.backtrace
message = ["\n#{exception.class} (#{exception.message}):\n"]
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
message << " " << trace.join("\n ")
message = message.join
API.logger.add Logger::FATAL, message
response_message =
if Rails.env.test?
message
else
'500 Internal Server Error'
end
rack_response({ 'message' => response_message }.to_json, 500)
end
|
#increment_counter(event_name) ⇒ Object
687
688
689
690
691
|
# File 'lib/api/helpers.rb', line 687
def increment_counter(event_name)
Gitlab::UsageDataCounters.count(event_name)
rescue StandardError => error
Gitlab::AppLogger.warn("Redis tracking event failed for event: #{event_name}, message: #{error.message}")
end
|
#increment_unique_values(event_name, values) ⇒ Object
695
696
697
698
699
700
701
|
# File 'lib/api/helpers.rb', line 695
def increment_unique_values(event_name, values)
return unless values.present?
Gitlab::UsageDataCounters::HLLRedisCounter.track_event(event_name, values: values)
rescue StandardError => error
Gitlab::AppLogger.warn("Redis tracking event failed for event: #{event_name}, message: #{error.message}")
end
|
#job_token_authentication? ⇒ Boolean
60
61
62
|
# File 'lib/api/helpers.rb', line 60
def job_token_authentication?
initial_current_user && @current_authenticated_job.present? end
|
#logger ⇒ Object
24
25
26
|
# File 'lib/api/helpers.rb', line 24
def logger
API.logger
end
|
#model_errors(model) ⇒ Object
567
568
569
|
# File 'lib/api/helpers.rb', line 567
def model_errors(model)
model.errors
end
|
#no_content! ⇒ Object
549
550
551
|
# File 'lib/api/helpers.rb', line 549
def no_content!
render_api_error!('204 No Content', 204)
end
|
#not_acceptable! ⇒ Object
519
520
521
|
# File 'lib/api/helpers.rb', line 519
def not_acceptable!
render_api_error!('406 Not Acceptable', 406)
end
|
#not_allowed!(message = nil) ⇒ Object
515
516
517
|
# File 'lib/api/helpers.rb', line 515
def not_allowed!(message = nil)
render_api_error!(message || '405 Method Not Allowed', :method_not_allowed)
end
|
#not_found!(resource = nil) ⇒ Object
498
499
500
501
502
503
|
# File 'lib/api/helpers.rb', line 498
def not_found!(resource = nil)
message = ["404"]
message << resource if resource
message << "Not Found"
render_api_error!(message.join(' '), 404)
end
|
#not_modified! ⇒ Object
545
546
547
|
# File 'lib/api/helpers.rb', line 545
def not_modified!
render_api_error!('304 Not Modified', 304)
end
|
#order_by_similarity?(allow_unauthorized: true) ⇒ Boolean
719
720
721
|
# File 'lib/api/helpers.rb', line 719
def order_by_similarity?(allow_unauthorized: true)
params[:order_by] == 'similarity' && params[:search].present? && (allow_unauthorized || current_user.present?)
end
|
#order_options_with_tie_breaker ⇒ Object
465
466
467
468
469
470
471
472
473
474
475
|
# File 'lib/api/helpers.rb', line 465
def order_options_with_tie_breaker
order_by = if params[:order_by] == 'created_at'
'id'
else
params[:order_by]
end
order_options = { order_by => params[:sort] }
order_options['id'] ||= params[:sort] || 'asc'
order_options
end
|
#present_artifacts_file!(file, **args) ⇒ Object
655
656
657
658
659
|
# File 'lib/api/helpers.rb', line 655
def present_artifacts_file!(file, **args)
log_artifacts_filesize(file&.model)
present_carrierwave_file!(file, **args)
end
|
#present_carrierwave_file!(file, supports_direct_download: true) ⇒ Object
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
|
# File 'lib/api/helpers.rb', line 661
def present_carrierwave_file!(file, supports_direct_download: true)
return not_found! unless file&.exists?
if file.file_storage?
present_disk_file!(file.path, file.filename)
elsif supports_direct_download && file.class.direct_download_enabled?
return redirect(ObjectStorage::S3.signed_head_url(file)) if request.head? && file.fog_credentials[:provider] == 'AWS'
redirect(cdn_fronted_url(file))
else
(*Gitlab::Workhorse.send_url(file.url))
status :ok
body '' end
end
|
#present_disk_file!(path, filename, content_type = 'application/octet-stream') ⇒ Object
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
|
# File 'lib/api/helpers.rb', line 639
def present_disk_file!(path, filename, content_type = 'application/octet-stream')
filename ||= File.basename(path)
['Content-Disposition'] = ActionDispatch::Http::ContentDisposition.format(disposition: 'attachment', filename: filename)
['Content-Transfer-Encoding'] = 'binary'
content_type content_type
case ['X-Sendfile-Type']
when 'X-Sendfile'
['X-Sendfile'] = path
body '' else
sendfile path
end
end
|
#process_create_params(args) ⇒ Object
78
79
80
81
82
83
84
85
|
# File 'lib/api/helpers/snippets_helpers.rb', line 78
def process_create_params(args)
args[:snippet_actions] = args.delete(:files)&.map do |file|
file[:action] = :create
file.symbolize_keys
end
args
end
|
#process_update_params(args) ⇒ Object
87
88
89
90
91
|
# File 'lib/api/helpers/snippets_helpers.rb', line 87
def process_update_params(args)
args[:snippet_actions] = args.delete(:files)&.map(&:symbolize_keys)
args
end
|
#project_finder_params ⇒ Object
rubocop: enable CodeReuse/ActiveRecord
633
634
635
|
# File 'lib/api/helpers.rb', line 633
def project_finder_params
project_finder_params_ce.merge(project_finder_params_ee)
end
|
#read_project_ability ⇒ Object
174
175
176
|
# File 'lib/api/helpers.rb', line 174
def read_project_ability
:read_project
end
|
#redirect!(location_url) ⇒ Object
An error is raised to interrupt user’s request and redirect them to the right route. The error! helper behaves similarly, but it cannot be used because it formats the response message.
480
481
482
|
# File 'lib/api/helpers.rb', line 480
def redirect!(location_url)
raise ::API::API::MovedPermanentlyError, location_url
end
|
#render_api_error!(message, status) ⇒ Object
577
578
579
|
# File 'lib/api/helpers.rb', line 577
def render_api_error!(message, status)
render_structured_api_error!({ 'message' => message }, status)
end
|
#render_api_error_with_reason!(status, message, reason) ⇒ Object
571
572
573
574
575
|
# File 'lib/api/helpers.rb', line 571
def render_api_error_with_reason!(status, message, reason)
message = [message]
message << "- #{reason}" if reason
render_api_error!(message.join(' '), status)
end
|
#render_structured_api_error!(hash, status) ⇒ Object
581
582
583
584
585
586
|
# File 'lib/api/helpers.rb', line 581
def render_structured_api_error!(hash, status)
set_status_code_in_env(status)
error!(hash, status, )
end
|
#render_validation_error!(model, status = 400) ⇒ Object
561
562
563
564
565
|
# File 'lib/api/helpers.rb', line 561
def render_validation_error!(model, status = 400)
if model.errors.any?
render_api_error!(model_errors(model).messages || '400 Bad Request', status)
end
end
|
#reorder_projects(projects) ⇒ Object
rubocop: disable CodeReuse/ActiveRecord
628
629
630
|
# File 'lib/api/helpers.rb', line 628
def reorder_projects(projects)
projects.reorder(order_options_with_tie_breaker)
end
|
#require_gitlab_workhorse! ⇒ Object
398
399
400
401
402
403
404
|
# File 'lib/api/helpers.rb', line 398
def require_gitlab_workhorse!
verify_workhorse_api!
unless env['HTTP_GITLAB_WORKHORSE'].present?
forbidden!('Request should be executed via GitLab Workhorse')
end
end
|
#require_pages_config_enabled! ⇒ Object
418
419
420
|
# File 'lib/api/helpers.rb', line 418
def require_pages_config_enabled!
not_found! unless Gitlab.config.pages.enabled
end
|
#require_pages_enabled! ⇒ Object
414
415
416
|
# File 'lib/api/helpers.rb', line 414
def require_pages_enabled!
not_found! unless user_project.pages_available?
end
|
#require_repository_enabled!(subject = :global) ⇒ Object
394
395
396
|
# File 'lib/api/helpers.rb', line 394
def require_repository_enabled!(subject = :global)
not_found!("Repository") unless user_project.feature_available?(:repository, current_user)
end
|
#required_attributes!(keys) ⇒ Object
Checks the occurrences of required attributes, each attribute must be present in the params hash or a Bad Request error is invoked.
Parameters:
keys (required) - A hash consisting of keys that must be present
431
432
433
434
435
|
# File 'lib/api/helpers.rb', line 431
def required_attributes!(keys)
keys.each do |key|
bad_request_missing_attribute!(key) unless params[key].present?
end
end
|
#save_current_token_in_env ⇒ Object
106
107
108
109
110
111
|
# File 'lib/api/helpers.rb', line 106
def save_current_token_in_env
token = access_token
env[API_TOKEN_ENV] = { token_id: token.id, token_type: token.class } if token
rescue Gitlab::Auth::UnauthorizedError
end
|
#save_current_user_in_env(user) ⇒ Object
rubocop:enable Gitlab/ModuleWithInstanceVariables
102
103
104
|
# File 'lib/api/helpers.rb', line 102
def save_current_user_in_env(user)
env[API_USER_ENV] = { user_id: user.id, username: user.username }
end
|
#service_unavailable!(message = nil) ⇒ Object
523
524
525
|
# File 'lib/api/helpers.rb', line 523
def service_unavailable!(message = nil)
render_api_error!(message || '503 Service Unavailable', 503)
end
|
#set_status_code_in_env(status) ⇒ Object
588
589
590
591
592
593
|
# File 'lib/api/helpers.rb', line 588
def set_status_code_in_env(status)
env[API_RESPONSE_STATUS_CODE] = Rack::Utils.status_code(status)
end
|
#sudo? ⇒ Boolean
113
114
115
|
# File 'lib/api/helpers.rb', line 113
def sudo?
initial_current_user != current_user
end
|
#too_many_requests!(message = nil, retry_after: 1.minute) ⇒ Object
539
540
541
542
543
|
# File 'lib/api/helpers.rb', line 539
def too_many_requests!(message = nil, retry_after: 1.minute)
['Retry-After'] = retry_after.to_i if retry_after
render_api_error!(message || '429 Too Many Requests', 429)
end
|
#track_event(event_name, user:, namespace_id: nil, project_id: nil) ⇒ Object
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
|
# File 'lib/api/helpers.rb', line 703
def track_event(event_name, user:, namespace_id: nil, project_id: nil)
return unless user.present?
namespace = Namespace.find(namespace_id) if namespace_id
project = Project.find(project_id) if project_id
Gitlab::InternalEvents.track_event(
event_name,
user: user,
namespace: namespace,
project: project
)
rescue StandardError => e
Gitlab::ErrorTracking.track_and_raise_for_dev_exception(e, event_name: event_name)
end
|
#unauthorized!(reason = nil) ⇒ Object
511
512
513
|
# File 'lib/api/helpers.rb', line 511
def unauthorized!(reason = nil)
render_api_error_with_reason!(401, '401 Unauthorized', reason)
end
|
#unprocessable_entity!(message = nil) ⇒ Object
531
532
533
|
# File 'lib/api/helpers.rb', line 531
def unprocessable_entity!(message = nil)
render_api_error!(message || '422 Unprocessable Entity', :unprocessable_entity)
end
|
#user_group ⇒ Object
117
118
119
|
# File 'lib/api/helpers.rb', line 117
def user_group
@group ||= find_group!(params[:id])
end
|
#user_project ⇒ Object
121
122
123
|
# File 'lib/api/helpers.rb', line 121
def user_project
@project ||= find_project!(params[:id])
end
|
#validate_params_for_multiple_files(snippet) ⇒ Object
93
94
95
96
97
98
99
|
# File 'lib/api/helpers/snippets_helpers.rb', line 93
def validate_params_for_multiple_files(snippet)
return unless params[:content] || params[:file_name]
if snippet.multiple_files?
render_api_error!({ error: _('To update Snippets with multiple files, you must use the `files` parameter') }, 400)
end
end
|
#verify_workhorse_api! ⇒ Object