system/nixos/hosts/magenta/services/mailserver.nix

73 lines
2.1 KiB
Nix
Raw Normal View History

{ config, pkgs, ... }:
2022-10-18 00:42:23 +03:00
let
cfg = config.mailserver;
certsDir = "/var/certs";
2023-04-23 09:58:51 +03:00
# Extracting a Certificate from Traefik`s acme.json
# Source: https://www.zdyn.net/docker/2022/02/04/acme-certificate.html
dumpTraefikMailCerts = pkgs.writeScript "dump-mail-certs" ''
#!/bin/sh
2023-06-05 13:56:10 +03:00
mkdir -p $(dirname "${cfg.certificateFile}") $(dirname "${cfg.keyFile}")
${pkgs.jq}/bin/jq -r '.le.Certificates[] | select(.domain.main=="${cfg.fqdn}") | .certificate' /var/lib/traefik/acme.json | base64 -d > ${cfg.certificateFile}
${pkgs.jq}/bin/jq -r '.le.Certificates[] | select(.domain.main=="${cfg.fqdn}") | .key' /var/lib/traefik/acme.json | base64 -d > ${cfg.keyFile}
'';
in
2022-10-18 00:42:23 +03:00
{
2022-10-19 19:17:37 +03:00
imports = [ ./mailserver-accounts.secret.nix ];
2022-10-18 00:42:23 +03:00
# See: https://nixos-mailserver.readthedocs.io/en/latest/options.html
mailserver = {
enable = true;
# We use traefik to generate certificates
certificateScheme = 1;
certificateFile = "${certsDir}/cert-${cfg.fqdn}.pem";
keyFile = "${certsDir}/key-${cfg.fqdn}.pem";
2022-10-18 00:42:23 +03:00
hierarchySeparator = "/";
};
2023-03-04 23:22:03 +03:00
services.traefik.dynamicConfigOptions.http = {
routers.mailserver_acme = {
rule = "Host(`${cfg.fqdn}`)";
entryPoints = [ "http" ];
tls = {
certResolver = "le";
domains = [
{
main = cfg.fqdn;
sans = cfg.domains;
}
];
};
service = "noop@internal";
};
2023-03-04 23:22:03 +03:00
};
systemd = {
2023-04-23 09:58:51 +03:00
# Watch traefik`s acme.json to update certs in /var/certs
# Source: https://superuser.com/questions/1171751/restart-systemd-service-automatically-whenever-a-directory-changes-any-file-ins
services.dump-traefik-mail-cert = {
unitConfig = {
Description = "Restart mail cert service";
After = [ "network.target" ];
};
serviceConfig = {
Type = "oneshot";
ExecStart = "${dumpTraefikMailCerts}";
};
wantedBy = [ "multi-user.target" ];
};
paths.dump-traefik-mail-cert = {
wantedBy = [ "multi-user.target" ];
pathConfig.PathChanged = "/var/lib/traefik/acme.json";
};
};
2022-10-18 00:42:23 +03:00
}