summaryrefslogtreecommitdiff
path: root/services/mail2.nix
blob: b8e24cfb9dd32783eb86e9b47c51c9042df91afc (plain)
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
{
  config,
  lib,
  ...
}:
let
  cfg = config.wilkuu.services.mail;
  hostname = config.networking.hostName;
in
{
  options.wilkuu.services.mail = with lib; {
    enable = mkEnableOption "Enable webmail";
    doACME = mkEnableOption "Enable ACME for stalwart here";
    defaultDomain = mkOption {
      type = lib.types.str;
      default = "mail.${hostname}.local";
      example = "mail.wilkuu.xyz";
      description = "Domain for http connections.";
    };
    domains = mkOption {
      type = types.listOf types.str;
      default = [ ];
      example = [ "mail.wilkuu.xyz" ];
      description = "Domains for email.";
    };
    wellKnownDomains = mkOption {
      type = types.listOf types.str;
      default = [ "${hostname}.local" ];
      example = [ "wilkuu.xyz" ];
      description = "Domain for well-known items";
    };
    extraConfig = mkOption {
      type = types.listOf types.attrs;
      description = "Additional plan steps added to the stalwart config";
      default = [ ];
      example = [ ];
    };
    extraCreate = mkOption {
      type = types.listOf types.attrs;
      description = "Additional idempotent create steps added to the stalwart config";
      default = [ ];
      example = [ ];
    };

    startupMode = mkOption {
      type = types.enum [
        "normal"
        "bootstrap"
        "recovery"
      ];
      description = "Whenever to use the bootstrap or recovery mode, see https://stalw.art/docs/configuration/bootstrap-mode/ and https://stalw.art/docs/configuration/recovery-mode/";
      default = "normal";
      example = "bootstrap";
    };

  };

  config = lib.mkIf cfg.enable (
    let
      sopsPath = ../secrets/${hostname}/stalwart.yaml;
      secrets = [
        "admin_user"
        "admin_password"
        "recovery_user"
        "recovery_password"
        "oidc_secret"
      ];
      toSops = (sname: "stalwart16/${sname}");
      toPlaceholder = (sname: config.sops.placeholder.${toSops sname});
      toCredfilePath = (name: config.sops.secrets.${toSops name}.path);

      # We do this to satisfy the foreign key constraint of the SystemSettings singleton
      proxyWellKnown =
        names:
        let
          uris = map (n: "/.well-known/${n}") names;
        in
        (lib.genAttrs uris (uri: {
          proxyPass = "http://127.0.0.1:8080${uri}";
          recommendedProxySettings = true;
        }));
      makeHTTPRedirectBody = target: https: "302 ${if https then "https" else "http"}://${target}";

    in
    {
      users.users.stalwart = {
        isSystemUser = true;
        group = "stalwart";
      };
      users.groups.stalwart = { };
      sops.secrets = (
        lib.genAttrs (map toSops secrets) (_name: {
          sopsFile = sopsPath;
          mode = "0440";
          owner = "stalwart";
        })
      );

      sops.templates = {
        stalwart-config-creds = {
          owner = "stalwart";
          mode = "0440";
          content = ''
            STALWART_USER=${toPlaceholder "admin_user"}
            STALWART_PASSWORD=${toPlaceholder "admin_password"}
          '';
        };
        stalwart-recovery-creds = {
          owner = "stalwart";
          mode = "0440";
          content = ''
            STALWART_RECOVERY_ADMIN=${toPlaceholder "recovery_user"}:${toPlaceholder "recovery_password"}
          '';
        };
      };

      security.acme.certs.${cfg.defaultDomain}.extraLegoRenewFlags = [
        "--reuse-key"
      ];
      services.nginx.enable = lib.mkDefault true;
      services.nginx.virtualHosts =
        (lib.genAttrs
          (lib.concatLists [
            cfg.wellKnownDomains
            cfg.domains
            [ cfg.defaultDomain ]
          ])
          (_wdomain: {
            forceSSL = lib.mkDefault cfg.doACME;
            enableACME = lib.mkDefault cfg.doACME;
            locations =
              (proxyWellKnown [
                "mta-sts.txt"
                "mail-v1.xml"
                "autoconfig/mail"
                "openid-configuration"
                "oauth-authorization-server"
              ])
              // (lib.genAttrs [ "/.well-known/caldav/" "/.well-known/webdav/" "/.well-known/jmap" ] (uri: {
                extraConfig = ''
                  	return ${makeHTTPRedirectBody "${cfg.defaultDomain}${uri}" cfg.doACME};
                '';
              }));

          })
        )
        // (lib.genAttrs [ cfg.defaultDomain ] (_domain: {
          forceSSL = cfg.doACME;
          enableACME = cfg.doACME;
          #serverName = "${domain}";
          locations."/" = {
            proxyPass = "http://127.0.0.1:8080";
            proxyWebsockets = true;
            recommendedProxySettings = true;
          };
        }));

      stalwart-nix.stalwart = {
        enable = cfg.enable;
        url =
          if cfg.startupMode != "normal" then "http://127.0.0.1:8080/" else "http://${cfg.defaultDomain}";
        credentialsFile = config.sops.templates.stalwart-config-creds.path;
        recoveryCredentialsFile = config.sops.templates.stalwart-recovery-creds.path;
        startupMode = cfg.startupMode;
        user = "stalwart";
        group = "stalwart";
        configPlanPre = [ ];
        idempotentCreate = cfg.extraCreate;
        configPlanPost = cfg.extraConfig;
        useMimalloc = true;
        credentials =
          (lib.genAttrs secrets toCredfilePath)
          // (builtins.foldl' (a: b: a // b) ({ }) (
            map (
              domain:
              let
                acme_dir = config.security.acme.certs.${domain}.directory;
                cert_path = file: "${acme_dir}/${file}";
              in
              {
                "tls_${domain}_cert.pem" = cert_path "cert.pem";
                "tls_${domain}_key.pem" = cert_path "key.pem";
              }
            ) (lib.optionals cfg.doACME (lib.unique ([ cfg.defaultDomain ] ++ cfg.domains)))
          ));
      };
    }
  );

}