aboutsummaryrefslogtreecommitdiff
path: root/flakes/secrets/flake.nix
blob: 7bf04a4517fb2ed4f839ff56d14526294d9fbfcf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
{
  description = "Secrets handling";

  outputs = { self }: {
    nixosModule = { config, lib, pkgs, ... }: {
      # Necessary for situations where flake gets included multiple times
      key = builtins.hashString "sha256" (builtins.path { path = self.sourceInfo.outPath; name = "source"; });
      options.secrets = with lib; {
        keys = mkOption {
          type = types.attrsOf (types.submodule {
            options = {
              isTemplated = mkOption {
                type = types.bool;
                default = true;
                description = "If the file is a gucci template that needs to be resolved";
              };
              isDir = mkOption {
                type = types.bool;
                default = false;
                description = "If the entry is a directory";
              };
              group = mkOption {
                type = types.str;
                default = "root";
                description = "Group to associate to the entry";
              };
              user = mkOption {
                type = types.str;
                default = "root";
                description = "User to associate to the entry";
              };
              permissions = mkOption {
                type = types.str;
                default = "0600";
                description = "Permissions to associate to the entry";
              };
              text = mkOption {
                type = types.str;
                description = "Content of the entry";
              };
              keyDependencies = mkOption {
                default = [];
                type = types.listOf (types.either types.path types.package);
                description = ''
                  (public) system dependencies that needs to be
                  uploaded with the key.

                  keyDependencies + ignoredKeyDependencies should
                  contain the exhaustive list of the text context.

                  A warning will be thrown if there are remaning
                  dependencies from the text.
                '';
              };
              ignoredKeyDependencies = mkOption {
                default = [];
                type = types.listOf (types.either types.path types.package);
                description = ''
                  dependencies that must not be sent along with the key.

                  keyDependencies + ignoredKeyDependencies should
                  contain the exhaustive list of the text context.

                  A warning will be thrown if there are remaning
                  dependencies from the text.
                '';
              };
            };
          });
          default = {};
          description = "Keys attrs to upload to the server";
          apply = builtins.mapAttrs (dest: v: v // { inherit dest; });
        };
        gpgKeys = mkOption {
          type = types.listOf types.path;
          default = [];
          description = "GPG public keys files to encrypt to";
        };
        ageKeys = mkOption {
          type = types.listOf types.str;
          default = [];
          description = "AGE keys to encrypt to";
        };
        decryptKey = mkOption {
          type = types.str;
          default = "/etc/ssh/ssh_host_ed25519_key";
          description = "ed25519 key used to decrypt with AGE";
        };
        location = mkOption {
          type = types.path;
          default = "/var/secrets";
          description = "Location where to put the keys";
        };
        secretsVars = mkOption {
          type = types.path;
          description = "Location where the secrets variables are defined, to be used to fill the templates in secrets";
        };
        deleteSecretsVars = mkOption {
          type = types.bool;
          default = false;
          description = "Delete secrets file after deployment";
        };
        # Read-only variables
        fullPaths = mkOption {
          type = types.attrsOf types.path;
          default = builtins.mapAttrs
            (n: v: "${config.secrets.location}/${n}") config.secrets.keys;
          readOnly = true;
          description = "set of full paths to secrets";
        };
      };

      config = let
        location = config.secrets.location;
        keys = builtins.attrValues config.secrets.keys;
        empty = pkgs.runCommand "empty" { preferLocalBuild = true; } "mkdir -p $out && touch $out/done";
        fpath = v: "secrets/${v.dest}${lib.optionalString v.isTemplated ".gucci.tpl"}";
        dumpKey = v:
          if v.isDir then
            ''
              mkdir -p secrets/${v.dest}
              cat >> mods <<EOF
              ${v.user} ${v.group} ${v.permissions} secrets/${v.dest}
              EOF
            ''
          else ''
            mkdir -p secrets/$(dirname ${v.dest})
            echo -n ${lib.strings.escapeShellArg v.text} > ${fpath v}
            cat >> mods <<EOF
            ${v.user} ${v.group} ${v.permissions} ${fpath v}
            EOF
            '';
        secrets = pkgs.runCommand "secrets.tar.enc" {
          buildInputs = [ pkgs.gnupg pkgs.sops ];
          } ''
          touch mods
          tar --format=ustar --mtime='1970-01-01' -P --transform="s@${empty}@secrets@" -cf $out ${empty}/done
          ${builtins.concatStringsSep "\n" (map dumpKey keys)}
          cat mods | while read u g p k; do
          tar --no-recursion --format=ustar --mtime='1970-01-01' --owner="$u" --group="$g" --mode="$p" --append -f $out "$k"
          done
          export HOME=$(pwd)
          fingerprints=
          for key in ${builtins.concatStringsSep " " config.secrets.gpgKeys}; do
            gpg --import $key 2>/dev/null
            fingerprints=$fingerprints,$(cat $key | gpg --with-colons --import-options show-only --import 2>/dev/null | grep ^fpr | cut -d: -f10 | head -n1)
          done

          sops --age ${builtins.concatStringsSep "," config.secrets.ageKeys} --pgp ''${fingerprints#,} --input-type binary -i -e $out 2>/dev/null
          '';
        pathChmodExcl =
          let
            dirs = builtins.filter (v: v.isDir) keys;
            exclPath = builtins.concatStringsSep " -o " (map (d: " -path $TMP/${d.dest}") dirs);
          in
            lib.optionalString (builtins.length dirs > 0) " -not \\( ${exclPath} \\) ";

        checkKeyDependencies = key:
          let
            allDeps = builtins.map (n: if builtins.isPath n then "${n}" else n.drvPath) (key.keyDependencies ++ key.ignoredKeyDependencies);
            context = builtins.attrNames (builtins.getContext key.text);
            missing = builtins.foldl' (o: n: lib.remove n o) context allDeps;
          in
            lib.optional (!key.isDir && builtins.length missing > 0)
              ''
                Key ${key.dest} has non declared dependencies in its context: ${builtins.concatStringsSep " " missing}
                Add them to ignoredKeyDependencies to ignore
              '';
      in lib.mkIf (builtins.length keys > 0) {
        warnings = lib.concatMap checkKeyDependencies keys;
        # FIXME: Use lib.concatMap (k: k.keyDependencies) keys in latest nixpkgs
        system.extraDependencies = lib.concatMap (k: builtins.map (dep:
          if builtins.isPath dep then pkgs.writeText "extra-dep" "${dep}" else dep
        ) k.keyDependencies) keys;
        system.activationScripts.secrets = {
          deps = [ "users" "wrappers" ];
          text = ''
            install -m0750 -o root -g keys -d ${location}
            TMP=$(${pkgs.coreutils}/bin/mktemp -d)
            TMPWORK=$(${pkgs.coreutils}/bin/mktemp -d)
            chmod go-rwx $TMPWORK
            if [ -n "$TMP" -a -n "$TMPWORK" -a -f ${config.secrets.secretsVars} ]; then
              install -m0750 -o root -g keys -d $TMP
              ${pkgs.ssh-to-age}/bin/ssh-to-age -private-key -i ${config.secrets.decryptKey} -o $TMPWORK/keys.txt
              SOPS_AGE_KEY_FILE=$TMPWORK/keys.txt ${pkgs.sops}/bin/sops -d ${secrets} | ${pkgs.gnutar}/bin/tar --strip-components 1 -C $TMP -x
              SOPS_AGE_KEY_FILE=$TMPWORK/keys.txt ${pkgs.sops}/bin/sops -d ${config.secrets.secretsVars} > $TMPWORK/vars.yml
              if [ -f $TMPWORK/vars.yml ]; then
                find $TMP -name "*.gucci.tpl" -exec \
                  /bin/sh -c 'f="{}"; ${pkgs.gucci}/bin/gucci -f '$TMPWORK'/vars.yml "$f" > "''${f%.gucci.tpl}"; touch --reference "$f" ''${f%.gucci.tpl} ; chmod --reference="$f" ''${f%.gucci.tpl} ; chown --reference="$f" ''${f%.gucci.tpl}' \;
              fi
              find $TMP -type d ${pathChmodExcl}-exec chown root:keys {} \; -exec chmod o-rx {} \;
              ${pkgs.rsync}/bin/rsync --exclude="*.gucci.tpl" -O -c -av --delete $TMP/ ${location}
              rm -rf $TMP $TMPWORK ${lib.optionalString config.secrets.deleteSecretsVars config.secrets.secretsVars}
            fi
          '';
        };

      };
    };
  };
}