code improvement; use more secure flow to create secret file

This commit is contained in:
mlatus 2023-03-15 13:56:51 +08:00
parent c955d8fe91
commit efd85fbf51
2 changed files with 22 additions and 19 deletions

View file

@ -6,8 +6,7 @@ let
cfg = config.sops;
secretsForUsers = lib.filterAttrs (_: v: v.neededForUsers) cfg.secrets;
users = config.users.users;
substitute = pkgs.writers.writePython3 "substitute" { }
(replaceStrings [ "@subst@" ] [ "${subst-pairs}" ] (readFile ./subs.py));
substitute = pkgs.writers.writePython3 "substitute" { } (readFile ./subs.py);
subst-pairs = pkgs.writeText "pairs" (concatMapStringsSep "\n" (name:
"${toString config.sops.placeholder.${name}} ${
config.sops.secrets.${name}.path
@ -78,10 +77,6 @@ in {
default = { };
visible = false;
};
substituteCmd = mkOption {
type = types.path;
default = substitute;
};
};
config = optionalAttrs (options ? sops.secrets)
@ -98,10 +93,10 @@ in {
let tpl = config.sops.templates.${name};
in ''
mkdir -p "${dirOf tpl.path}"
${config.sops.substituteCmd} ${tpl.file} > ${tpl.path}
(umask 077; ${substitute} ${tpl.file} ${subst-pairs} > ${tpl.path})
chmod "${tpl.mode}" "${tpl.path}"
chown "${tpl.owner}" "${tpl.path}"
chgrp "${tpl.group}" "${tpl.path}"
chown "${tpl.owner}" "${tpl.path}"
'') (attrNames config.sops.templates)}
'');
});

View file

@ -1,17 +1,25 @@
from sys import argv
target = argv[1]
subst = "@subst@"
with open(target) as f:
content = f.read()
def substitute(target: str, subst: str) -> str:
with open(target) as f:
content = f.read()
with open(subst) as f:
subst_pairs = f.read().splitlines()
with open(subst) as f:
subst_pairs = f.read().splitlines()
for pair in subst_pairs:
placeholder, path = pair.split()
with open(path) as f:
content = content.replace(placeholder, f.read())
for pair in subst_pairs:
placeholder, path = pair.split()
with open(path) as f:
content = content.replace(placeholder, f.read())
print(content)
return content
def main() -> None:
target = argv[1]
subst = argv[2]
print(substitute(target, subst))
main()