Class: Tipi::ACME::CertificateManager

Inherits:
Object
  • Object
show all
Defined in:
lib/tipi/acme.rb

Constant Summary collapse

ACME_CHALLENGE_PATH_REGEXP =
/\/\.well\-known\/acme\-challenge/.freeze
IP_REGEXP =
/^\d+\.\d+\.\d+\.\d+$/
MAX_WAIT_FOR_CTX_DURATION =
30
LOCALHOST_REGEXP =
/\.?localhost$/.freeze
CERTIFICATE_REGEXP =
/(-----BEGIN CERTIFICATE-----\n[^-]+-----END CERTIFICATE-----\n)/.freeze
ACME_DIRECTORY =
'https://acme-v02.api.letsencrypt.org/directory'

Instance Method Summary collapse

Constructor Details

#initialize(master_ctx:, store:, challenge_handler:, valid_hosts:) ⇒ CertificateManager

Returns a new instance of CertificateManager.



13
14
15
16
17
18
19
20
21
22
# File 'lib/tipi/acme.rb', line 13

def initialize(master_ctx:, store:, challenge_handler:, valid_hosts:)
  @master_ctx = master_ctx
  @store = store
  @challenge_handler = challenge_handler
  @valid_hosts = valid_hosts
  @contexts = {}
  @requests = Polyphony::Queue.new
  @worker = spin { run }
  setup_sni_callback
end

Instance Method Details

#acme_clientObject



150
151
152
# File 'lib/tipi/acme.rb', line 150

def acme_client
  @acme_client ||= setup_acme_client
end

#challenge_routing_app(app) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/tipi/acme.rb', line 26

def challenge_routing_app(app)
  ->(req) do
    (req.path =~ ACME_CHALLENGE_PATH_REGEXP ? @challenge_handler : app)
      .(req)
  rescue => e
    puts "Error while handling request: #{e.inspect} (headers: #{req.headers})"
    req.respond(nil, ':status' => Qeweney::Status::BAD_REQUEST)
  end
end

#get_certificate(name) ⇒ Object



130
131
132
133
134
135
136
137
# File 'lib/tipi/acme.rb', line 130

def get_certificate(name)
  entry = @store.get(name)
  return entry if entry

  provision_certificate(name).tap do |entry|
    @store.set(name, **entry)
  end
end

#get_context(name) ⇒ Object



89
90
91
# File 'lib/tipi/acme.rb', line 89

def get_context(name)
  @contexts[name] = setup_context(name)
end

#get_ctx(name) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/tipi/acme.rb', line 42

def get_ctx(name)
  state = { ctx: nil }

  if @valid_hosts
    return nil unless @valid_hosts.include?(name)
  end

  ready_ctx = @contexts[name]
  return ready_ctx if ready_ctx
  return @master_ctx if name =~ IP_REGEXP

  @requests << [name, state]
  wait_for_ctx(state)
  # Eventually we might want to return an error returned in
  # state[:error]. For the time being we handle errors by returning the
  # master context
  state[:ctx] || @master_ctx
rescue => e
  @master_ctx
end

#get_expired_stamp(certificate) ⇒ Object



124
125
126
127
128
# File 'lib/tipi/acme.rb', line 124

def get_expired_stamp(certificate)
  chain = parse_certificate(certificate)
  cert = chain.shift
  cert.not_after
end

#localhost_contextObject



139
140
141
142
# File 'lib/tipi/acme.rb', line 139

def localhost_context
  @localhost_authority ||= Localhost::Authority.fetch
  @localhost_authority.server_context
end

#parse_certificate(certificate) ⇒ Object



118
119
120
121
122
# File 'lib/tipi/acme.rb', line 118

def parse_certificate(certificate)
  certificate
    .scan(CERTIFICATE_REGEXP)
    .map { |p|  OpenSSL::X509::Certificate.new(p.first) }
end

#private_keyObject



144
145
146
# File 'lib/tipi/acme.rb', line 144

def private_key
  @private_key ||= OpenSSL::PKey::RSA.new(4096)
end

#provision_certificate(name) ⇒ Object

Raises:



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/tipi/acme.rb', line 166

def provision_certificate(name)
  order = acme_client.new_order(identifiers: [name])
  authorization = order.authorizations.first
  challenge = authorization.http

  @challenge_handler.add(challenge)
  challenge.request_validation
  while challenge.status == 'pending'
    sleep(0.25)
    challenge.reload
  end
  raise ACME::Error, "Invalid CSR" if challenge.status == 'invalid'

  private_key = OpenSSL::PKey::RSA.new(4096)
  csr = Acme::Client::CertificateRequest.new(
    private_key: private_key,
    subject: { common_name: name }
  )
  order.finalize(csr: csr)
  while order.status == 'processing'
    sleep(0.25)
    order.reload
  end
  certificate = begin
    order.certificate(force_chain: 'DST Root CA X3')
  rescue Acme::Client::Error::ForcedChainNotFound
    order.certificate
  end
  expired_stamp = get_expired_stamp(certificate)
  puts "Certificate for #{name} expires: #{expired_stamp.inspect}"

  {
    private_key: private_key,
    certificate: certificate,
    expired_stamp: expired_stamp
  }
end

#provision_context(name) ⇒ Object



99
100
101
102
103
104
105
106
107
108
# File 'lib/tipi/acme.rb', line 99

def provision_context(name)
  return localhost_context if name =~ LOCALHOST_REGEXP

  info = get_certificate(name)
  ctx = OpenSSL::SSL::SSLContext.new
  chain = parse_certificate(info[:certificate])
  cert = chain.shift
  ctx.add_certificate(cert, info[:private_key], chain)
  ctx
end

#runObject



78
79
80
81
82
83
84
85
# File 'lib/tipi/acme.rb', line 78

def run
  loop do
    name, state = @requests.shift
    state[:ctx] = get_context(name)
  rescue => e
    state[:error] = e if state
  end
end

#setup_acme_clientObject



154
155
156
157
158
159
160
161
162
163
164
# File 'lib/tipi/acme.rb', line 154

def setup_acme_client
  client = Acme::Client.new(
    private_key: private_key,
    directory: ACME_DIRECTORY
  )
   = client.(
    contact: 'mailto:[email protected]',
    terms_of_service_agreed: true
  )
  client
end

#setup_context(name) ⇒ Object



93
94
95
96
97
# File 'lib/tipi/acme.rb', line 93

def setup_context(name)
  ctx = provision_context(name)
  transfer_ctx_settings(ctx)
  ctx
end

#setup_sni_callbackObject



38
39
40
# File 'lib/tipi/acme.rb', line 38

def setup_sni_callback
  @master_ctx.servername_cb = proc { |_socket, name| get_ctx(name) }
end

#transfer_ctx_settings(ctx) ⇒ Object



110
111
112
113
114
# File 'lib/tipi/acme.rb', line 110

def transfer_ctx_settings(ctx)
  ctx.alpn_protocols = @master_ctx.alpn_protocols
  ctx.alpn_select_cb =  @master_ctx.alpn_select_cb
  ctx.ciphers = @master_ctx.ciphers
end

#wait_for_ctx(state) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/tipi/acme.rb', line 65

def wait_for_ctx(state)
  t0 = Time.now
  period = 0.00001
  while !state[:ctx] && !state[:error]
    orig_sleep period
    if period < 0.1
      period *= 2
    elsif Time.now - t0 > MAX_WAIT_FOR_CTX_DURATION
      raise "Timeout waiting for certificate provisioning"
    end
  end
end