diff options
author | Stan Hu <stanhu@gmail.com> | 2018-01-06 00:41:13 -0800 |
---|---|---|
committer | Stan Hu <stanhu@gmail.com> | 2018-01-08 21:23:24 -0800 |
commit | eaf9088ba8abe8c847a09860b55a86c7ae0d5987 (patch) | |
tree | 6aa8b076c5f598f8c0efa9ea7ef8d4e08870839a /lib | |
parent | 7b2f9af4486b26512a2fefb3f385a2b8fa65a068 (diff) | |
download | gitlab-ce-eaf9088ba8abe8c847a09860b55a86c7ae0d5987.tar.gz |
Save user ID and username in Grape API log (api_json.log)sh-store-user-in-api-logs
This will enable admins to identify who actually made the API request.
Relates to #36960
Diffstat (limited to 'lib')
-rw-r--r-- | lib/api/api.rb | 3 | ||||
-rw-r--r-- | lib/api/helpers.rb | 7 | ||||
-rw-r--r-- | lib/gitlab/grape_logging/loggers/user_logger.rb | 18 |
3 files changed, 27 insertions, 1 deletions
diff --git a/lib/api/api.rb b/lib/api/api.rb index e0d14281c96..ae161efb358 100644 --- a/lib/api/api.rb +++ b/lib/api/api.rb @@ -13,7 +13,8 @@ module API formatter: Gitlab::GrapeLogging::Formatters::LogrageWithTimestamp.new, include: [ GrapeLogging::Loggers::FilterParameters.new, - GrapeLogging::Loggers::ClientEnv.new + GrapeLogging::Loggers::ClientEnv.new, + Gitlab::GrapeLogging::Loggers::UserLogger.new ] allow_access_with_scope :api diff --git a/lib/api/helpers.rb b/lib/api/helpers.rb index bf388163ec8..d6ce368efd5 100644 --- a/lib/api/helpers.rb +++ b/lib/api/helpers.rb @@ -5,6 +5,7 @@ module API SUDO_HEADER = "HTTP_SUDO".freeze SUDO_PARAM = :sudo + API_USER_ENV = 'gitlab.api.user'.freeze def declared_params(options = {}) options = { include_parent_namespaces: false }.merge(options) @@ -48,10 +49,16 @@ module API validate_access_token!(scopes: scopes_registered_for_endpoint) unless sudo? + save_current_user_in_env(@current_user) if @current_user + @current_user end # rubocop:enable Gitlab/ModuleWithInstanceVariables + def save_current_user_in_env(user) + env[API_USER_ENV] = { user_id: user.id, username: user.username } + end + def sudo? initial_current_user != current_user end diff --git a/lib/gitlab/grape_logging/loggers/user_logger.rb b/lib/gitlab/grape_logging/loggers/user_logger.rb new file mode 100644 index 00000000000..fa172861967 --- /dev/null +++ b/lib/gitlab/grape_logging/loggers/user_logger.rb @@ -0,0 +1,18 @@ +# This grape_logging module (https://github.com/aserafin/grape_logging) makes it +# possible to log the user who performed the Grape API action by retrieving +# the user context from the request environment. +module Gitlab + module GrapeLogging + module Loggers + class UserLogger < ::GrapeLogging::Loggers::Base + def parameters(request, _) + params = request.env[::API::Helpers::API_USER_ENV] + + return {} unless params + + params.slice(:user_id, :username) + end + end + end + end +end |