Skip to content

Commit

Permalink
Updates safe to switch from secret ID to label
Browse files Browse the repository at this point in the history
  • Loading branch information
juditnovak committed Nov 20, 2023
1 parent 3a814a3 commit db1ff02
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,20 @@ def _translate_field_to_secret_key(self, key: str) -> str:
new_key = key.replace("_", "-")
return new_key.strip("-")

def _safe_get_secret(self, scope: Scopes, label: str) -> SecretCache:
"""Safety measure, for upgrades between versions based on secret URI usage to others with labels usage.
If the secret can't be retrieved by label, we search for the uri -- and if found, we "stick" the
label on the secret for further usage.
"""
secret_uri = self._peer_data(scope).get(SECRET_INTERNAL_LABEL, None)
secret = self.secrets.get(label, secret_uri)

# Since now we switched to labels, the databag reference can be removed
if secret_uri and secret and scope == APP_SCOPE and self.unit.is_leader():
self._peer_data(scope).pop(SECRET_INTERNAL_LABEL, None)
return secret

def get_secret(self, scope: Scopes, key: str) -> Optional[str]:
"""Get secret from the secret storage."""
if scope not in get_args(Scopes):
Expand All @@ -220,15 +234,15 @@ def get_secret(self, scope: Scopes, key: str) -> Optional[str]:
return value

if JujuVersion.from_environ().has_secrets:
secret_key = self._translate_field_to_secret_key(key)
label = generate_secret_label(self, scope)
for attempt in Retrying(stop=stop_after_attempt(3), wait=wait_fixed(1), reraise=True):
with attempt:
secret = self.secrets.get(label)
secret = self._safe_get_secret(scope, label)

if not secret:
return

secret_key = self._translate_field_to_secret_key(key)
value = secret.get_content().get(secret_key)
if value != SECRET_DELETED_LABEL:
return value
Expand All @@ -248,7 +262,7 @@ def set_secret(self, scope: Scopes, key: str, value: Optional[str]) -> Optional[

secret_key = self._translate_field_to_secret_key(key)
label = generate_secret_label(self, scope)
secret = self.secrets.get(label)
secret = self._safe_get_secret(scope, label)
if not secret:
self.secrets.add(label, {secret_key: value}, scope)
else:
Expand All @@ -267,7 +281,7 @@ def remove_secret(self, scope: Scopes, key: str) -> None:
if JujuVersion.from_environ().has_secrets:
secret_key = self._translate_field_to_secret_key(key)
label = generate_secret_label(self, scope)
secret = self.secrets.get(label)
secret = self._safe_get_secret(scope, label)

if not secret:
return
Expand Down

0 comments on commit db1ff02

Please sign in to comment.