]> git.immae.eu Git - perso/Immae/Config/Nix/NUR.git/blob - modules/secrets.nix
808b15c5bdeb886347a8f9c34f69891495e0999f
[perso/Immae/Config/Nix/NUR.git] / modules / secrets.nix
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 };
15 config = let
16 location = config.secrets.location;
17 keys = config.secrets.keys;
18 empty = pkgs.runCommand "empty" { preferLocalBuild = true; } "mkdir -p $out && touch $out/done";
19 dumpKey = v: ''
20 mkdir -p secrets/$(dirname ${v.dest})
21 echo -n ${lib.strings.escapeShellArg v.text} > secrets/${v.dest}
22 cat >> mods <<EOF
23 ${v.user or "root"} ${v.group or "root"} ${v.permissions or "0600"} secrets/${v.dest}
24 EOF
25 '';
26 secrets = pkgs.runCommand "secrets.tar" {} ''
27 touch mods
28 tar --format=ustar --mtime='1970-01-01' -P --transform="s@${empty}@secrets@" -cf $out ${empty}/done
29 ${builtins.concatStringsSep "\n" (map dumpKey keys)}
30 cat mods | while read u g p k; do
31 tar --format=ustar --mtime='1970-01-01' --owner="$u" --group="$g" --mode="$p" --append -f $out "$k"
32 done
33 '';
34 in lib.mkIf (builtins.length keys > 0) {
35 system.activationScripts.secrets = {
36 deps = [ "users" "wrappers" ];
37 text = ''
38 install -m0750 -o root -g keys -d ${location}
39 if [ -f /run/keys/secrets.tar ]; then
40 if [ ! -f ${location}/currentSecrets ] || ! sha512sum -c --status "${location}/currentSecrets"; then
41 echo "rebuilding secrets"
42 TMP=$(${pkgs.coreutils}/bin/mktemp -d)
43 if [ -n "$TMP" ]; then
44 install -m0750 -o root -g keys -d $TMP
45 ${pkgs.gnutar}/bin/tar --strip-components 1 -C $TMP -xf /run/keys/secrets.tar
46 sha512sum /run/keys/secrets.tar > $TMP/currentSecrets
47 find $TMP -type d -exec chown root:keys {} \; -exec chmod o-rx {} \;
48 ${pkgs.rsync}/bin/rsync -O -c -av --delete $TMP/ ${location}
49 rm -rf $TMP
50 fi
51 fi
52 fi
53 '';
54 };
55 deployment.keys."secrets.tar" = {
56 permissions = "0400";
57 # keyFile below is not evaluated at build time by nixops, so the
58 # `secrets` path doesn’t necessarily exist when uploading the
59 # keys, and nixops is unhappy.
60 user = "root${builtins.substring 10000 1 secrets}";
61 group = "root";
62 keyFile = "${secrets}";
63 };
64 };
65 }