diff --git a/nixos/hosts/magenta/services/mailserver.nix b/nixos/hosts/magenta/services/mailserver.nix index 2dfc239..c2082da 100644 --- a/nixos/hosts/magenta/services/mailserver.nix +++ b/nixos/hosts/magenta/services/mailserver.nix @@ -1,5 +1,17 @@ -{ ... }: +{ config, pkgs, ... }: +let + cfg = config.mailserver; + + certsDir = "/var/certs"; + + dumpTraefikMailCerts = pkgs.writeScript "dump-mail-certs" '' + #!/bin/sh + ${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 { imports = [ ./mailserver-accounts.secret.nix ]; @@ -9,17 +21,52 @@ fqdn = "mail.pleshevski.ru"; domains = [ "pleshevski.ru" ]; - # Use Let's Encrypt certificates. Note that this needs to set up a stripped - # down nginx and opens port 80. - certificateScheme = 3; + # We use traefik to generate certificates + certificateScheme = 1; + certificateFile = "${certsDir}/cert-${cfg.fqdn}.pem"; + keyFile = "${certsDir}/key-${cfg.fqdn}.pem"; hierarchySeparator = "/"; }; - # required for certificateScheme = 3 - # TODO: Try to use traefik - services.nginx = { - defaultHTTPListenPort = 10080; - defaultSSLListenPort = 10443; + 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"; + }; }; + + systemd = { + 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"; + }; + }; + + }