]> git.immae.eu Git - perso/Immae/Config/Nix.git/blobdiff - flakes/secrets/flake.nix
Move secrets to flakes
[perso/Immae/Config/Nix.git] / flakes / secrets / flake.nix
diff --git a/flakes/secrets/flake.nix b/flakes/secrets/flake.nix
new file mode 100644 (file)
index 0000000..0ee6a40
--- /dev/null
@@ -0,0 +1,124 @@
+{
+  description = "Secrets handling";
+
+  outputs = { self }: {
+    nixosModule = { config, lib, pkgs, ... }: {
+      options.secrets = with lib; {
+        keys = mkOption {
+          type = types.listOf types.unspecified;
+          default = [];
+          description = "Keys to upload to server";
+        };
+        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.listToAttrs
+            (map (v: { name = v.dest; value = "${config.secrets.location}/${v.dest}"; }) config.secrets.keys);
+          readOnly = true;
+          description = "set of full paths to secrets";
+        };
+      };
+
+      config = let
+        location = config.secrets.location;
+        keys = config.secrets.keys;
+        empty = pkgs.runCommand "empty" { preferLocalBuild = true; } "mkdir -p $out && touch $out/done";
+        fpath = v: "secrets/${v.dest}${lib.optionalString (v.isTemplated or true) ".gucci.tpl"}";
+        dumpKey = v:
+          if v.isDir or false then
+            ''
+              mkdir -p secrets/${v.dest}
+              cat >> mods <<EOF
+              ${v.user or "root"} ${v.group or "root"} ${v.permissions or "0600"} 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 or "root"} ${v.group or "root"} ${v.permissions or "0600"} ${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 or false) keys;
+            exclPath = builtins.concatStringsSep " -o " (map (d: " -path $TMP/${d.dest}") dirs);
+          in
+            lib.optionalString (builtins.length dirs > 0) " -not \\( ${exclPath} \\) ";
+      in lib.mkIf (builtins.length keys > 0) {
+        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" ]; 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
+              if [ -f ${config.secrets.secretsVars} ]; then
+                SOPS_AGE_KEY_FILE=$TMPWORK/keys.txt ${pkgs.sops}/bin/sops -d ${config.secrets.secretsVars} > $TMPWORK/vars.yml
+              fi
+              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
+          '';
+        };
+
+      };
+    };
+  };
+}