edq.config.cmd.encrypt

Encrypt any unencrypted secrets present in configuration files.

 1"""
 2Encrypt any unencrypted secrets present in configuration files.
 3"""
 4
 5import argparse
 6import os
 7
 8import edq.config.settings
 9import edq.config.util
10import edq.util.crypto
11import edq.util.serial
12
13def run(args: argparse.Namespace) -> int:
14    """ Run the target command and return the suggested exit status. """
15
16    config_info = args._config_info
17
18    paths = set()
19
20    if (len(args.paths) > 0):
21        paths |= set(args.paths)
22    else:
23        for load_results in args._config_info.sources.values():
24            paths |= {result.path for result in load_results if (result.path is not None)}
25
26    encryption_key = config_info.application_config.encryption_key
27    config_class = type(config_info.application_config)
28    serialization_context = edq.util.serial.SerializationContext(key = encryption_key)
29
30    count = 0
31    for path in sorted(paths):
32        path = os.path.abspath(path)
33        if (not os.path.exists(path)):
34            continue
35
36        file_config = config_class.from_path(path, context = serialization_context)
37
38        to_write = {}
39        for attr_name in dir(file_config):
40            attr = getattr(file_config, attr_name, None)
41            if (attr is None):
42                continue
43
44            if (not isinstance(attr, edq.util.crypto.Secret)):
45                continue
46
47            if (attr.is_encrypted()):
48                continue
49
50            to_write[attr_name] = attr.encrypt(encryption_key)
51            count += 1
52
53        if (len(to_write) > 0):
54            print(f"Found {len(to_write)} unencrypted secret(s) in '{path}': {sorted(to_write.keys())}.")
55
56        if ((len(to_write) > 0) and (not args.dry_run)):
57            edq.config.util.update_options_in_config_file(path, to_write)
58
59    if (count > 0):
60        print(f"Encrypted {count} secret(s).")
61    else:
62        print("Found no unencrypted secrets.")
63
64    return 0
65
66def modify_parser(parser: argparse.ArgumentParser) -> None:
67    """ Add this CLI's flags to the given parser. """
68
69    group = parser.add_argument_group('encrypt options')
70
71    group.add_argument('--dry-run', dest = 'dry_run',
72        action = 'store_true',
73        help = "Do not write any data, just state would would happen.",
74    )
75
76    group.add_argument('paths', metavar = 'PATHS',
77        action = 'store', nargs = '*', type = str,
78        help = "Optional paths to look for unencrypted secrets. If no paths are specified, all active config paths will be used.",
79    )
def run(args: argparse.Namespace) -> int:
14def run(args: argparse.Namespace) -> int:
15    """ Run the target command and return the suggested exit status. """
16
17    config_info = args._config_info
18
19    paths = set()
20
21    if (len(args.paths) > 0):
22        paths |= set(args.paths)
23    else:
24        for load_results in args._config_info.sources.values():
25            paths |= {result.path for result in load_results if (result.path is not None)}
26
27    encryption_key = config_info.application_config.encryption_key
28    config_class = type(config_info.application_config)
29    serialization_context = edq.util.serial.SerializationContext(key = encryption_key)
30
31    count = 0
32    for path in sorted(paths):
33        path = os.path.abspath(path)
34        if (not os.path.exists(path)):
35            continue
36
37        file_config = config_class.from_path(path, context = serialization_context)
38
39        to_write = {}
40        for attr_name in dir(file_config):
41            attr = getattr(file_config, attr_name, None)
42            if (attr is None):
43                continue
44
45            if (not isinstance(attr, edq.util.crypto.Secret)):
46                continue
47
48            if (attr.is_encrypted()):
49                continue
50
51            to_write[attr_name] = attr.encrypt(encryption_key)
52            count += 1
53
54        if (len(to_write) > 0):
55            print(f"Found {len(to_write)} unencrypted secret(s) in '{path}': {sorted(to_write.keys())}.")
56
57        if ((len(to_write) > 0) and (not args.dry_run)):
58            edq.config.util.update_options_in_config_file(path, to_write)
59
60    if (count > 0):
61        print(f"Encrypted {count} secret(s).")
62    else:
63        print("Found no unencrypted secrets.")
64
65    return 0

Run the target command and return the suggested exit status.

def modify_parser(parser: argparse.ArgumentParser) -> None:
67def modify_parser(parser: argparse.ArgumentParser) -> None:
68    """ Add this CLI's flags to the given parser. """
69
70    group = parser.add_argument_group('encrypt options')
71
72    group.add_argument('--dry-run', dest = 'dry_run',
73        action = 'store_true',
74        help = "Do not write any data, just state would would happen.",
75    )
76
77    group.add_argument('paths', metavar = 'PATHS',
78        action = 'store', nargs = '*', type = str,
79        help = "Optional paths to look for unencrypted secrets. If no paths are specified, all active config paths will be used.",
80    )

Add this CLI's flags to the given parser.