summaryrefslogtreecommitdiff
path: root/app/models/personal_access_token.rb
blob: 9ed25c56ed6f82c83c289e7413b44c612e7f4e31 (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
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
# frozen_string_literal: true

class PersonalAccessToken < ApplicationRecord
  include Expirable
  include TokenAuthenticatable
  include Sortable
  include EachBatch
  extend ::Gitlab::Utils::Override

  add_authentication_token_field :token, digest: true

  REDIS_EXPIRY_TIME = 3.minutes

  # PATs are 20 characters + optional configurable settings prefix (0..20)
  TOKEN_LENGTH_RANGE = (20..40).freeze

  serialize :scopes, Array # rubocop:disable Cop/ActiveRecordSerialize

  belongs_to :user

  before_save :ensure_token

  scope :active, -> { not_revoked.not_expired }
  scope :expiring_and_not_notified, ->(date) { where(["revoked = false AND expire_notification_delivered = false AND expires_at >= CURRENT_DATE AND expires_at <= ?", date]) }
  scope :expired_today_and_not_notified, -> { where(["revoked = false AND expires_at = CURRENT_DATE AND after_expiry_notification_delivered = false"]) }
  scope :inactive, -> { where("revoked = true OR expires_at < CURRENT_DATE") }
  scope :created_before, -> (date) { where("personal_access_tokens.created_at < :date", date: date) }
  scope :last_used_before_or_unused, -> (date) { where("personal_access_tokens.created_at < :date AND (last_used_at < :date OR last_used_at IS NULL)", date: date) }
  scope :with_impersonation, -> { where(impersonation: true) }
  scope :without_impersonation, -> { where(impersonation: false) }
  scope :revoked, -> { where(revoked: true) }
  scope :not_revoked, -> { where(revoked: [false, nil]) }
  scope :for_user, -> (user) { where(user: user) }
  scope :for_users, -> (users) { where(user: users) }
  scope :preload_users, -> { preload(:user) }
  scope :order_expires_at_asc, -> { reorder(expires_at: :asc) }
  scope :order_expires_at_desc, -> { reorder(expires_at: :desc) }
  scope :order_expires_at_asc_id_desc, -> { reorder(expires_at: :asc, id: :desc) }
  scope :project_access_token, -> { includes(:user).where(user: { user_type: :project_bot }) }
  scope :owner_is_human, -> { includes(:user).where(user: { user_type: :human }) }

  validates :scopes, presence: true
  validate :validate_scopes

  after_initialize :set_default_scopes, if: :persisted?

  def revoke!
    update!(revoked: true)
  end

  def active?
    !revoked? && !expired?
  end

  def self.redis_getdel(user_id)
    Gitlab::Redis::SharedState.with do |redis|
      redis_key = redis_shared_state_key(user_id)
      encrypted_token = redis.get(redis_key)
      redis.del(redis_key)

      begin
        Gitlab::CryptoHelper.aes256_gcm_decrypt(encrypted_token)
      rescue StandardError => e
        logger.warn "Failed to decrypt #{self.name} value stored in Redis for key ##{redis_key}: #{e.class}"
        encrypted_token
      end
    end
  end

  def self.redis_store!(user_id, token)
    encrypted_token = Gitlab::CryptoHelper.aes256_gcm_encrypt(token)

    Gitlab::Redis::SharedState.with do |redis|
      redis.set(redis_shared_state_key(user_id), encrypted_token, ex: REDIS_EXPIRY_TIME)
    end
  end

  override :simple_sorts
  def self.simple_sorts
    super.merge(
      {
        'expires_at_asc' => -> { order_expires_at_asc },
        'expires_at_desc' => -> { order_expires_at_desc },
        'expires_at_asc_id_desc' => -> { order_expires_at_asc_id_desc }
      }
    )
  end

  def self.token_prefix
    Gitlab::CurrentSettings.current_application_settings.personal_access_token_prefix
  end

  override :format_token
  def format_token(token)
    "#{self.class.token_prefix}#{token}"
  end

  def project_access_token?
    user&.project_bot?
  end

  protected

  def validate_scopes
    unless revoked || scopes.all? { |scope| Gitlab::Auth.all_available_scopes.include?(scope.to_sym) }
      errors.add :scopes, "can only contain available scopes"
    end
  end

  def set_default_scopes
    # When only loading a select set of attributes, for example using `EachBatch`,
    # the `scopes` attribute is not present, so we can't initialize it.
    return unless has_attribute?(:scopes)

    self.scopes = Gitlab::Auth::DEFAULT_SCOPES if self.scopes.empty?
  end

  def self.redis_shared_state_key(user_id)
    "gitlab:personal_access_token:#{user_id}"
  end
end

PersonalAccessToken.prepend_mod_with('PersonalAccessToken')