Skip to content

Commit 17c4bca

Browse files
committed
Add read_secret_data for user secrets
1 parent aa5d7f6 commit 17c4bca

1 file changed

Lines changed: 33 additions & 4 deletions

File tree

juju/secrets.py

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@
77

88

99
import base64
10-
from pathlib import Path
10+
import json
1111
import re
12+
import yaml
13+
from pathlib import Path
14+
from . import errors
1215

1316
file_suffix = "#file"
1417
max_value_size_bytes = 5 * 1024
@@ -50,7 +53,7 @@ def create_secret_data(args):
5053
except Exception as e:
5154
raise ValueError(f"Error processing key {key}: {e}")
5255

53-
return encodeValuesBase64(data)
56+
return encode_values_base64(data)
5457

5558

5659
def read_secret_data(file):
@@ -60,14 +63,40 @@ def read_secret_data(file):
6063
6164
:return []str: bag of key value pairs for a secret
6265
"""
63-
return {}
66+
data = {}
67+
path = Path(file).resolve()
68+
69+
try:
70+
fs = path.stat()
71+
if fs.st_size > max_content_size_bytes:
72+
raise ValueError(f"Secret content in file {path} too large: {fs.st_size} bytes")
73+
except FileNotFoundError:
74+
raise FileNotFoundError(f"The file {path} does not exist.")
75+
except OSError:
76+
raise
77+
78+
try:
79+
with open(path, 'r', encoding='utf-8') as file:
80+
data = file.read()
81+
except Exception:
82+
raise
83+
84+
try:
85+
data = json.loads(data)
86+
except json.JSONDecodeError:
87+
try:
88+
data = yaml.safe_load(data)
89+
except yaml.YAMLError:
90+
raise errors.JujuNotValid(f"Invalid data file at: {file}")
91+
92+
return encode_values_base64(data)
6493

6594

6695
base64_suffix = "#base64"
6796
key_reg_exp = re.compile("^([a-z](?:-?[a-z0-9]){2,})$")
6897

6998

70-
def encodeValuesBase64(data):
99+
def encode_values_base64(data):
71100
"""Encodes the values in the given data bag for a secret
72101
73102
If a key has the #base64 suffix, then the value is already base64 encoded,otherwise the value is base64 encoded as it is added to the data bag.

0 commit comments

Comments
 (0)