Skip to content

Commit 9f3980e

Browse files
committed
Add lazy KMS creation in AthenianKMS
Signed-off-by: Lou Marvin Caraig <[email protected]>
1 parent b2608bf commit 9f3980e

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

server/athenian/api/kms.py

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,32 @@ def __init__(self):
3838
"%s must be defined, see https://cloud.google.com/kms/docs/reference/rest"
3939
% env_names[0],
4040
)
41-
service_file_inline = os.getenv("GOOGLE_KMS_SERVICE_ACCOUNT_JSON_INLINE")
41+
42+
self._evars = evars
43+
44+
service_file_inline = os.getenv(
45+
"GOOGLE_KMS_SERVICE_ACCOUNT_JSON_INLINE")
4246
if service_file_inline is not None:
43-
service_file = io.StringIO(service_file_inline)
47+
self._service_file = io.StringIO(service_file_inline)
4448
else:
45-
service_file = os.getenv("GOOGLE_KMS_SERVICE_ACCOUNT_JSON")
46-
self._kms = KMS(**evars, service_file=service_file)
47-
self.log.info("Using Google KMS %(keyproject)s/%(keyring)s/%(keyname)s", evars)
49+
self._service_file = os.getenv("GOOGLE_KMS_SERVICE_ACCOUNT_JSON")
50+
51+
self._kms = None
52+
self.log.info(
53+
"Using Google KMS %(keyproject)s/%(keyring)s/%(keyname)s", evars)
54+
55+
async def _get_kms(self) -> KMS:
56+
if self._kms is None:
57+
self._kms = KMS(**self._evars, service_file=self._service_file)
58+
59+
return self._kms
4860

4961
async def encrypt(self, plaintext: Union[bytes, str]) -> str:
5062
"""Encrypt text using Google KMS."""
63+
kms = await self._get_kms()
5164
for attempt in range(self.timeout_retries):
5265
try:
53-
return await self._kms.encrypt(encode(plaintext))
66+
return await kms.encrypt(encode(plaintext))
5467
except asyncio.TimeoutError as e:
5568
self.log.warning("encrypt attempt %d", attempt + 1)
5669
if attempt == self.timeout_retries - 1:
@@ -59,9 +72,10 @@ async def encrypt(self, plaintext: Union[bytes, str]) -> str:
5972
async def decrypt(self, ciphertext: str) -> bytes:
6073
"""Decrypt text using Google KMS."""
6174
# we cannot use gcloud.aio.kms.decode because it converts bytes to string with str.decode()
75+
kms = await self._get_kms()
6276
for attempt in range(self.timeout_retries):
6377
try:
64-
payload = await self._kms.decrypt(ciphertext)
78+
payload = await kms.decrypt(ciphertext)
6579
except asyncio.TimeoutError as e:
6680
self.log.warning("decrypt attempt %d", attempt + 1)
6781
if attempt == self.timeout_retries - 1:
@@ -72,4 +86,5 @@ async def decrypt(self, ciphertext: str) -> bytes:
7286

7387
async def close(self):
7488
"""Close the underlying HTTPS session."""
75-
await self._kms.close()
89+
if self._kms is not None:
90+
await self._kms.close()

0 commit comments

Comments
 (0)