Class: Gitlab::Email::Smime::Certificate

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/email/smime/certificate.rb

Constant Summary collapse

CERT_REGEX =
/-----BEGIN CERTIFICATE-----(?:.|\n)+?-----END CERTIFICATE-----/.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, cert, ca_certs = nil) ⇒ Certificate

Returns a new instance of Certificate.


50
51
52
53
54
# File 'lib/gitlab/email/smime/certificate.rb', line 50

def initialize(key, cert, ca_certs = nil)
  @key = key
  @cert = cert
  @ca_certs = ca_certs
end

Instance Attribute Details

#ca_certsObject (readonly)

Returns the value of attribute ca_certs


9
10
11
# File 'lib/gitlab/email/smime/certificate.rb', line 9

def ca_certs
  @ca_certs
end

#certObject (readonly)

Returns the value of attribute cert


9
10
11
# File 'lib/gitlab/email/smime/certificate.rb', line 9

def cert
  @cert
end

#keyObject (readonly)

Returns the value of attribute key


9
10
11
# File 'lib/gitlab/email/smime/certificate.rb', line 9

def key
  @key
end

Class Method Details

.from_files(key_path, cert_path, ca_certs_path = nil) ⇒ Object


31
32
33
34
35
# File 'lib/gitlab/email/smime/certificate.rb', line 31

def self.from_files(key_path, cert_path, ca_certs_path = nil)
  ca_certs_string = File.read(ca_certs_path) if ca_certs_path

  from_strings(File.read(key_path), File.read(cert_path), ca_certs_string)
end

.from_strings(key_string, cert_string, ca_certs_string = nil) ⇒ Object


23
24
25
26
27
28
29
# File 'lib/gitlab/email/smime/certificate.rb', line 23

def self.from_strings(key_string, cert_string, ca_certs_string = nil)
  key = OpenSSL::PKey::RSA.new(key_string)
  cert = OpenSSL::X509::Certificate.new(cert_string)
  ca_certs = load_ca_certs_bundle(ca_certs_string)

  new(key, cert, ca_certs)
end

.load_ca_certs_bundle(ca_certs_string) ⇒ Object

Returns an array of OpenSSL::X509::Certificate objects, empty array if none found

Ruby OpenSSL::X509::Certificate.new will only load the first certificate if a bundle is presented, this allows to parse multiple certs in the same file


42
43
44
45
46
47
48
# File 'lib/gitlab/email/smime/certificate.rb', line 42

def self.load_ca_certs_bundle(ca_certs_string)
  return [] unless ca_certs_string

  ca_certs_string.scan(CERT_REGEX).map do |ca_cert_string|
    OpenSSL::X509::Certificate.new(ca_cert_string)
  end
end

Instance Method Details

#ca_certs_stringObject


19
20
21
# File 'lib/gitlab/email/smime/certificate.rb', line 19

def ca_certs_string
  ca_certs.map(&:to_pem).join('\n') unless ca_certs.blank?
end

#cert_stringObject


15
16
17
# File 'lib/gitlab/email/smime/certificate.rb', line 15

def cert_string
  cert.to_pem
end

#key_stringObject


11
12
13
# File 'lib/gitlab/email/smime/certificate.rb', line 11

def key_string
  key.to_s
end