Skip to content

Commit 3efd2a6

Browse files
committed
fix: retry a failed CA bundle update and compare the bundle byte for byte
The charm keeps a copy of the CA bundle and acts only when the bundle differs from it. The copy was written before update-ca-certificates ran and before the result was pushed to the workload, and only a failure of the first step was handled, by removing the copy. A push that failed left the copy equal to the bundle, so the next hook did nothing and the unit ended active without the CA; a removal that failed was never tried again. Both steps are now in one try, a Pebble error and an OSError (a request that times out, a missing binary) are caught too, and on failure the earlier copy is put back, so that the next reconciliation runs both steps again. The copy was also read as text, which turns CRLF into LF: a bundle with CRLF line endings never equalled its copy, and every hook wrote the copy and ran update-ca-certificates again. It is now read without newline translation.
1 parent 1824311 commit 3efd2a6

2 files changed

Lines changed: 95 additions & 5 deletions

File tree

‎src/charm.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -511,8 +511,9 @@ def _ensure_tls(self) -> bool:
511511
LOCAL_CHARM_CERTIFICATES_FILE.parent.mkdir(parents=True, exist_ok=True)
512512

513513
certificates = TLSCertificates.load(self.certificate_transfer_requirer).ca_bundle
514+
# No newline translation: a bundle with CRLF line endings has to equal its copy.
514515
existing = (
515-
LOCAL_CHARM_CERTIFICATES_FILE.read_text()
516+
LOCAL_CHARM_CERTIFICATES_FILE.read_bytes().decode()
516517
if LOCAL_CHARM_CERTIFICATES_FILE.exists()
517518
else ""
518519
)
@@ -537,12 +538,16 @@ def _ensure_tls(self) -> bool:
537538
],
538539
check=True,
539540
)
540-
except subprocess.CalledProcessError:
541+
self._tls_cert_changed = self._workload_service.update_ca_certs()
542+
# OSError: a request to Pebble that times out, or a missing binary.
543+
except (subprocess.CalledProcessError, ops.pebble.Error, OSError):
541544
logger.exception("Failed to update CA certificates")
542-
# Remove the cert file so the next reconciliation retries the subprocess.
543-
LOCAL_CHARM_CERTIFICATES_FILE.unlink(missing_ok=True)
545+
# Put the earlier copy back so the next reconciliation retries.
546+
if existing:
547+
LOCAL_CHARM_CERTIFICATES_FILE.write_text(existing)
548+
else:
549+
LOCAL_CHARM_CERTIFICATES_FILE.unlink(missing_ok=True)
544550
return False
545-
self._tls_cert_changed = self._workload_service.update_ca_certs()
546551
return True
547552

548553
def _on_holistic_handler(self, event: ops.EventBase) -> None:

‎tests/unit/test_charm.py‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# See LICENSE file for licensing details.
33

44
import subprocess
5+
from pathlib import Path
56
from typing import Any
67
from unittest.mock import MagicMock, patch
78

@@ -828,6 +829,90 @@ def test_ensure_tls_subprocess_failure_blocks_plan(
828829
assert "tenant-service" not in container_out.layers
829830

830831

832+
class TestCABundle:
833+
@pytest.fixture
834+
def charm_copy(self, mocker: MockerFixture, tmp_path: Path) -> Path:
835+
"""The charm's copy of the bundle it last applied."""
836+
return mocker.patch("charm.LOCAL_CHARM_CERTIFICATES_FILE", tmp_path / "ca.crt")
837+
838+
@pytest.fixture
839+
def state(
840+
self,
841+
database_relation: testing.Relation,
842+
openfga_relation: testing.Relation,
843+
openfga_secret: testing.Secret,
844+
peer_relation: testing.PeerRelation,
845+
kratos_info_relation: testing.Relation,
846+
api_token_secret: testing.Secret,
847+
) -> testing.State:
848+
return create_state(
849+
relations=[database_relation, openfga_relation, peer_relation, kratos_info_relation],
850+
secrets=[api_token_secret, openfga_secret],
851+
)
852+
853+
@pytest.mark.parametrize(
854+
"error",
855+
[
856+
pytest.param(ops.pebble.ConnectionError("pebble is down"), id="pebble is down"),
857+
pytest.param(TimeoutError("timed out"), id="pebble does not answer in time"),
858+
],
859+
)
860+
def test_failed_push_is_retried(
861+
self,
862+
context: testing.Context,
863+
state: testing.State,
864+
charm_copy: Path,
865+
mocker: MockerFixture,
866+
error: Exception,
867+
) -> None:
868+
mocker.patch("charm.TLSCertificates").load.return_value.ca_bundle = "new-ca-cert"
869+
push = mocker.patch(
870+
"charm.WorkloadService.update_ca_certs",
871+
side_effect=[error, True],
872+
)
873+
874+
context.run(context.on.config_changed(), state)
875+
context.run(context.on.config_changed(), state)
876+
877+
assert push.call_count == 2
878+
879+
def test_failed_removal_is_retried(
880+
self,
881+
context: testing.Context,
882+
state: testing.State,
883+
charm_copy: Path,
884+
mocked_subprocess_run: MagicMock,
885+
mocker: MockerFixture,
886+
) -> None:
887+
charm_copy.write_text("old-ca-cert")
888+
mocker.patch("charm.TLSCertificates").load.return_value.ca_bundle = ""
889+
mocked_subprocess_run.side_effect = subprocess.CalledProcessError(
890+
1, "update-ca-certificates"
891+
)
892+
893+
context.run(context.on.config_changed(), state)
894+
895+
assert charm_copy.read_text() == "old-ca-cert"
896+
897+
def test_applied_bundle_with_crlf_line_endings_is_not_applied_again(
898+
self,
899+
context: testing.Context,
900+
state: testing.State,
901+
charm_copy: Path,
902+
mocked_subprocess_run: MagicMock,
903+
mocker: MockerFixture,
904+
) -> None:
905+
bundle = "ca-cert-line-1\r\nca-cert-line-2"
906+
charm_copy.write_text(bundle)
907+
mocker.patch("charm.TLSCertificates").load.return_value.ca_bundle = bundle
908+
push = mocker.patch("charm.WorkloadService.update_ca_certs")
909+
910+
context.run(context.on.config_changed(), state)
911+
912+
mocked_subprocess_run.assert_not_called()
913+
push.assert_not_called()
914+
915+
831916
class TestSecretMissing:
832917
def test_api_token_missing_raises_value_error(self) -> None:
833918
"""Test that accessing api_token without secret raises ValueError."""

0 commit comments

Comments
 (0)