charmlibs-interfaces-certificate-transfer 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,134 @@
1
+ # Copyright 2025 Canonical Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Transfer x.509 certificates using the ``certificate-transfer`` interface (V1).
16
+
17
+ This is a port of ``certificate_transfer_interface.certificate_transfer`` v1.15.
18
+
19
+ This library contains the Requires and Provides classes for handling the
20
+ certificate-transfer interface. It supports both v0 and v1 of the interface.
21
+
22
+ For requirers, they will set version 1 in their application databag as a hint to
23
+ the provider. They will read the databag from the provider first as v1, and fallback
24
+ to v0 if the format does not match.
25
+
26
+ For providers, they will check the version in the requirer's application databag,
27
+ and send v1 if that version is set to 1, otherwise it will default to 0 for backwards
28
+ compatibility.
29
+
30
+ =================
31
+ Getting Started
32
+ =================
33
+
34
+ From a charm directory, fetch the library using ``charmcraft``::
35
+
36
+ charmcraft fetch-lib charms.certificate_transfer_interface.v1.certificate_transfer
37
+
38
+ =================
39
+ Provider charm
40
+ =================
41
+
42
+ The provider charm is the charm providing public certificates to another charm that requires them.
43
+
44
+ Example::
45
+
46
+ from ops.charm import CharmBase, RelationJoinedEvent
47
+ from ops.main import main
48
+
49
+ from lib.charms.certificate_transfer_interface.v1.certificate_transfer import (
50
+ CertificateTransferProvides,
51
+ )
52
+
53
+ class DummyCertificateTransferProviderCharm(CharmBase):
54
+ def __init__(self, *args):
55
+ super().__init__(*args)
56
+ self.ct = CertificateTransferProvides(self, "certificates")
57
+ self.framework.observe(
58
+ self.on.certificates_relation_joined, self._on_certificates_relation_joined
59
+ )
60
+
61
+ def _on_certificates_relation_joined(self, event: RelationJoinedEvent):
62
+ certificate = "my certificate"
63
+ self.ct.add_certificates(certificate)
64
+
65
+
66
+ if __name__ == "__main__":
67
+ main(DummyCertificateTransferProviderCharm)
68
+
69
+
70
+ =================
71
+ Requirer charm
72
+ =================
73
+ The requirer charm is the charm requiring certificates from another charm that provides them.
74
+
75
+ Example::
76
+
77
+ import logging
78
+
79
+ from ops.charm import CharmBase
80
+ from ops.main import main
81
+
82
+ from lib.charms.certificate_transfer_interface.v1.certificate_transfer import (
83
+ CertificatesAvailableEvent,
84
+ CertificatesRemovedEvent,
85
+ CertificateTransferRequires,
86
+ )
87
+
88
+
89
+ class DummyCertificateTransferRequirerCharm(CharmBase):
90
+ def __init__(self, *args):
91
+ super().__init__(*args)
92
+ self.ct = CertificateTransferRequires(self, "certificates")
93
+ self.framework.observe(
94
+ self.ct.on.certificate_set_updated, self._on_certificates_available
95
+ )
96
+ self.framework.observe(
97
+ self.ct.on.certificates_removed, self._on_certificates_removed
98
+ )
99
+
100
+ def _on_certificates_available(self, event: CertificatesAvailableEvent):
101
+ logging.info(event.certificates)
102
+ logging.info(event.relation_id)
103
+
104
+ def _on_certificates_removed(self, event: CertificatesRemovedEvent):
105
+ logging.info(event.relation_id)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main(DummyCertificateTransferRequirerCharm)
110
+
111
+ You can integrate both charms by running::
112
+
113
+ juju integrate <certificate_transfer provider charm> <certificate_transfer requirer charm>
114
+
115
+ """
116
+
117
+ from ._certificate_transfer import (
118
+ CertificatesAvailableEvent,
119
+ CertificatesRemovedEvent,
120
+ CertificateTransferProvides,
121
+ CertificateTransferRequires,
122
+ DataValidationError,
123
+ TLSCertificatesError,
124
+ )
125
+ from ._version import __version__ as __version__
126
+
127
+ __all__ = [
128
+ "CertificateTransferProvides",
129
+ "CertificateTransferRequires",
130
+ "CertificatesAvailableEvent",
131
+ "CertificatesRemovedEvent",
132
+ "DataValidationError",
133
+ "TLSCertificatesError",
134
+ ]
@@ -0,0 +1,608 @@
1
+ # Copyright 2025 Canonical Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Source code of ``certificate_transfer_interface.certificate_transfer`` v1.15."""
16
+
17
+ import json
18
+ import logging
19
+ from collections.abc import MutableMapping
20
+ from typing import Any
21
+
22
+ import pydantic
23
+ from ops import (
24
+ CharmEvents,
25
+ EventBase,
26
+ EventSource,
27
+ Handle,
28
+ Relation,
29
+ RelationBrokenEvent,
30
+ RelationChangedEvent,
31
+ RelationCreatedEvent,
32
+ )
33
+ from ops.charm import CharmBase
34
+ from ops.framework import Object
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ IS_PYDANTIC_V1 = int(pydantic.version.VERSION.split(".")[0]) < 2
39
+
40
+
41
+ class TLSCertificatesError(Exception):
42
+ """Base class for custom errors raised by this library."""
43
+
44
+
45
+ class DataValidationError(TLSCertificatesError):
46
+ """Raised when data validation fails."""
47
+
48
+
49
+ class DatabagModel(pydantic.BaseModel):
50
+ """Base databag model.
51
+
52
+ Supports both pydantic v1 and v2.
53
+ """
54
+
55
+ if IS_PYDANTIC_V1:
56
+
57
+ class Config:
58
+ """Pydantic config."""
59
+
60
+ # ignore any extra fields in the databag
61
+ extra = "ignore"
62
+ """Ignore any extra fields in the databag."""
63
+ allow_population_by_field_name = True
64
+ """Allow instantiating this class by field name (instead of forcing alias)."""
65
+
66
+ _NEST_UNDER = None
67
+
68
+ model_config = pydantic.ConfigDict(
69
+ # tolerate additional keys in databag
70
+ extra="ignore",
71
+ # Allow instantiating this class by field name (instead of forcing alias).
72
+ populate_by_name=True,
73
+ # Custom config key: whether to nest the whole datastructure (as json)
74
+ # under a field or spread it out at the toplevel.
75
+ _NEST_UNDER=None,
76
+ ) # type: ignore
77
+ """Pydantic config."""
78
+
79
+ @classmethod
80
+ def load(cls, databag: MutableMapping[str, Any]):
81
+ """Load this model from a Juju databag."""
82
+ if IS_PYDANTIC_V1:
83
+ return cls._load_v1(databag)
84
+ nest_under = cls.model_config.get("_NEST_UNDER")
85
+ if nest_under:
86
+ return cls.model_validate(json.loads(databag[nest_under]))
87
+
88
+ try:
89
+ data = {
90
+ k: json.loads(v)
91
+ for k, v in databag.items()
92
+ # Don't attempt to parse model-external values
93
+ if k in {(f.alias or n) for n, f in cls.model_fields.items()}
94
+ }
95
+ except json.JSONDecodeError as e:
96
+ msg = f"invalid databag contents: expecting json. {databag}"
97
+ logger.error(msg)
98
+ raise DataValidationError(msg) from e
99
+
100
+ try:
101
+ return cls.model_validate_json(json.dumps(data))
102
+ except pydantic.ValidationError as e:
103
+ msg = f"failed to validate databag: {databag}"
104
+ logger.debug(msg, exc_info=True)
105
+ raise DataValidationError(msg) from e
106
+
107
+ @classmethod
108
+ def _load_v1(cls, databag: MutableMapping[str, Any]):
109
+ """Load implementation for pydantic v1."""
110
+ if cls._NEST_UNDER:
111
+ return cls.parse_obj(json.loads(databag[cls._NEST_UNDER])) # type: ignore
112
+
113
+ try:
114
+ data = {
115
+ k: json.loads(v)
116
+ for k, v in databag.items()
117
+ # Don't attempt to parse model-external values
118
+ if k in {f.alias for f in cls.__fields__.values()} # type: ignore
119
+ }
120
+ except json.JSONDecodeError as e:
121
+ msg = f"invalid databag contents: expecting json. {databag}"
122
+ logger.error(msg)
123
+ raise DataValidationError(msg) from e
124
+
125
+ try:
126
+ return cls.parse_raw(json.dumps(data)) # type: ignore
127
+ except pydantic.ValidationError as e:
128
+ msg = f"failed to validate databag: {databag}"
129
+ logger.debug(msg, exc_info=True)
130
+ raise DataValidationError(msg) from e
131
+
132
+ def dump(self, databag: MutableMapping[str, Any] | None = None, clear: bool = True):
133
+ """Write the contents of this model to Juju databag.
134
+
135
+ Args:
136
+ databag: The databag to write to.
137
+ clear: Whether to clear the databag before writing.
138
+
139
+ Returns:
140
+ MutableMapping: The databag.
141
+ """
142
+ if IS_PYDANTIC_V1:
143
+ return self._dump_v1(databag, clear)
144
+ if clear and databag:
145
+ databag.clear()
146
+
147
+ if databag is None:
148
+ databag = {}
149
+ nest_under = self.model_config.get("_NEST_UNDER")
150
+ if nest_under:
151
+ databag[nest_under] = self.model_dump_json(
152
+ by_alias=True,
153
+ # skip keys whose values are default
154
+ exclude_defaults=True,
155
+ )
156
+ return databag
157
+
158
+ dct = self.model_dump(mode="json", by_alias=True, exclude_defaults=False)
159
+ databag.update({k: json.dumps(v) for k, v in dct.items()})
160
+ return databag
161
+
162
+ def _dump_v1(self, databag: MutableMapping[str, Any] | None = None, clear: bool = True):
163
+ """Dump implementation for pydantic v1."""
164
+ if clear and databag:
165
+ databag.clear()
166
+
167
+ if databag is None:
168
+ databag = {}
169
+
170
+ if self._NEST_UNDER:
171
+ databag[self._NEST_UNDER] = self.json(by_alias=True, exclude_defaults=False) # type: ignore
172
+ return databag
173
+
174
+ dct = json.loads(self.json(by_alias=True, exclude_defaults=False)) # type: ignore
175
+ databag.update({k: json.dumps(v) for k, v in dct.items()})
176
+
177
+ return databag
178
+
179
+
180
+ class ProviderApplicationData(DatabagModel):
181
+ """Provider App databag model."""
182
+
183
+ if int(pydantic.version.VERSION.split(".")[0]) < 2:
184
+ certificates: set[str] = pydantic.Field(
185
+ description="The set of certificates that will be transferred to a requirer",
186
+ default_factory=set,
187
+ )
188
+ else:
189
+ certificates: set[str] = pydantic.Field(
190
+ description="The set of certificates that will be transferred to a requirer",
191
+ default=set(),
192
+ )
193
+ version: int = pydantic.Field(
194
+ description="Version of the interface used in this databag",
195
+ default=1,
196
+ )
197
+
198
+
199
+ class ProviderUnitDataV0(DatabagModel):
200
+ """Provider Unit databag v0 model."""
201
+
202
+ ca: str
203
+ certificate: str
204
+ chain: list[str] | None = None
205
+ version: int = pydantic.Field(
206
+ description="Version of the interface used in this databag",
207
+ default=0,
208
+ )
209
+
210
+
211
+ class RequirerApplicationData(DatabagModel):
212
+ """Requirer App databag model."""
213
+
214
+ version: int = pydantic.Field(
215
+ description="Version of the interface supported by this requirer",
216
+ default=1,
217
+ )
218
+
219
+
220
+ class CertificateTransferProvides(Object):
221
+ """Certificate Transfer provider class to be instantiated by charms sending certificates."""
222
+
223
+ def __init__(self, charm: CharmBase, relationship_name: str):
224
+ super().__init__(charm, relationship_name + "_v1")
225
+ self.charm = charm
226
+ self.relationship_name = relationship_name
227
+
228
+ def add_certificates(self, certificates: set[str], relation_id: int | None = None) -> None:
229
+ """Add certificates from a set to relation data.
230
+
231
+ Adds certificate to all relations if relation_id is not provided.
232
+
233
+ Args:
234
+ certificates (Set[str]): A set of certificate strings in PEM format
235
+ relation_id (int): Juju relation ID
236
+
237
+ Returns:
238
+ None
239
+ """
240
+ if not self.charm.unit.is_leader():
241
+ logger.warning("Only the leader unit can add certificates to this relation")
242
+ return
243
+ relations = self._get_active_relations(relation_id)
244
+ if not relations:
245
+ if relation_id is not None:
246
+ logger.debug(
247
+ "At least 1 matching relation ID not found with the relation name '%s'",
248
+ self.relationship_name,
249
+ )
250
+ else:
251
+ logger.debug(
252
+ "No active relations found with the relation name '%s'",
253
+ self.relationship_name,
254
+ )
255
+ return
256
+
257
+ for relation in relations:
258
+ existing_data = self._get_relation_data(relation)
259
+ existing_data.update(certificates)
260
+ self._set_relation_data(relation, existing_data)
261
+
262
+ def remove_all_certificates(self, relation_id: int | None = None) -> None:
263
+ """Remove all certificates from relation data.
264
+
265
+ Removes all certificates from all relations if relation_id not given
266
+
267
+ Args:
268
+ relation_id (int): Relation ID
269
+
270
+ Returns:
271
+ None
272
+ """
273
+ if not self.charm.unit.is_leader():
274
+ logger.warning("Only the leader unit can add certificates to this relation")
275
+ return
276
+ relations = self._get_active_relations(relation_id)
277
+ if not relations:
278
+ if relation_id is not None:
279
+ logger.debug(
280
+ "At least 1 matching relation ID not found with the relation name '%s'",
281
+ self.relationship_name,
282
+ )
283
+ else:
284
+ logger.debug(
285
+ "No active relations found with the relation name '%s'",
286
+ self.relationship_name,
287
+ )
288
+ return
289
+
290
+ for relation in relations:
291
+ self._set_relation_data(relation, set())
292
+
293
+ def remove_certificate(
294
+ self,
295
+ certificate: str,
296
+ relation_id: int | None = None,
297
+ ) -> None:
298
+ """Remove a given certificate from relation data.
299
+
300
+ Removes certificate from all relations if relation_id not given
301
+
302
+ Args:
303
+ certificate (str): Certificate in PEM format that's in the list
304
+ relation_id (int): Relation ID
305
+
306
+ Returns:
307
+ None
308
+ """
309
+ if not self.charm.unit.is_leader():
310
+ logger.warning("Only the leader unit can add certificates to this relation")
311
+ return
312
+ relations = self._get_active_relations(relation_id)
313
+ if not relations:
314
+ if relation_id is not None:
315
+ logger.debug(
316
+ "At least 1 matching relation ID not found with the relation name '%s'",
317
+ self.relationship_name,
318
+ )
319
+ else:
320
+ logger.debug(
321
+ "No active relations found with the relation name '%s'",
322
+ self.relationship_name,
323
+ )
324
+ return
325
+
326
+ for relation in relations:
327
+ existing_data = self._get_relation_data(relation)
328
+ existing_data.discard(certificate)
329
+ self._set_relation_data(relation, existing_data)
330
+
331
+ def _get_active_relations(self, relation_id: int | None = None) -> list[Relation]:
332
+ """Get the relation if relation is active and id is given, or all active relations."""
333
+ if relation_id is not None:
334
+ relation = self.model.get_relation(
335
+ relation_name=self.relationship_name, relation_id=relation_id
336
+ )
337
+ if relation and relation.active:
338
+ return [relation]
339
+ return []
340
+
341
+ return [
342
+ relation
343
+ for relation in self.model.relations[self.relationship_name]
344
+ if relation.active
345
+ ]
346
+
347
+ def _set_relation_data(self, relation: Relation, data: set[str]) -> None:
348
+ """Set the given relation data."""
349
+ if relation.data.get(relation.app, {}).get("version", "0") == "1":
350
+ databag = relation.data[self.model.app]
351
+ ProviderApplicationData(certificates=data).dump(databag, True)
352
+ else:
353
+ if "version" in relation.data.get(relation.app, {}):
354
+ logger.warning(
355
+ (
356
+ "Requirer in relation %d is using version %s of the interface,",
357
+ "defaulting to version 0.",
358
+ "This is deprecated, please consider upgrading the requirer",
359
+ "to version 1 of the library.",
360
+ ),
361
+ relation.id,
362
+ relation.data[relation.app]["version"],
363
+ )
364
+ else:
365
+ logger.warning(
366
+ (
367
+ "Requirer in relation %d did not provide version field,",
368
+ "defaulting to version 0.",
369
+ "This is deprecated, please consider upgrading the requirer",
370
+ "to version 1 of the library.",
371
+ ),
372
+ relation.id,
373
+ )
374
+
375
+ databag = relation.data[self.model.unit]
376
+ if data:
377
+ certificates = list(data)
378
+ ProviderUnitDataV0(
379
+ ca=certificates[0], certificate=certificates[0], chain=certificates
380
+ ).dump(databag, True)
381
+
382
+ def _get_relation_data(self, relation: Relation) -> set[str]:
383
+ """Get the given relation data."""
384
+ try:
385
+ if relation.data.get(relation.app, {}).get("version", "0") == "1":
386
+ databag = relation.data[self.model.app]
387
+ return ProviderApplicationData().load(databag).certificates
388
+ else:
389
+ databag = relation.data[self.model.unit]
390
+ certs = ProviderUnitDataV0.load(databag).chain
391
+ if certs is None:
392
+ return set()
393
+ return set(certs)
394
+ except DataValidationError as e:
395
+ logger.error(
396
+ (
397
+ "Error parsing relation databag: %s. ",
398
+ "Make sure not to interact with the databags "
399
+ "except using the public methods in the provider library "
400
+ "and use version V1.",
401
+ ),
402
+ e.args,
403
+ )
404
+ return set()
405
+
406
+
407
+ class CertificatesAvailableEvent(EventBase):
408
+ """Charm Event triggered when the set of provided certificates is updated."""
409
+
410
+ def __init__(
411
+ self,
412
+ handle: Handle,
413
+ certificates: set[str],
414
+ relation_id: int,
415
+ ):
416
+ super().__init__(handle)
417
+ self.certificates = certificates
418
+ self.relation_id = relation_id
419
+
420
+ def snapshot(self) -> dict[str, set[str] | int]:
421
+ """Return snapshot."""
422
+ return {
423
+ "certificates": self.certificates,
424
+ "relation_id": self.relation_id,
425
+ }
426
+
427
+ def restore(self, snapshot: dict[str, set[str] | int]):
428
+ """Restores snapshot."""
429
+ self.certificates = snapshot["certificates"]
430
+ self.relation_id = snapshot["relation_id"]
431
+
432
+
433
+ class CertificatesRemovedEvent(EventBase):
434
+ """Charm Event triggered when the set of provided certificates is removed."""
435
+
436
+ def __init__(self, handle: Handle, relation_id: int):
437
+ super().__init__(handle)
438
+ self.relation_id = relation_id
439
+
440
+ def snapshot(self) -> dict[str, int]:
441
+ """Return snapshot."""
442
+ return {"relation_id": self.relation_id}
443
+
444
+ def restore(self, snapshot: dict[str, int]):
445
+ """Restores snapshot."""
446
+ self.relation_id = snapshot["relation_id"]
447
+
448
+
449
+ class CertificateTransferRequirerCharmEvents(CharmEvents):
450
+ """List of events that the Certificate Transfer requirer charm can leverage."""
451
+
452
+ certificate_set_updated = EventSource(CertificatesAvailableEvent)
453
+ certificates_removed = EventSource(CertificatesRemovedEvent)
454
+
455
+
456
+ class CertificateTransferRequires(Object):
457
+ """Certificate transfer requirer class to be instantiated by charms expecting certificates."""
458
+
459
+ on = CertificateTransferRequirerCharmEvents() # type: ignore
460
+
461
+ def __init__(
462
+ self,
463
+ charm: CharmBase,
464
+ relationship_name: str,
465
+ ):
466
+ """Observe events related to the relation.
467
+
468
+ Args:
469
+ charm: Charm object
470
+ relationship_name: Juju relation name
471
+ """
472
+ super().__init__(charm, relationship_name + "_v1")
473
+ self.relationship_name = relationship_name
474
+ self.charm = charm
475
+ self.framework.observe(
476
+ charm.on[relationship_name].relation_changed, self._on_relation_changed
477
+ )
478
+ self.framework.observe(
479
+ charm.on[relationship_name].relation_broken, self._on_relation_broken
480
+ )
481
+ self.framework.observe(
482
+ charm.on[relationship_name].relation_created, self._on_relation_created
483
+ )
484
+
485
+ def _on_relation_changed(self, event: RelationChangedEvent) -> None:
486
+ """Emit certificate set updated event.
487
+
488
+ Args:
489
+ event: Juju event
490
+
491
+ Returns:
492
+ None
493
+ """
494
+ remote_unit_relation_data = self.get_all_certificates(event.relation.id)
495
+ self.on.certificate_set_updated.emit(
496
+ certificates=remote_unit_relation_data,
497
+ relation_id=event.relation.id,
498
+ )
499
+
500
+ def _on_relation_broken(self, event: RelationBrokenEvent) -> None:
501
+ """Handle relation broken event.
502
+
503
+ Args:
504
+ event: Juju event
505
+
506
+ Returns:
507
+ None
508
+ """
509
+ self.on.certificates_removed.emit(relation_id=event.relation.id)
510
+
511
+ def _on_relation_created(self, event: RelationCreatedEvent) -> None:
512
+ """Handle relation created event.
513
+
514
+ Args:
515
+ event: Juju event
516
+
517
+ Returns:
518
+ None
519
+ """
520
+ if not self.model.unit.is_leader():
521
+ logger.debug("Only leader unit sets the version number in the app databag")
522
+ return
523
+ databag = event.relation.data[self.model.app]
524
+ RequirerApplicationData().dump(databag, False)
525
+
526
+ def get_all_certificates(self, relation_id: int | None = None) -> set[str]:
527
+ """Get transferred certificates.
528
+
529
+ If no relation id is given, certificates from all relations will be
530
+ provided in a concatenated list.
531
+
532
+ Args:
533
+ relation_id: The id of the relation to get the certificates from.
534
+ """
535
+ relations = self._get_active_relations(relation_id)
536
+ result: set[str] = set()
537
+ for relation in relations:
538
+ data = self._get_relation_data(relation)
539
+ result = result.union(data)
540
+ return result
541
+
542
+ def get_all_certificates_by_relation(
543
+ self, relation_id: int | None = None
544
+ ) -> dict[int, list[str]]:
545
+ """Get a deterministic list of certificates grouped by relation.
546
+
547
+ - Grouped by relation_id.
548
+ - The list order is sorted lexicographically by PEM content.
549
+
550
+ Args:
551
+ relation_id: If provided, only certificates for this relation are returned.
552
+
553
+ Returns:
554
+ Dict where keys are relation IDs and values are ordered lists of PEMs.
555
+ """
556
+ relations = self._get_active_relations(relation_id)
557
+ result: dict[int, list[str]] = {}
558
+ for relation in relations:
559
+ certificates = sorted(self._get_relation_data(relation))
560
+ result[relation.id] = certificates
561
+ return result
562
+
563
+ def is_ready(self, relation: Relation) -> bool:
564
+ """Check if the relation is ready by checking that it has valid relation data."""
565
+ databag = relation.data[relation.app]
566
+ try:
567
+ ProviderApplicationData().load(databag)
568
+ return True
569
+ except DataValidationError:
570
+ return False
571
+
572
+ def _get_relation_data(self, relation: Relation) -> set[str]:
573
+ """Get the given relation data."""
574
+ try:
575
+ databag = relation.data[relation.app]
576
+ certificates = ProviderApplicationData().load(databag).certificates
577
+ if not certificates and relation.units:
578
+ databag = relation.data.get(relation.units.pop(), {})
579
+ certs = ProviderUnitDataV0.load(databag).chain
580
+ if certs is None:
581
+ return set()
582
+ return set(certs)
583
+ return certificates
584
+ except DataValidationError as e:
585
+ logger.error(
586
+ (
587
+ "Error parsing relation databag: %s. ",
588
+ "Make sure not to interact with the databags "
589
+ "except using the public methods in the provider library "
590
+ "and use version V1.",
591
+ ),
592
+ e.args,
593
+ )
594
+ return set()
595
+
596
+ def _get_active_relations(self, relation_id: int | None = None) -> list[Relation]:
597
+ """Get the active relation if relation_id is given, all active relations otherwise."""
598
+ if relation_id is not None and (
599
+ relation := self.model.get_relation(
600
+ relation_name=self.relationship_name, relation_id=relation_id
601
+ )
602
+ ):
603
+ return [relation]
604
+ return [
605
+ relation
606
+ for relation in self.model.relations[self.relationship_name]
607
+ if relation.active
608
+ ]
@@ -0,0 +1,15 @@
1
+ # Copyright 2025 Canonical Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = '1.0.0'
File without changes
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: charmlibs-interfaces-certificate_transfer
3
+ Version: 1.0.0
4
+ Summary: The charmlibs.interfaces.certificate_transfer package.
5
+ Project-URL: Repository, https://github.com/canonical/charmlibs
6
+ Project-URL: Issues, https://github.com/canonical/charmlibs/issues
7
+ Author: The TLS team at Canonical
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: ops
15
+ Requires-Dist: pydantic
16
+ Description-Content-Type: text/markdown
17
+
18
+ # charmlibs.interfaces.certificate_transfer
19
+
20
+ The `certificate_transfer` interface library.
21
+
22
+ To install, add `charmlibs-interfaces-certificate_transfer` to your Python dependencies. Then in your Python code, import as:
23
+
24
+ ```py
25
+ from charmlibs.interfaces import certificate_transfer
26
+ ```
27
+
28
+ See the [reference documentation](https://documentation.ubuntu.com/charmlibs/reference/charmlibs/interfaces/certificate_transfer).
@@ -0,0 +1,7 @@
1
+ charmlibs/interfaces/certificate_transfer/__init__.py,sha256=YqsXUvcCR3CGmfTsD40c7VousuYV-nyEk6jQ2lBocxA,4376
2
+ charmlibs/interfaces/certificate_transfer/_certificate_transfer.py,sha256=DHXvo5MIPhCuGGyZWqBxr2_E7qsl0JI6ATeKioBrX3A,21276
3
+ charmlibs/interfaces/certificate_transfer/_version.py,sha256=SOabh2HM3GM1fjRvHHGC-IV789Y2DPLYqgl_cRoScto,597
4
+ charmlibs/interfaces/certificate_transfer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ charmlibs_interfaces_certificate_transfer-1.0.0.dist-info/METADATA,sha256=S2Yx_BVIAB5cdobCJFNBRPgzirT-jHGyZ9oqpMXdlSw,1095
6
+ charmlibs_interfaces_certificate_transfer-1.0.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
7
+ charmlibs_interfaces_certificate_transfer-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any