-
Notifications
You must be signed in to change notification settings - Fork 7
/
cert_handler.py
435 lines (360 loc) · 17 KB
/
cert_handler.py
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
"""## Overview.
This document explains how to use the `CertHandler` class to
create and manage TLS certificates through the `tls_certificates` interface.
The goal of the CertHandler is to provide a wrapper to the `tls_certificates`
library functions to make the charm integration smoother.
## Library Usage
This library should be used to create a `CertHandler` object, as per the
following example:
```python
self.cert_handler = CertHandler(
charm=self,
key="my-app-cert-manager",
peer_relation_name="replicas",
cert_subject="unit_name", # Optional
)
```
You can then observe the library's custom event and make use of the key and cert:
```python
self.framework.observe(self.cert_handler.on.cert_changed, self._on_server_cert_changed)
container.push(keypath, self.cert_handler.key)
container.push(certpath, self.cert_handler.cert)
```
This library requires a peer relation to be declared in the requirer's metadata. Peer relation data
is used for "persistent storage" of the private key and certs.
"""
import ipaddress
import json
import socket
from itertools import filterfalse
from typing import List, Optional, Union, cast
try:
from charms.tls_certificates_interface.v2.tls_certificates import ( # type: ignore
AllCertificatesInvalidatedEvent,
CertificateAvailableEvent,
CertificateExpiringEvent,
CertificateInvalidatedEvent,
TLSCertificatesRequiresV2,
generate_csr,
generate_private_key,
)
except ImportError as e:
raise ImportError(
"failed to import charms.tls_certificates_interface.v2.tls_certificates; "
"Either the library itself is missing (please get it through charmcraft fetch-lib) "
"or one of its dependencies is unmet."
) from e
import logging
from ops.charm import CharmBase, RelationBrokenEvent
from ops.framework import EventBase, EventSource, Object, ObjectEvents
from ops.model import Relation
logger = logging.getLogger(__name__)
LIBID = "b5cd5cd580f3428fa5f59a8876dcbe6a"
LIBAPI = 0
LIBPATCH = 9
def is_ip_address(value: str) -> bool:
"""Return True if the input value is a valid IPv4 address; False otherwise."""
try:
ipaddress.IPv4Address(value)
return True
except ipaddress.AddressValueError:
return False
class CertChanged(EventBase):
"""Event raised when a cert is changed (becomes available or revoked)."""
class CertHandlerEvents(ObjectEvents):
"""Events for CertHandler."""
cert_changed = EventSource(CertChanged)
class CertHandler(Object):
"""A wrapper for the requirer side of the TLS Certificates charm library."""
on = CertHandlerEvents() # pyright: ignore
def __init__(
self,
charm: CharmBase,
*,
key: str,
peer_relation_name: str,
certificates_relation_name: str = "certificates",
cert_subject: Optional[str] = None,
extra_sans_dns: Optional[List[str]] = None, # TODO: in v1, rename arg to `sans`
):
"""CertHandler is used to wrap TLS Certificates management operations for charms.
CerHandler manages one single cert.
Args:
charm: The owning charm.
key: A manually-crafted, static, unique identifier used by ops to identify events.
It shouldn't change between one event to another.
peer_relation_name: Must match metadata.yaml.
certificates_relation_name: Must match metadata.yaml.
cert_subject: Custom subject. Name collisions are under the caller's responsibility.
extra_sans_dns: DNS names. If none are given, use FQDN.
"""
super().__init__(charm, key)
self.charm = charm
# We need to sanitize the unit name, otherwise route53 complains:
# "urn:ietf:params:acme:error:malformed" :: Domain name contains an invalid character
self.cert_subject = charm.unit.name.replace("/", "-") if not cert_subject else cert_subject
# Use fqdn only if no SANs were given, and drop empty/duplicate SANs
sans = list(set(filter(None, (extra_sans_dns or [socket.getfqdn()]))))
self.sans_ip = list(filter(is_ip_address, sans))
self.sans_dns = list(filterfalse(is_ip_address, sans))
self.peer_relation_name = peer_relation_name
self.certificates_relation_name = certificates_relation_name
self.certificates = TLSCertificatesRequiresV2(self.charm, self.certificates_relation_name)
self.framework.observe(
self.charm.on.config_changed,
self._on_config_changed,
)
self.framework.observe(
self.charm.on.certificates_relation_joined, # pyright: ignore
self._on_certificates_relation_joined,
)
self.framework.observe(
self.certificates.on.certificate_available, # pyright: ignore
self._on_certificate_available,
)
self.framework.observe(
self.certificates.on.certificate_expiring, # pyright: ignore
self._on_certificate_expiring,
)
self.framework.observe(
self.certificates.on.certificate_invalidated, # pyright: ignore
self._on_certificate_invalidated,
)
self.framework.observe(
self.certificates.on.all_certificates_invalidated, # pyright: ignore
self._on_all_certificates_invalidated,
)
self.framework.observe(
self.charm.on[self.certificates_relation_name].relation_broken, # pyright: ignore
self._on_certificates_relation_broken,
)
# Peer relation events
self.framework.observe(
self.charm.on[self.peer_relation_name].relation_created, self._on_peer_relation_created
)
@property
def enabled(self) -> bool:
"""Boolean indicating whether the charm has a tls_certificates relation."""
# We need to check for units as a temporary workaround because of https://bugs.launchpad.net/juju/+bug/2024583
# This could in theory not work correctly on scale down to 0 but it is necessary for the moment.
return (
len(self.charm.model.relations[self.certificates_relation_name]) > 0
and len(self.charm.model.get_relation(self.certificates_relation_name).units) > 0 # type: ignore
)
@property
def _peer_relation(self) -> Optional[Relation]:
"""Return the peer relation."""
return self.charm.model.get_relation(self.peer_relation_name, None)
def _on_peer_relation_created(self, _):
"""Generate the CSR if the certificates relation is ready."""
self._generate_privkey()
# check cert relation is ready
if not (self.charm.model.get_relation(self.certificates_relation_name)):
# peer relation event happened to fire before tls-certificates events.
# Abort, and let the "certificates joined" observer create the CSR.
logger.info("certhandler waiting on certificates relation")
return
logger.debug("certhandler has peer and certs relation: proceeding to generate csr")
self._generate_csr()
def _on_certificates_relation_joined(self, _) -> None:
"""Generate the CSR if the peer relation is ready."""
self._generate_privkey()
# check peer relation is there
if not self._peer_relation:
# tls-certificates relation event happened to fire before peer events.
# Abort, and let the "peer joined" relation create the CSR.
logger.info("certhandler waiting on peer relation")
return
logger.debug("certhandler has peer and certs relation: proceeding to generate csr")
self._generate_csr()
def _generate_privkey(self):
# Generate priv key unless done already
# TODO figure out how to go about key rotation.
if not self._private_key:
private_key = generate_private_key()
self._private_key = private_key.decode()
def _on_config_changed(self, _):
# FIXME on config changed, the web_external_url may or may not change. But because every
# call to `generate_csr` appends a uuid, CSRs cannot be easily compared to one another.
# so for now, will be overwriting the CSR (and cert) every config change. This is not
# great. We could avoid this problem if:
# - we extract the external_url from the existing cert and compare to current; or
# - we drop the web_external_url from the list of SANs.
# Generate a CSR only if the necessary relations are already in place.
if self._peer_relation and self.charm.model.get_relation(self.certificates_relation_name):
self._generate_csr(renew=True)
def _generate_csr(
self, overwrite: bool = False, renew: bool = False, clear_cert: bool = False
):
"""Request a CSR "creation" if renew is False, otherwise request a renewal.
Without overwrite=True, the CSR would be created only once, even if calling the method
multiple times. This is useful needed because the order of peer-created and
certificates-joined is not predictable.
This method intentionally does not emit any events, leave it for caller's responsibility.
"""
# At this point, assuming "peer joined" and "certificates joined" have already fired
# (caller must guard) so we must have a private_key entry in relation data at our disposal.
# Otherwise, traceback -> debug.
# In case we already have a csr, do not overwrite it by default.
if overwrite or renew or not self._csr:
private_key = self._private_key
if private_key is None:
# FIXME: raise this in a less nested scope by
# generating privkey and csr in the same method.
raise RuntimeError(
"private key unset. call _generate_privkey() before you call this method."
)
csr = generate_csr(
private_key=private_key.encode(),
subject=self.cert_subject,
sans_dns=self.sans_dns,
sans_ip=self.sans_ip,
)
if renew and self._csr:
self.certificates.request_certificate_renewal(
old_certificate_signing_request=self._csr.encode(),
new_certificate_signing_request=csr,
)
else:
logger.info(
"Creating CSR for %s with DNS %s and IPs %s",
self.cert_subject,
self.sans_dns,
self.sans_ip,
)
self.certificates.request_certificate_creation(certificate_signing_request=csr)
# Note: CSR is being replaced with a new one, so until we get the new cert, we'd have
# a mismatch between the CSR and the cert.
# For some reason the csr contains a trailing '\n'. TODO figure out why
self._csr = csr.decode().strip()
if clear_cert:
self._ca_cert = ""
self._server_cert = ""
self._chain = []
def _on_certificate_available(self, event: CertificateAvailableEvent) -> None:
"""Get the certificate from the event and store it in a peer relation.
Note: assuming "limit: 1" in metadata
"""
# We need to store the ca cert and server cert somewhere it would persist across upgrades.
# While we support Juju 2.9, the only option is peer data. When we drop 2.9, then secrets.
# I think juju guarantees that a peer-created always fires before any regular
# relation-changed. If that is not the case, we would need more guards and more paths.
# Process the cert only if it belongs to the unit that requested it (this unit)
event_csr = (
event.certificate_signing_request.strip()
if event.certificate_signing_request
else None
)
if event_csr == self._csr:
self._ca_cert = event.ca
self._server_cert = event.certificate
self._chain = event.chain
self.on.cert_changed.emit() # pyright: ignore
@property
def key(self):
"""Return the private key."""
return self._private_key
@property
def _private_key(self) -> Optional[str]:
if self._peer_relation:
return self._peer_relation.data[self.charm.unit].get("private_key", None)
return None
@_private_key.setter
def _private_key(self, value: str):
# Caller must guard. We want the setter to fail loudly. Failure must have a side effect.
rel = self._peer_relation
assert rel is not None # For type checker
rel.data[self.charm.unit].update({"private_key": value})
@property
def _csr(self) -> Optional[str]:
if self._peer_relation:
return self._peer_relation.data[self.charm.unit].get("csr", None)
return None
@_csr.setter
def _csr(self, value: str):
# Caller must guard. We want the setter to fail loudly. Failure must have a side effect.
rel = self._peer_relation
assert rel is not None # For type checker
rel.data[self.charm.unit].update({"csr": value})
@property
def _ca_cert(self) -> Optional[str]:
if self._peer_relation:
return self._peer_relation.data[self.charm.unit].get("ca", None)
return None
@_ca_cert.setter
def _ca_cert(self, value: str):
# Caller must guard. We want the setter to fail loudly. Failure must have a side effect.
rel = self._peer_relation
assert rel is not None # For type checker
rel.data[self.charm.unit].update({"ca": value})
@property
def cert(self):
"""Return the server cert."""
return self._server_cert
@property
def ca(self):
"""Return the CA cert."""
return self._ca_cert
@property
def _server_cert(self) -> Optional[str]:
if self._peer_relation:
return self._peer_relation.data[self.charm.unit].get("certificate", None)
return None
@_server_cert.setter
def _server_cert(self, value: str):
# Caller must guard. We want the setter to fail loudly. Failure must have a side effect.
rel = self._peer_relation
assert rel is not None # For type checker
rel.data[self.charm.unit].update({"certificate": value})
@property
def _chain(self) -> List[str]:
if self._peer_relation:
if chain := self._peer_relation.data[self.charm.unit].get("chain", []):
return json.loads(cast(str, chain))
return []
@_chain.setter
def _chain(self, value: List[str]):
# Caller must guard. We want the setter to fail loudly. Failure must have a side effect.
rel = self._peer_relation
assert rel is not None # For type checker
rel.data[self.charm.unit].update({"chain": json.dumps(value)})
@property
def chain(self) -> List[str]:
"""Return the ca chain."""
return self._chain
def _on_certificate_expiring(
self, event: Union[CertificateExpiringEvent, CertificateInvalidatedEvent]
) -> None:
"""Generate a new CSR and request certificate renewal."""
if event.certificate == self._server_cert:
self._generate_csr(renew=True)
def _certificate_revoked(self, event) -> None:
"""Remove the certificate from the peer relation and generate a new CSR."""
# Note: assuming "limit: 1" in metadata
if event.certificate == self._server_cert:
self._generate_csr(overwrite=True, clear_cert=True)
self.on.cert_changed.emit() # pyright: ignore
def _on_certificate_invalidated(self, event: CertificateInvalidatedEvent) -> None:
"""Deal with certificate revocation and expiration."""
if event.certificate != self._server_cert:
return
# if event.reason in ("revoked", "expired"):
# Currently, the reason does not matter to us because the action is the same.
self._generate_csr(overwrite=True, clear_cert=True)
self.on.cert_changed.emit() # pyright: ignore
def _on_all_certificates_invalidated(self, event: AllCertificatesInvalidatedEvent) -> None:
# Do what you want with this information, probably remove all certificates
# Note: assuming "limit: 1" in metadata
self._generate_csr(overwrite=True, clear_cert=True)
self.on.cert_changed.emit() # pyright: ignore
def _on_certificates_relation_broken(self, event: RelationBrokenEvent) -> None:
"""Clear the certificates data when removing the relation."""
if self._peer_relation:
private_key = self._private_key
# This is a workaround for https://bugs.launchpad.net/juju/+bug/2024583
self._peer_relation.data[self.charm.unit].clear()
if private_key:
self._peer_relation.data[self.charm.unit].update({"private_key": private_key})
self.on.cert_changed.emit() # pyright: ignore