debian-mirror-gitlab/app/models/ci/secure_file.rb

87 lines
2.2 KiB
Ruby
Raw Normal View History

2022-03-02 08:16:31 +05:30
# frozen_string_literal: true
module Ci
class SecureFile < Ci::ApplicationRecord
include FileStoreMounter
2022-05-07 20:08:51 +05:30
include Limitable
2022-03-02 08:16:31 +05:30
FILE_SIZE_LIMIT = 5.megabytes.freeze
CHECKSUM_ALGORITHM = 'sha256'
2022-11-25 23:54:43 +05:30
PARSABLE_EXTENSIONS = %w[cer p12 mobileprovision].freeze
2022-03-02 08:16:31 +05:30
2022-05-07 20:08:51 +05:30
self.limit_scope = :project
self.limit_name = 'project_ci_secure_files'
2022-03-02 08:16:31 +05:30
belongs_to :project, optional: false
validates :file, presence: true, file_size: { maximum: FILE_SIZE_LIMIT }
2022-07-16 23:28:13 +05:30
validates :checksum, :file_store, :name, :project_id, presence: true
2022-06-21 17:19:12 +05:30
validates :name, uniqueness: { scope: :project }
2023-03-04 22:38:38 +05:30
attribute :metadata, :ind_jsonb
2022-11-25 23:54:43 +05:30
validates :metadata, json_schema: { filename: "ci_secure_file_metadata" }, allow_nil: true
2022-03-02 08:16:31 +05:30
2023-03-04 22:38:38 +05:30
attribute :file_store, default: -> { Ci::SecureFileUploader.default_store }
mount_file_store_uploader Ci::SecureFileUploader
2022-06-21 17:19:12 +05:30
after_initialize :generate_key_data
2022-03-02 08:16:31 +05:30
before_validation :assign_checksum
2022-07-23 23:45:48 +05:30
scope :order_by_created_at, -> { order(created_at: :desc) }
2022-08-27 11:52:29 +05:30
scope :project_id_in, ->(ids) { where(project_id: ids) }
2022-07-23 23:45:48 +05:30
2022-03-02 08:16:31 +05:30
def checksum_algorithm
CHECKSUM_ALGORITHM
end
2022-11-25 23:54:43 +05:30
def file_extension
2023-04-23 21:23:45 +05:30
File.extname(name).delete_prefix('.').presence
2022-11-25 23:54:43 +05:30
end
def metadata_parsable?
PARSABLE_EXTENSIONS.include?(file_extension)
end
def metadata_parser
return unless metadata_parsable?
case file_extension
when 'cer'
Gitlab::Ci::SecureFiles::Cer.new(file.read)
when 'p12'
Gitlab::Ci::SecureFiles::P12.new(file.read)
when 'mobileprovision'
Gitlab::Ci::SecureFiles::MobileProvision.new(file.read)
end
end
def update_metadata!
return unless metadata_parser
begin
parser = metadata_parser
self.metadata = parser.metadata
self.expires_at = parser.metadata[:expires_at]
save!
rescue StandardError => err
Gitlab::AppLogger.error("Secure File Parser Failure (#{id}): #{err.message} - #{parser.error}.")
nil
end
end
2022-03-02 08:16:31 +05:30
private
def assign_checksum
self.checksum = file.checksum if file.present? && file_changed?
end
2022-06-21 17:19:12 +05:30
def generate_key_data
return if key_data.present?
self.key_data = SecureRandom.hex(64)
end
2022-03-02 08:16:31 +05:30
end
end
2022-08-27 11:52:29 +05:30
Ci::SecureFile.prepend_mod