summaryrefslogtreecommitdiff
path: root/app/services/audit_event_service.rb
blob: fb309aed6494f5d68b3b7d439d0f6b07b6bfe38d (plain)
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
# frozen_string_literal: true

class AuditEventService
  # Instantiates a new service
  #
  # @param [User] author the user who authors the change
  # @param [User, Project, Group] entity the scope which audit event belongs to
  #   This param is also used to determine the visibility of the audit event.
  #   - Project: events are visible at Project and Instance level
  #   - Group: events are visible at Group and Instance level
  #   - User: events are visible at Instance level
  # @param [Hash] details extra data of audit event
  #
  # @return [AuditEventService]
  def initialize(author, entity, details = {})
    @author = build_author(author)
    @entity = entity
    @details = details
  end

  # Builds the @details attribute for authentication
  #
  # This uses the @author as the target object being audited
  #
  # @return [AuditEventService]
  def for_authentication
    @details = {
      with: @details[:with],
      target_id: @author.id,
      target_type: 'User',
      target_details: @author.name
    }

    self
  end

  # Writes event to a file and creates an event record in DB
  #
  # @return [SecurityEvent] persited if saves and non-persisted if fails
  def security_event
    log_security_event_to_file
    log_security_event_to_database
  end

  # Writes event to a file
  def log_security_event_to_file
    file_logger.info(base_payload.merge(formatted_details))
  end

  private

  def build_author(author)
    case author
    when User
      author.impersonated? ? Gitlab::Audit::ImpersonatedAuthor.new(author) : author
    else
      Gitlab::Audit::UnauthenticatedAuthor.new(name: author)
    end
  end

  def base_payload
    {
      author_id: @author.id,
      entity_id: @entity.id,
      entity_type: @entity.class.name
    }
  end

  def file_logger
    @file_logger ||= Gitlab::AuditJsonLogger.build
  end

  def formatted_details
    @details.merge(@details.slice(:from, :to).transform_values(&:to_s))
  end

  def log_security_event_to_database
    return if Gitlab::Database.read_only?

    SecurityEvent.create(base_payload.merge(details: @details))
  end
end

AuditEventService.prepend_if_ee('EE::AuditEventService')