Debian Codegraph @

test/units/mock/vault_helper.py

raw
1 from __future__ import annotations
2
3 from ansible._internal._datatag import _tags
4 from ansible.module_utils.common.text.converters import to_bytes
5 from ansible.parsing.vault import VaultSecret, VaultSecretsContext, VaultLib, EncryptedString
6
7
8 class TextVaultSecret(VaultSecret):
9 """A secret piece of text. ie, a password. Tracks text encoding.
10
11 The text encoding of the text may not be the default text encoding so
12 we keep track of the encoding so we encode it to the same bytes."""
13
14 def __init__(self, text, encoding=None, errors=None, _bytes=None):
15 super(TextVaultSecret, self).__init__()
16 self.text = text
17 self.encoding = encoding or 'utf-8'
18 self._bytes = _bytes
19 self.errors = errors or 'strict'
20
21 @property
22 def bytes(self):
23 """The text encoded with encoding, unless we specifically set _bytes."""
24 return self._bytes or to_bytes(self.text, encoding=self.encoding, errors=self.errors)
25
26
27 class VaultTestHelper:
28 @classmethod
29 def make_vault_ciphertext(cls, plaintext: str) -> str:
30 """Creates an `EncryptedString` from the first secret in the active VaultSecretsContext."""
31 secrets = VaultSecretsContext.current().secrets
32 vl = VaultLib(secrets)
33
34 return vl.encrypt(plaintext, secrets[0][1]).decode()
35
36 @classmethod
37 def make_encrypted_string(cls, plaintext: str) -> EncryptedString:
38 """Creates an `EncryptedString` from the first secret in the active VaultSecretsContext."""
39 return _tags.Origin(path="/tmp/sometest", line_num=42, col_num=42).tag(EncryptedString(ciphertext=cls.make_vault_ciphertext(plaintext)))