Compare commits

..

9 Commits

Author SHA1 Message Date
John Lancaster 2fea8238d1 systemd 2026-05-01 00:11:55 -05:00
John Lancaster cf1174d36b consolidation 2026-04-30 22:39:27 -05:00
John Lancaster bae2b3027e WIP mtls wrapper 2026-04-30 22:28:35 -05:00
John Lancaster 68483c0231 improvement 2026-04-30 16:36:38 -05:00
John Lancaster f0eba76e49 mtls-check wrapping openssl kinda working 2026-04-30 16:31:26 -05:00
John Lancaster 8357372b39 mtlsCheck wrapper 2026-04-29 21:46:11 -05:00
John Lancaster 3c4aa74b0f WIP mtls wrappers 2026-04-29 21:36:16 -05:00
John Lancaster ed473ddfae started zed-editor wrapper, package, and home-manager module 2026-04-29 17:46:01 -05:00
John Lancaster 133bad5aef started mtls wrappers 2026-04-27 09:01:19 -05:00
2 changed files with 283 additions and 164 deletions
+250 -164
View File
@@ -48,7 +48,7 @@ let
enable = lib.mkOption { enable = lib.mkOption {
description = "Enable automatic mTLS certificate renewal using a systemd timer."; description = "Enable automatic mTLS certificate renewal using a systemd timer.";
type = lib.types.bool; type = lib.types.bool;
default = true; default = cfg.enable;
}; };
onCalendar = lib.mkOption { onCalendar = lib.mkOption {
description = "systemd OnCalendar schedule for mTLS certificate renewal checks."; description = "systemd OnCalendar schedule for mTLS certificate renewal checks.";
@@ -115,154 +115,28 @@ let
''; '';
}; };
mkMtlsCheckScript = { pkgs, bundleFile }: pkgs.writeShellApplication {
name = "mtls-check";
runtimeInputs = with pkgs; [ openssl ];
text = ''
openssl x509 -noout -in ${bundleFile} \
-subject -issuer \
-ext subjectAltName,extendedKeyUsage \
-enddate
'';
};
mkMtlsRenewScript = {
pkgs,
cfg,
systemctlArgs ? [ ],
}:
let
systemctlCmd = "systemctl ${lib.escapeShellArgs systemctlArgs}";
hasReloadUnits = cfg.renew.reloadUnits != [ ];
renewReloadScript = lib.concatMapStringsSep "\n" (unit: ''
if ${systemctlCmd} --quiet is-active "${unit}"; then
${systemctlCmd} try-reload-or-restart "${unit}"
fi
'') cfg.renew.reloadUnits;
hasPostCommands = cfg.renew.postCommands != [ ];
renewPostCommands = lib.concatStringsSep "\n" cfg.renew.postCommands;
fileOwner = "${cfg.renew.user}:${cfg.renew.group}";
in
pkgs.writeShellApplication {
name = "mtls-renew";
runtimeInputs = with pkgs; [ coreutils step-cli systemd ];
text = ''
set -euo pipefail
YELLOW_BANG="\e[33m!\e[0m"
force=0
while [[ $# -gt 0 ]]; do
case $1 in
--force)
force=1
shift
;;
*)
echo -e "$YELLOW_BANG Warning: ignoring unrecognized argument '$1'"
exit 1
;;
esac
done
if [[ $force -eq 0 ]] && ! step certificate needs-renewal "${cfg.certFile}"; then
echo "Skipping renew"
exit 0
fi
echo "Renewing mTLS certificate"
step ca renew --force "${cfg.certFile}" "${cfg.keyFile}"
(umask 077; cat "${cfg.certFile}" "${cfg.keyFile}" > "${cfg.bundleFile}")
chown ${fileOwner} ${cfg.certFile} ${cfg.keyFile} ${cfg.bundleFile}
chmod 640 ${cfg.certFile} ${cfg.keyFile} ${cfg.bundleFile}
${lib.optionalString hasReloadUnits ''
echo "Reloading units: ${lib.concatStringsSep ", " cfg.renew.reloadUnits}"
${renewReloadScript}
''}
${lib.optionalString hasPostCommands ''echo "Post commands:" ${renewPostCommands}''}
'';
};
mkNixosMtlsRenewService = { pkgs, cfg, ... }:
{
description = "Renew the mTLS certificate when Smallstep marks it ready";
wantedBy = [ ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
User = cfg.renew.user;
Group = cfg.renew.group;
ExecStart = lib.getExe (mkMtlsRenewScript { inherit pkgs cfg; });
};
};
mkNixosMtlsRenewTimer = {
onCalendar,
randomizedDelaySec,
unit ? "mtls-renew.service",
}: {
description = "Periodic Smallstep renewal for the mTLS certificate";
wantedBy = [ "timers.target" ];
timerConfig = {
Persistent = true;
OnCalendar = onCalendar;
AccuracySec = "1us";
RandomizedDelaySec = randomizedDelaySec;
Unit = unit;
};
};
mkHomeManagerMtlsRenewService = { pkgs, cfg, ... }:
let
renewScript = mkMtlsRenewScript {
inherit pkgs cfg;
systemctlArgs = [ "--user" ];
};
in
{
Unit = {
Description = "Renew the mTLS certificate when Smallstep marks it ready";
After = [ "network-online.target" ];
Wants = [ "network-online.target" ];
};
Service = {
Type = "oneshot";
ExecStart = lib.getExe renewScript;
};
};
mkHomeManagerMtlsRenewTimer = {
onCalendar,
randomizedDelaySec,
unit ? "mtls-renew.service",
}: {
Unit = {
Description = "Periodic Smallstep renewal for the mTLS certificate";
};
Timer = {
Persistent = true;
OnCalendar = onCalendar;
AccuracySec = "1us";
RandomizedDelaySec = randomizedDelaySec;
Unit = unit;
};
Install = {
WantedBy = [ "timers.target" ];
};
};
in in
{ {
flake.modules.nixos.mtls = { config, lib, pkgs, ... }: flake.modules.nixos.mtls = { config, lib, pkgs, ... }:
let let
cfg = config.mtls; cfg = config.mtls;
sanArgs = lib.concatMapStringsSep " " (san: "--san \"${san}\"") cfg.san; mtlsRenewWrapper = inputs.self.wrappers.mtlsRenew.apply {
inherit pkgs;
inherit (cfg) certDir keyFile certFile bundleFile;
inherit (cfg.renew) user group reloadUnits postCommands;
systemd = {
description = "Renew the mTLS certificate when Smallstep marks it ready";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
User = cfg.renew.user;
Group = cfg.renew.group;
};
} // lib.optionalAttrs cfg.renew.enable {
startAt = cfg.renew.onCalendar;
};
};
in in
{ {
options.mtls = (mkOpts config) // { options.mtls = (mkOpts config) // {
@@ -291,30 +165,44 @@ in
inherit (cfg) subject provisioner san certFile keyFile bundleFile lifetime; inherit (cfg) subject provisioner san certFile keyFile bundleFile lifetime;
inherit (cfg.renew) user group; inherit (cfg.renew) user group;
}) })
(mkMtlsCheckScript { inherit pkgs; inherit (cfg) bundleFile; }) (inputs.self.wrappers.mtlsCheck.apply {
(mkMtlsRenewScript { inherit pkgs cfg; }) inherit pkgs;
inherit (cfg) bundleFile;
}).wrapper
mtlsRenewWrapper.wrapper
]; ];
systemd.tmpfiles.rules = [ systemd.tmpfiles.rules = [
"d ${cfg.certDir} 0750 ${cfg.renew.user} ${cfg.renew.group} -" "d ${cfg.certDir} 0750 ${cfg.renew.user} ${cfg.renew.group} -"
]; ];
systemd.services.mtls-renew = lib.mkIf cfg.renew.enable systemd.packages = lib.mkIf cfg.renew.enable [
(mkNixosMtlsRenewService { inherit pkgs cfg; }); mtlsRenewWrapper.outputs.systemd-system
];
systemd.timers.mtls-renew = lib.mkIf cfg.renew.enable (mkNixosMtlsRenewTimer { systemd.timers.mtls-renew = lib.mkIf cfg.renew.enable {
inherit (cfg.renew) onCalendar randomizedDelaySec; wantedBy = [ "timers.target" ];
}); timerConfig = {
Persistent = true;
AccuracySec = "1us";
RandomizedDelaySec = cfg.renew.randomizedDelaySec;
};
};
}; };
}; };
flake.modules.homeManager.mtls = { config, lib, pkgs, ... }: flake.modules.homeManager.mtls = { config, lib, pkgs, ... }:
let let
cfg = config.mtls; cfg = config.mtls;
keyFile = cfg.keyFile; mtlsRenewWrapper = inputs.self.wrappers.mtlsRenew.apply {
certFile = cfg.certFile; inherit pkgs;
bundleFile = cfg.bundleFile; inherit (cfg) certDir keyFile certFile bundleFile;
sanArgs = lib.concatMapStringsSep " " (san: "--san \"${san}\"") cfg.san; inherit (cfg.renew) reloadUnits postCommands;
systemctlArgs = [ "--user" ];
systemd = lib.optionalAttrs cfg.renew.enable {
startAt = cfg.renew.onCalendar;
};
};
in in
{ {
options.mtls = (mkOpts config) // { options.mtls = (mkOpts config) // {
@@ -329,24 +217,222 @@ in
home.packages = with pkgs; lib.optionals cfg.enable [ home.packages = with pkgs; lib.optionals cfg.enable [
# step-cli # step-cli
(mkMtlsGenerateScript { (mkMtlsGenerateScript {
inherit pkgs;
inherit (cfg) keyFile certFile bundleFile;
inherit (cfg) subject provisioner san lifetime; inherit (cfg) subject provisioner san lifetime;
inherit (cfg.renew) user group; inherit (cfg.renew) user group;
inherit pkgs certFile keyFile bundleFile;
}) })
(mkMtlsCheckScript { inherit pkgs bundleFile; }) (inputs.self.wrappers.mtlsCheck.apply {
(mkMtlsRenewScript { inherit pkgs cfg; systemctlArgs = [ "--user" ]; }) inherit pkgs;
inherit (cfg) bundleFile;
}).wrapper
]; ];
systemd.user.tmpfiles.rules = lib.mkIf cfg.enable [ systemd.user.tmpfiles.rules = lib.mkIf cfg.enable [
"d ${cfg.certDir} 0700 - - -" "d ${cfg.certDir} 0700 - - -" # Ensure the cert directory exists and is writable by the user
]; ];
systemd.user.services.mtls-renew = lib.mkIf cfg.renew.enable # Create the systemd service files for the user.
(mkHomeManagerMtlsRenewService { inherit pkgs cfg; }); xdg.dataFile = lib.mkIf cfg.renew.enable {
"systemd/user/mtls-renew.service".source =
"${mtlsRenewWrapper.outputs.systemd-user}/systemd/user/mtls-renew.service";
"systemd/user/mtls-renew.timer".source =
"${mtlsRenewWrapper.outputs.systemd-user}/systemd/user/mtls-renew.timer";
"systemd/user/mtls-renew.timer.d/override.conf".text = ''
[Timer]
Persistent=true
AccuracySec=1us
RandomizedDelaySec=${cfg.renew.randomizedDelaySec}
'';
};
systemd.user.timers.mtls-renew = lib.mkIf cfg.renew.enable (mkHomeManagerMtlsRenewTimer { # Ensure the timer gets started
inherit (cfg.renew) onCalendar randomizedDelaySec; home.activation.mtlsRenewTimer = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
}); if [ -n "$XDG_RUNTIME_DIR" ] && [ -S "$XDG_RUNTIME_DIR/systemd/private" ]; then
if [ "${lib.boolToString (cfg.enable && cfg.renew.enable)}" = "true" ]; then
run ${pkgs.systemd}/bin/systemctl --user daemon-reload
run ${pkgs.systemd}/bin/systemctl --user enable --now mtls-renew.timer
else
run ${pkgs.systemd}/bin/systemctl --user disable --now mtls-renew.timer || true
run ${pkgs.systemd}/bin/systemctl --user daemon-reload || true
fi
fi
'';
}; };
}; };
flake.wrappers = {
mtlsCheck = inputs.wrappers.lib.wrapModule ({ config, lib, wlib, ... }: {
options = {
bundleFile = lib.mkOption {
description = "String path for the mTLS key bundle";
type = lib.types.str;
};
};
config = {
binName = "mtls-check";
# This pattern is necessary to wrap packages like openssl that provide more than one binary
package = config.pkgs.symlinkJoin {
name = "openssl";
paths = [ config.pkgs.openssl.bin config.pkgs.openssl.man ];
meta.mainProgram = "openssl";
};
args = [
"x509"
"-noout"
"-in" config.bundleFile
"-subject"
"-issuer"
"-ext" "subjectAltName,extendedKeyUsage"
"-enddate"
];
};
});
mtlsNeedsRenewal = inputs.wrappers.lib.wrapModule ({ config, lib, wlib, ... }: {
options = {
certFile = lib.mkOption {
description = "String path for the public cert";
type = lib.types.str;
};
};
config = {
binName = "mtls-needs-renewal";
package = config.pkgs.step-cli;
preHook = ''
echo "Checking renewal status..."
'';
args = [ "certificate" "needs-renewal" "${config.certFile}" ];
};
});
mtlsRenew = inputs.wrappers.lib.wrapModule ({ config, lib, wlib, ... }: {
imports = [ wlib.modules.systemd ];
options = {
certDir = lib.mkOption {
description = "String path to the directory where the certs will be stored";
type = lib.types.str;
};
keyFile = lib.mkOption {
description = "String path for the private key";
type = lib.types.str;
default = "${config.certDir}/key.pem";
};
certFile = lib.mkOption {
description = "String path for the public cert";
type = lib.types.str;
default = "${config.certDir}/cert.pem";
};
bundleFile = lib.mkOption {
description = "String path for the mTLS key bundle";
type = lib.types.str;
default = "${config.certDir}/mtls.pem";
};
user = lib.mkOption {
description = "User that should own the renewed certificate files.";
type = lib.types.nullOr lib.types.str;
default = null;
};
group = lib.mkOption {
description = "Group that should own the renewed certificate files.";
type = lib.types.nullOr lib.types.str;
default = null;
};
reloadUnits = lib.mkOption {
description = "systemd units to try-reload-or-restart after a successful renewal.";
type = lib.types.listOf lib.types.str;
default = [ ];
};
postCommands = lib.mkOption {
description = "Shell commands to run after a successful renewal.";
type = lib.types.listOf lib.types.lines;
default = [ ];
};
systemctlArgs = lib.mkOption {
description = "Additional arguments to pass to systemctl when reloading units.";
type = lib.types.listOf lib.types.str;
default = [ ];
};
};
config = {
binName = "mtls-renew";
package = let
systemctlCmd = "systemctl ${lib.escapeShellArgs config.systemctlArgs}";
hasReloadUnits = config.reloadUnits != [ ];
renewReloadScript = lib.concatMapStringsSep "\n" (unit: ''
if ${systemctlCmd} --quiet is-active "${unit}"; then
${systemctlCmd} try-reload-or-restart "${unit}"
fi
'') config.reloadUnits;
hasPostCommands = config.postCommands != [ ];
renewPostCommands = lib.concatStringsSep "\n" config.postCommands;
hasOwnership = config.user != null && config.group != null;
in
config.pkgs.writeShellApplication {
name = "mtls-renew";
runtimeInputs = with config.pkgs; [ coreutils step-cli systemd ];
text = ''
set -euo pipefail
YELLOW_BANG="\e[33m!\e[0m"
force=0
while [[ $# -gt 0 ]]; do
case $1 in
--force)
force=1
shift
;;
*)
echo -e "$YELLOW_BANG Warning: ignoring unrecognized argument '$1'"
exit 1
;;
esac
done
if [[ $force -eq 0 ]] && ! step certificate needs-renewal "${config.certFile}"; then
echo "Skipping renew"
exit 0
fi
echo "Renewing mTLS certificate"
step ca renew --force "${config.certFile}" "${config.keyFile}"
(umask 077; cat "${config.certFile}" "${config.keyFile}" > "${config.bundleFile}")
${lib.optionalString hasOwnership ''
chown ${config.user}:${config.group} ${config.certFile} ${config.keyFile} ${config.bundleFile}
chmod 640 ${config.certFile} ${config.keyFile} ${config.bundleFile}
''}
${lib.optionalString hasReloadUnits ''
echo "Reloading units: ${lib.concatStringsSep ", " config.reloadUnits}"
${renewReloadScript}
''}
${lib.optionalString hasPostCommands ''
echo "Running post commands"
${renewPostCommands}
''}
'';
};
systemd = {
description = "Automatic mTLS renewal service";
documentation = [
"https://smallstep.com/docs/step-ca/certificate-authority-server-production"
];
startLimitIntervalSec = 0;
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig.Type = lib.mkDefault "oneshot";
};
};
});
};
} }
+33
View File
@@ -0,0 +1,33 @@
{ self, inputs, ... }:
let
packageName = "zed-editor";
zedWrapper = inputs.wrappers.lib.wrapModule ({ config, lib, wlib, ... }: {
options = {
text-to-say = lib.mkOption {
type = lib.types.str;
description = "Text for the ascii cow to say.";
};
};
config = {
binName = "my-pkg";
package = config.pkgs.cowsay;
args = [ config.text-to-say ];
};
});
in
{
perSystem = { system, pkgs, lib, ... }: {
packages."${packageName}" = (zedWrapper.apply {
inherit pkgs;
text-to-say = "Hello from wrapped module!";
}).wrapper;
};
flake.modules.homeManager."${packageName}" = { config, pkgs, lib, ... }: {
home.packages = [
inputs.self.packages.${pkgs.stdenv.hostPlatform.system}."${packageName}"
];
};
}