]>
Commit | Line | Data |
---|---|---|
1 | { lib, pkgs, config, ... }: | |
2 | { | |
3 | options.secrets = { | |
4 | keys = lib.mkOption { | |
5 | type = lib.types.listOf lib.types.unspecified; | |
6 | default = []; | |
7 | description = "Keys to upload to server"; | |
8 | }; | |
9 | location = lib.mkOption { | |
10 | type = lib.types.path; | |
11 | default = "/var/secrets"; | |
12 | description = "Location where to put the keys"; | |
13 | }; | |
14 | # Read-only variables | |
15 | fullPaths = lib.mkOption { | |
16 | type = lib.types.attrsOf lib.types.path; | |
17 | default = builtins.listToAttrs | |
18 | (map (v: { name = v.dest; value = "${config.secrets.location}/${v.dest}"; }) config.secrets.keys); | |
19 | readOnly = true; | |
20 | description = "set of full paths to secrets"; | |
21 | }; | |
22 | }; | |
23 | ||
24 | config = let | |
25 | location = config.secrets.location; | |
26 | keys = config.secrets.keys; | |
27 | empty = pkgs.runCommand "empty" { preferLocalBuild = true; } "mkdir -p $out && touch $out/done"; | |
28 | dumpKey = v: '' | |
29 | mkdir -p secrets/$(dirname ${v.dest}) | |
30 | echo -n ${lib.strings.escapeShellArg v.text} > secrets/${v.dest} | |
31 | cat >> mods <<EOF | |
32 | ${v.user or "root"} ${v.group or "root"} ${v.permissions or "0600"} secrets/${v.dest} | |
33 | EOF | |
34 | ''; | |
35 | secrets = pkgs.runCommand "secrets.tar" {} '' | |
36 | touch mods | |
37 | tar --format=ustar --mtime='1970-01-01' -P --transform="s@${empty}@secrets@" -cf $out ${empty}/done | |
38 | ${builtins.concatStringsSep "\n" (map dumpKey keys)} | |
39 | cat mods | while read u g p k; do | |
40 | tar --format=ustar --mtime='1970-01-01' --owner="$u" --group="$g" --mode="$p" --append -f $out "$k" | |
41 | done | |
42 | ''; | |
43 | in lib.mkIf (builtins.length keys > 0) { | |
44 | system.activationScripts.secrets = { | |
45 | deps = [ "users" "wrappers" ]; | |
46 | text = '' | |
47 | install -m0750 -o root -g keys -d ${location} | |
48 | if [ -f /run/keys/secrets.tar ]; then | |
49 | if [ ! -f ${location}/currentSecrets ] || ! sha512sum -c --status "${location}/currentSecrets"; then | |
50 | echo "rebuilding secrets" | |
51 | TMP=$(${pkgs.coreutils}/bin/mktemp -d) | |
52 | if [ -n "$TMP" ]; then | |
53 | install -m0750 -o root -g keys -d $TMP | |
54 | ${pkgs.gnutar}/bin/tar --strip-components 1 -C $TMP -xf /run/keys/secrets.tar | |
55 | sha512sum /run/keys/secrets.tar > $TMP/currentSecrets | |
56 | find $TMP -type d -exec chown root:keys {} \; -exec chmod o-rx {} \; | |
57 | ${pkgs.rsync}/bin/rsync -O -c -av --delete $TMP/ ${location} | |
58 | rm -rf $TMP | |
59 | fi | |
60 | fi | |
61 | fi | |
62 | ''; | |
63 | }; | |
64 | system.extraDependencies = [ secrets ]; | |
65 | deployment.secrets."secrets.tar" = { | |
66 | source = "${secrets}"; | |
67 | destination = "/run/keys/secrets.tar"; | |
68 | owner.user = "root"; | |
69 | owner.group = "root"; | |
70 | permissions = "0400"; | |
71 | }; | |
72 | }; | |
73 | } |