Commit 1086983d authored by Sean McGivern's avatar Sean McGivern

Merge branch 'sh-store-user-in-api-logs' into 'master'

Save user ID and username in Grape API log (api_json.log)

See merge request gitlab-org/gitlab-ce!16264
parents 2a808cb0 eaf9088b
---
title: Save user ID and username in Grape API log (api_json.log)
merge_request:
author:
type: changed
...@@ -13,7 +13,8 @@ module API ...@@ -13,7 +13,8 @@ module API
formatter: Gitlab::GrapeLogging::Formatters::LogrageWithTimestamp.new, formatter: Gitlab::GrapeLogging::Formatters::LogrageWithTimestamp.new,
include: [ include: [
GrapeLogging::Loggers::FilterParameters.new, GrapeLogging::Loggers::FilterParameters.new,
GrapeLogging::Loggers::ClientEnv.new GrapeLogging::Loggers::ClientEnv.new,
Gitlab::GrapeLogging::Loggers::UserLogger.new
] ]
allow_access_with_scope :api allow_access_with_scope :api
......
...@@ -5,6 +5,7 @@ module API ...@@ -5,6 +5,7 @@ module API
SUDO_HEADER = "HTTP_SUDO".freeze SUDO_HEADER = "HTTP_SUDO".freeze
SUDO_PARAM = :sudo SUDO_PARAM = :sudo
API_USER_ENV = 'gitlab.api.user'.freeze
def declared_params(options = {}) def declared_params(options = {})
options = { include_parent_namespaces: false }.merge(options) options = { include_parent_namespaces: false }.merge(options)
...@@ -48,10 +49,16 @@ module API ...@@ -48,10 +49,16 @@ module API
validate_access_token!(scopes: scopes_registered_for_endpoint) unless sudo? validate_access_token!(scopes: scopes_registered_for_endpoint) unless sudo?
save_current_user_in_env(@current_user) if @current_user
@current_user @current_user
end end
# rubocop:enable Gitlab/ModuleWithInstanceVariables # 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? def sudo?
initial_current_user != current_user initial_current_user != current_user
end end
......
# 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
...@@ -68,6 +68,12 @@ describe API::Helpers do ...@@ -68,6 +68,12 @@ describe API::Helpers do
end end
it { is_expected.to eq(user) } it { is_expected.to eq(user) }
it 'sets the environment with data of the current user' do
subject
expect(env[API::Helpers::API_USER_ENV]).to eq({ user_id: subject.id, username: subject.username })
end
end end
context "HEAD request" do context "HEAD request" do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment