]> git.immae.eu Git - perso/Immae/Config/Nix.git/blame - modules/secrets.nix
Upgrade syden peertube to flake
[perso/Immae/Config/Nix.git] / modules / secrets.nix
CommitLineData
1a718805 1{ lib, pkgs, config, ... }:
44742a43 2{
1a718805 3 options.secrets = {
44742a43
IB
4 keys = lib.mkOption {
5 type = lib.types.listOf lib.types.unspecified;
1a718805 6 default = [];
44742a43
IB
7 description = "Keys to upload to server";
8 };
1a718805
IB
9 location = lib.mkOption {
10 type = lib.types.path;
11 default = "/var/secrets";
12 description = "Location where to put the keys";
13 };
717ccfd9
IB
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 };
44742a43 22 };
717ccfd9 23
44742a43 24 config = let
1a718805
IB
25 location = config.secrets.location;
26 keys = config.secrets.keys;
44742a43 27 empty = pkgs.runCommand "empty" { preferLocalBuild = true; } "mkdir -p $out && touch $out/done";
44742a43
IB
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
44742a43
IB
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 '';
1a718805 43 in lib.mkIf (builtins.length keys > 0) {
44742a43
IB
44 system.activationScripts.secrets = {
45 deps = [ "users" "wrappers" ];
46 text = ''
1a718805 47 install -m0750 -o root -g keys -d ${location}
44742a43 48 if [ -f /run/keys/secrets.tar ]; then
1a718805 49 if [ ! -f ${location}/currentSecrets ] || ! sha512sum -c --status "${location}/currentSecrets"; then
44742a43 50 echo "rebuilding secrets"
17f6eae9
IB
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
44742a43
IB
60 fi
61 fi
62 '';
63 };
34abd6af
IB
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";
44742a43 70 permissions = "0400";
44742a43
IB
71 };
72 };
73}