Skip to content

Commit ec29a9e

Browse files
committed
make the chain order fix backwards compatible
1 parent 3657fcb commit ec29a9e

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

lib/charms/observability_libs/v1/cert_handler.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@
6868

6969
LIBID = "b5cd5cd580f3428fa5f59a8876dcbe6a"
7070
LIBAPI = 1
71-
LIBPATCH = 16
71+
LIBPATCH = 17
7272

7373
VAULT_SECRET_LABEL = "cert-handler-private-vault"
7474

@@ -82,6 +82,37 @@ def is_ip_address(value: str) -> bool:
8282
return False
8383

8484

85+
def split_chain(chain: str) -> List[str]:
86+
"""Split a chain string in to individual cert strings.
87+
88+
Args:
89+
chain: The chain to split.
90+
91+
Returns:
92+
List[str]: A list of cert strings.
93+
"""
94+
certs = []
95+
current_cert = []
96+
lines = chain.strip().splitlines()
97+
98+
in_cert = False
99+
for line in lines:
100+
line = line.strip()
101+
if line == "-----BEGIN CERTIFICATE-----":
102+
# The first line of a new cert.
103+
in_cert = True
104+
current_cert = [line]
105+
elif line == "-----END CERTIFICATE-----":
106+
# The last line of the cert.
107+
current_cert.append(line)
108+
certs.append("\n".join(current_cert))
109+
in_cert = False
110+
elif in_cert:
111+
# Somewhere in the middle.
112+
current_cert.append(line)
113+
return certs
114+
115+
85116
class CertChanged(EventBase):
86117
"""Event raised when a cert is changed (becomes available or revoked)."""
87118

@@ -613,6 +644,15 @@ def chain(self) -> Optional[str]:
613644
if cert.certificate not in chain:
614645
# add server cert to chain
615646
chain = cert.certificate + "\n\n" + chain
647+
648+
# Needed for backwards compatibility with self-signed-certificates.
649+
# See https://github.com/canonical/traefik-k8s-operator/issues/491.
650+
# This should be removed when revision 308 of self-signed-certificates is sufficiently old.
651+
certs = split_chain(chain)
652+
if cert.certificate != certs[0]:
653+
certs.reverse()
654+
chain = "\n\n".join(certs)
655+
616656
return chain
617657

618658
def _on_certificate_expiring(

0 commit comments

Comments
 (0)