Skip to content

Commit

Permalink
fix(model): Ensure Secret.get_content returns a copy of the dict
Browse files Browse the repository at this point in the history
This avoids the caller modifying the Secret instance's dict.

Fixes canonical#999
  • Loading branch information
benhoyt committed Aug 29, 2023
1 parent c9bba5b commit 826d2f8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
5 changes: 4 additions & 1 deletion ops/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,9 @@ def _on_secret_changed(self, event):
def get_content(self, *, refresh: bool = False) -> Dict[str, str]:
"""Get the secret's content.
Returns:
A copy of the secret's content dictionary.
Args:
refresh: If true, fetch the latest revision's content and tell
Juju to update to tracking that revision. The default is to
Expand All @@ -1190,7 +1193,7 @@ def get_content(self, *, refresh: bool = False) -> Dict[str, str]:
if refresh or self._content is None:
self._content = self._backend.secret_get(
id=self.id, label=self.label, refresh=refresh)
return self._content
return self._content.copy()

def peek_content(self) -> Dict[str, str]:
"""Get the content of the latest revision of this secret.
Expand Down
12 changes: 12 additions & 0 deletions test/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3104,6 +3104,18 @@ def test_get_content_uncached(self):
self.assertEqual(fake_script_calls(self, clear=True),
[['secret-get', 'secret:z', '--format=json']])

def test_get_content_copies_dict(self):
fake_script(self, 'secret-get', """echo '{"foo": "bar"}'""")

secret = self.make_secret(id='z')
content = secret.get_content()
self.assertEqual(content, {'foo': 'bar'})
content['new'] = 'value'
self.assertEqual(secret.get_content(), {'foo': 'bar'})

self.assertEqual(fake_script_calls(self, clear=True),
[['secret-get', 'secret:z', '--format=json']])

def test_peek_content(self):
fake_script(self, 'secret-get', """echo '{"foo": "peeked"}'""")

Expand Down

0 comments on commit 826d2f8

Please sign in to comment.