-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathdefault.nix
372 lines (331 loc) · 11.5 KB
/
default.nix
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
{
pkgs,
config,
options,
lib,
...
}:
with lib; let
cfg = config.homeage;
ageBin = let
binName = (builtins.parseDrvName cfg.pkg.name).name;
in "${cfg.pkg}/bin/${binName}";
jq = lib.getExe pkgs.jq;
identities = builtins.concatStringsSep " " (map (path: "-i ${path}") cfg.identityPaths);
createFiles = command: runtimepath: destinations:
builtins.concatStringsSep "\n" ((map (dest: ''
$DRY_RUN_CMD mkdir $VERBOSE_ARG -p $(dirname ${dest})
$DRY_RUN_CMD ${command} $VERBOSE_ARG ${runtimepath} ${dest}
''))
destinations);
statePath = "homeage/state.json";
decryptSecret = name: {
source,
path,
symlinks,
copies,
mode,
owner,
group,
...
}: let
linksCmds = createFiles "ln -sf" path symlinks;
copiesCmds = createFiles "cp -f" path copies;
in ''
echo "Decrypting secret ${source} to ${path}"
TMP_FILE="${path}.tmp"
$DRY_RUN_CMD mkdir $VERBOSE_ARG -p $(dirname ${path})
(
$DRY_RUN_CMD umask u=r,g=,o=
$DRY_RUN_CMD ${ageBin} -d ${identities} -o "$TMP_FILE" "${source}"
)
$DRY_RUN_CMD chmod $VERBOSE_ARG ${mode} "$TMP_FILE"
$DRY_RUN_CMD chown $VERBOSE_ARG ${owner}:${group} "$TMP_FILE"
$DRY_RUN_CMD mv $VERBOSE_ARG -f "$TMP_FILE" "${path}"
${linksCmds}
${copiesCmds}
'';
cleanupSecret = prefix: ''
echo "${prefix}Cleaning up decrypted secret: $path"
# Cleanup symlinks
for symlink in ''${symlinks[@]}; do
if [ ! "$(readlink "$symlink")" == "$path" ]; then
echo "${prefix}Not removing symlink $symlink as it does not point to secret."
continue
fi
echo "${prefix}Removing symlink $symlink..."
unlink "$symlink"
rmdir --ignore-fail-on-non-empty --parents "$(dirname "$symlink")"
done
# Cleanup copies
for copy in ''${copies[@]}; do
if [ ! -f $path ]; then
echo "${prefix}Not removing copied file $copy because secret does not exist so can't verify wasn't modified."
continue
fi
if ! cmp -s "$copy" "$path"; then
echo "${prefix}Not removing copied file $copy because it was modified."
continue
fi
echo "${prefix}Removing copied file $copy..."
rm "$copy"
rmdir --ignore-fail-on-non-empty --parents "$(dirname "$copy")"
done
# Cleanup decrypted secret
if [ ! -f "$path" ]; then
echo "${prefix}Not removing secret file $path because does not exist."
continue
else
echo "${prefix}Removing secret file $path..."
rm "$path"
rmdir --ignore-fail-on-non-empty --parents "$(dirname "$path")"
fi
'';
activationFileCleanup = isActivation: ''
function homeageCleanup() {
# oldGenPath and newGenPath come from activation init:
# https://github.com/nix-community/home-manager/blob/master/modules/lib-bash/activation-init.sh
if [ ! -v oldGenPath ] ; then
echo "[homeage] No previous generation: no cleanup needed."
return 0
fi
local oldGenFile newGenFile
oldGenFile="$oldGenPath/${statePath}"
${
lib.optionalString isActivation ''
local newGenFile
newGenFile="$newGenPath/${statePath}"
# Technically not possible (state always written if has secrets). Check anyway
if [ ! -L "$newGenFile" ]; then
echo "[homeage] Activated but no current state" >&2
return 1
fi
''
}
if [ ! -L "$oldGenFile" ]; then
echo "[homeage] No previous homeage state: no cleanup needed"
return 0
fi
# Get all changed secrets for cleanup (intersection)
${jq} \
--null-input \
--compact-output \
--argfile old "$oldGenFile" \
${
if isActivation
then ''
--argfile new "$newGenFile" \
'$old - $new | .[]' |
''
else ''
'$old | .[]' |
''
}
# Replace $UID with $(id -u). Don't use eval
${pkgs.gnused}/bin/sed \
"s/\$UID/$(id -u)/g" |
while IFS=$"\n" read -r c; do
path=$(echo "$c" | ${jq} --raw-output '.path')
symlinks=$(echo "$c" | ${jq} --raw-output '.symlinks[]')
copies=$(echo "$c" | ${jq} --raw-output '.copies[]')
${cleanupSecret "[homeage] "}
done
echo "[homeage] Finished cleanup of secrets."
}
homeageCleanup
'';
# Options for a secret file
# Based on https://github.com/ryantm/agenix/pull/58
secretFile = types.submodule ({name, ...}: {
options = {
path = mkOption {
description = "Absolute path of where the file will be saved. Defaults to mount/name";
type = types.str;
default = "${cfg.mount}/${name}";
};
source = mkOption {
description = "Path to the age encrypted file";
type = types.path;
};
mode = mkOption {
type = types.str;
default = "0400";
description = "Permissions mode of the decrypted file";
};
owner = mkOption {
type = types.str;
default = "$UID";
description = "User of the decrypted file";
};
group = mkOption {
type = types.str;
default = "$(id -g)";
description = "Group of the decrypted file";
};
symlinks = mkOption {
type = types.listOf types.str;
default = [];
description = "Symbolically link decrypted file to absolute paths";
};
copies = mkOption {
type = types.listOf types.str;
default = [];
description = "Copy decrypted file to absolute paths";
};
};
});
in {
options.homeage = {
file = mkOption {
description = "Attrset of secret files";
default = {};
type = types.attrsOf secretFile;
};
pkg = mkOption {
description = "(R)age package to use. Detects if using rage and switches to `rage` as the command rather than `age`";
default = pkgs.age;
type = types.package;
};
mount = mkOption {
description = "Absolute path to folder where decrypted files are stored. Files are decrypted on login. Defaults to /run which is a tmpfs.";
default = "/run/user/$UID/secrets";
type = types.str;
};
identityPaths = mkOption {
description = "Absolute path to identity files used for age decryption. Must provide at least one path";
default = [];
type = types.listOf types.str;
};
installationType = mkOption {
description = ''
Specify the way how secrets should be installed. Either via systemd user services (<literal>systemd</literal>)
or during the activation of the generation (<literal>activation</literal>).
</para><para>
Note: Keep in mind that symlinked secrets will not work after reboots with <literal>activation</literal> if
<literal>homeage.mount</literal> does not point to persistent location.
Cleanup notes:
* Systemd performs cleanup when service stops.
* Activation performs cleanup after write boundary during activation.
* When switching from systemd to activation, may need to activate twice.
Because stopping systemd services, and thus cleanup, happens after
activation decryption. Only occurs on the first activation.
Cases when copied file/symlink is not removed:
1. Symlink does not point to the decrypted secret file.
2. Any copied file when the original secret file does not exist (can't verify they weren't modified).
3. Copied file when it does not match the original secret file (using `cmp`).
'';
default = "systemd";
type = types.enum ["activation" "systemd"];
};
};
config = mkIf (cfg.file != {}) (mkMerge [
{
assertions = [
{
assertion = cfg.identityPaths != [];
message = "secret.identityPaths must be set.";
}
{
assertion = let
paths = mapAttrsToList (_: value: value.path) cfg.file;
in
(unique paths) == paths;
message = "overlapping secret file paths.";
}
];
# Decryption check is enabled for all installation types
home.activation.homeageDecryptCheck = let
decryptCheckScript = name: source: ''
if ! ${ageBin} -d ${identities} -o /dev/null ${source} 2>/dev/null ; then
DECRYPTION="''${DECRYPTION}[homeage] Failed to decrypt ${name}\n"
fi
'';
checkDecryptionScript = ''
DECRYPTION=
${
builtins.concatStringsSep "\n"
(lib.mapAttrsToList (n: v: decryptCheckScript n v.source) cfg.file)
}
if [ ! -x $DECRYPTION ]; then
printf "''${errorColor}''${DECRYPTION}[homeage] Check homage.identityPaths to either add an identity or remove a broken one\n''${normalColor}" 1>&2
exit 1
fi
'';
in
hm.dag.entryBefore ["writeBoundary"] checkDecryptionScript;
}
(mkIf (cfg.installationType == "activation") {
home = {
# Always write state if activation installation so will
# cleanup the previous generations when cleanup gets enabled
# Do not write if systemd installation because cleanup will be done through systemd units
extraBuilderCommands = let
stateFile =
pkgs.writeText
"homeage-state.json"
(builtins.toJSON
(map
(secret: secret)
(builtins.attrValues cfg.file)));
in ''
mkdir -p $(dirname $out/${statePath})
ln -s ${stateFile} $out/${statePath}
'';
activation = {
homeageCleanup = let
fileCleanup = activationFileCleanup true;
in
hm.dag.entryBetween ["homeageDecrypt"] ["writeBoundary"] fileCleanup;
homeageDecrypt = let
activationScript = builtins.concatStringsSep "\n" (lib.attrsets.mapAttrsToList decryptSecret cfg.file);
in
hm.dag.entryBetween ["reloadSystemd"] ["writeBoundary"] activationScript;
};
};
})
(mkIf (cfg.installationType == "systemd") {
# Need to cleanup secrets if switching from activation -> systemd
home.activation.homeageCleanup = let
fileCleanup = activationFileCleanup false;
in
hm.dag.entryAfter ["writeBoundary"] fileCleanup;
systemd.user.services = let
mkServices =
lib.attrsets.mapAttrs'
(
name: value:
lib.attrsets.nameValuePair
"${name}-secret"
{
Unit = {
Description = "Decrypt ${name} secret";
};
Service = {
Type = "oneshot";
Environment = "PATH=${makeBinPath [pkgs.coreutils pkgs.diffutils]}";
ExecStart = "${pkgs.writeShellScript "${name}-decrypt" ''
set -euo pipefail
DRY_RUN_CMD=
VERBOSE_ARG=
${decryptSecret name value}
''}";
RemainAfterExit = true;
ExecStop = "${pkgs.writeShellScript "${name}-cleanup" ''
set -euo pipefail
path="${value.path}"
symlinks=(${builtins.concatStringsSep " " value.symlinks})
copies=(${builtins.concatStringsSep " " value.copies})
${cleanupSecret ""}
''}";
};
Install = {
WantedBy = ["default.target"];
};
}
)
cfg.file;
in
mkServices;
})
]);
}