summary refs log tree commit diff
path: root/nixos/modules/services/mail/rspamd.nix
blob: aacdbe2aeed257feb882a057be1dc77e0122abf6 (plain) (blame)
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
{ config, options, pkgs, lib, ... }:

with lib;

let

  cfg = config.services.rspamd;
  postfixCfg = config.services.postfix;

  bindSocketOpts = {options, config, ... }: {
    options = {
      socket = mkOption {
        type = types.str;
        example = "localhost:11333";
        description = ''
          Socket for this worker to listen on in a format acceptable by rspamd.
        '';
      };
      mode = mkOption {
        type = types.str;
        default = "0644";
        description = "Mode to set on unix socket";
      };
      owner = mkOption {
        type = types.str;
        default = "${cfg.user}";
        description = "Owner to set on unix socket";
      };
      group = mkOption {
        type = types.str;
        default = "${cfg.group}";
        description = "Group to set on unix socket";
      };
      rawEntry = mkOption {
        type = types.str;
        internal = true;
      };
    };
    config.rawEntry = let
      maybeOption = option:
        optionalString options.${option}.isDefined " ${option}=${config.${option}}";
    in
      if (!(hasPrefix "/" config.socket)) then "${config.socket}"
      else "${config.socket}${maybeOption "mode"}${maybeOption "owner"}${maybeOption "group"}";
  };

  traceWarning = w: x: builtins.trace "warning: ${w}" x;

  workerOpts = { name, options, ... }: {
    options = {
      enable = mkOption {
        type = types.nullOr types.bool;
        default = null;
        description = "Whether to run the rspamd worker.";
      };
      name = mkOption {
        type = types.nullOr types.str;
        default = name;
        description = "Name of the worker";
      };
      type = mkOption {
        type = types.nullOr (types.enum [
          "normal" "controller" "fuzzy" "rspamd_proxy" "lua" "proxy"
        ]);
        description = ''
          The type of this worker. The type <literal>proxy</literal> is
          deprecated and only kept for backwards compatibility and should be
          replaced with <literal>rspamd_proxy</literal>.
        '';
        apply = let
            from = "services.rspamd.workers.\"${name}\".type";
            files = options.type.files;
            warning = "The option `${from}` defined in ${showFiles files} has enum value `proxy` which has been renamed to `rspamd_proxy`";
          in x: if x == "proxy" then traceWarning warning "rspamd_proxy" else x;
      };
      bindSockets = mkOption {
        type = types.listOf (types.either types.str (types.submodule bindSocketOpts));
        default = [];
        description = ''
          List of sockets to listen, in format acceptable by rspamd
        '';
        example = [{
          socket = "/run/rspamd.sock";
          mode = "0666";
          owner = "rspamd";
        } "*:11333"];
        apply = value: map (each: if (isString each)
          then if (isUnixSocket each)
            then {socket = each; owner = cfg.user; group = cfg.group; mode = "0644"; rawEntry = "${each}";}
            else {socket = each; rawEntry = "${each}";}
          else each) value;
      };
      count = mkOption {
        type = types.nullOr types.int;
        default = null;
        description = ''
          Number of worker instances to run
        '';
      };
      includes = mkOption {
        type = types.listOf types.str;
        default = [];
        description = ''
          List of files to include in configuration
        '';
      };
      extraConfig = mkOption {
        type = types.lines;
        default = "";
        description = "Additional entries to put verbatim into worker section of rspamd config file.";
      };
    };
    config = mkIf (name == "normal" || name == "controller" || name == "fuzzy" || name == "rspamd_proxy") {
      type = mkDefault name;
      includes = mkDefault [ "$CONFDIR/worker-${if name == "rspamd_proxy" then "proxy" else name}.inc" ];
      bindSockets =
        let
          unixSocket = name: {
            mode = "0660";
            socket = "/run/rspamd/${name}.sock";
            owner = cfg.user;
            group = cfg.group;
          };
        in mkDefault (if name == "normal" then [(unixSocket "rspamd")]
          else if name == "controller" then [ "localhost:11334" ]
          else if name == "rspamd_proxy" then [ (unixSocket "proxy") ]
          else [] );
    };
  };

  isUnixSocket = socket: hasPrefix "/" (if (isString socket) then socket else socket.socket);

  mkBindSockets = enabled: socks: concatStringsSep "\n  "
    (flatten (map (each: "bind_socket = \"${each.rawEntry}\";") socks));

  rspamdConfFile = pkgs.writeText "rspamd.conf"
    ''
      .include "$CONFDIR/common.conf"

      options {
        pidfile = "$RUNDIR/rspamd.pid";
        .include "$CONFDIR/options.inc"
        .include(try=true; priority=1,duplicate=merge) "$LOCAL_CONFDIR/local.d/options.inc"
        .include(try=true; priority=10) "$LOCAL_CONFDIR/override.d/options.inc"
      }

      logging {
        type = "syslog";
        .include "$CONFDIR/logging.inc"
        .include(try=true; priority=1,duplicate=merge) "$LOCAL_CONFDIR/local.d/logging.inc"
        .include(try=true; priority=10) "$LOCAL_CONFDIR/override.d/logging.inc"
      }

      ${concatStringsSep "\n" (mapAttrsToList (name: value: let
          includeName = if name == "rspamd_proxy" then "proxy" else name;
          tryOverride = if value.extraConfig == "" then "true" else "false";
        in ''
        worker "${value.type}" {
          type = "${value.type}";
          ${optionalString (value.enable != null)
            "enabled = ${if value.enable != false then "yes" else "no"};"}
          ${mkBindSockets value.enable value.bindSockets}
          ${optionalString (value.count != null) "count = ${toString value.count};"}
          ${concatStringsSep "\n  " (map (each: ".include \"${each}\"") value.includes)}
          .include(try=true; priority=1,duplicate=merge) "$LOCAL_CONFDIR/local.d/worker-${includeName}.inc"
          .include(try=${tryOverride}; priority=10) "$LOCAL_CONFDIR/override.d/worker-${includeName}.inc"
        }
      '') cfg.workers)}

      ${optionalString (cfg.extraConfig != "") ''
        .include(priority=10) "$LOCAL_CONFDIR/override.d/extra-config.inc"
      ''}
   '';

  filterFiles = files: filterAttrs (n: v: v.enable) files;
  rspamdDir = pkgs.linkFarm "etc-rspamd-dir" (
    (mapAttrsToList (name: file: { name = "local.d/${name}"; path = file.source; }) (filterFiles cfg.locals)) ++
    (mapAttrsToList (name: file: { name = "override.d/${name}"; path = file.source; }) (filterFiles cfg.overrides)) ++
    (optional (cfg.localLuaRules != null) { name = "rspamd.local.lua"; path = cfg.localLuaRules; }) ++
    [ { name = "rspamd.conf"; path = rspamdConfFile; } ]
  );

  configFileModule = prefix: { name, config, ... }: {
    options = {
      enable = mkOption {
        type = types.bool;
        default = true;
        description = ''
          Whether this file ${prefix} should be generated.  This
          option allows specific ${prefix} files to be disabled.
        '';
      };

      text = mkOption {
        default = null;
        type = types.nullOr types.lines;
        description = "Text of the file.";
      };

      source = mkOption {
        type = types.path;
        description = "Path of the source file.";
      };
    };
    config = {
      source = mkIf (config.text != null) (
        let name' = "rspamd-${prefix}-" + baseNameOf name;
        in mkDefault (pkgs.writeText name' config.text));
    };
  };

  configOverrides =
    (mapAttrs' (n: v: nameValuePair "worker-${if n == "rspamd_proxy" then "proxy" else n}.inc" {
      text = v.extraConfig;
    })
    (filterAttrs (n: v: v.extraConfig != "") cfg.workers))
    // (if cfg.extraConfig == "" then {} else {
      "extra-config.inc".text = cfg.extraConfig;
    });
in

{
  ###### interface

  options = {

    services.rspamd = {

      enable = mkEnableOption "rspamd, the Rapid spam filtering system";

      debug = mkOption {
        type = types.bool;
        default = false;
        description = "Whether to run the rspamd daemon in debug mode.";
      };

      locals = mkOption {
        type = with types; attrsOf (submodule (configFileModule "locals"));
        default = {};
        description = ''
          Local configuration files, written into <filename>/etc/rspamd/local.d/{name}</filename>.
        '';
        example = literalExample ''
          { "redis.conf".source = "/nix/store/.../etc/dir/redis.conf";
            "arc.conf".text = "allow_envfrom_empty = true;";
          }
        '';
      };

      overrides = mkOption {
        type = with types; attrsOf (submodule (configFileModule "overrides"));
        default = {};
        description = ''
          Overridden configuration files, written into <filename>/etc/rspamd/override.d/{name}</filename>.
        '';
        example = literalExample ''
          { "redis.conf".source = "/nix/store/.../etc/dir/redis.conf";
            "arc.conf".text = "allow_envfrom_empty = true;";
          }
        '';
      };

      localLuaRules = mkOption {
        default = null;
        type = types.nullOr types.path;
        description = ''
          Path of file to link to <filename>/etc/rspamd/rspamd.local.lua</filename> for local
          rules written in Lua
        '';
      };

      workers = mkOption {
        type = with types; attrsOf (submodule workerOpts);
        description = ''
          Attribute set of workers to start.
        '';
        default = {
          normal = {};
          controller = {};
        };
        example = literalExample ''
          {
            normal = {
              includes = [ "$CONFDIR/worker-normal.inc" ];
              bindSockets = [{
                socket = "/run/rspamd/rspamd.sock";
                mode = "0660";
                owner = "${cfg.user}";
                group = "${cfg.group}";
              }];
            };
            controller = {
              includes = [ "$CONFDIR/worker-controller.inc" ];
              bindSockets = [ "[::1]:11334" ];
            };
          }
        '';
      };

      extraConfig = mkOption {
        type = types.lines;
        default = "";
        description = ''
          Extra configuration to add at the end of the rspamd configuration
          file.
        '';
      };

      user = mkOption {
        type = types.str;
        default = "rspamd";
        description = ''
          User to use when no root privileges are required.
        '';
      };

      group = mkOption {
        type = types.str;
        default = "rspamd";
        description = ''
          Group to use when no root privileges are required.
        '';
      };

      postfix = {
        enable = mkOption {
          type = types.bool;
          default = false;
          description = "Add rspamd milter to postfix main.conf";
        };

        config = mkOption {
          type = with types; attrsOf (oneOf [ bool str (listOf str) ]);
          description = ''
            Addon to postfix configuration
          '';
          default = {
            smtpd_milters = ["unix:/run/rspamd/rspamd-milter.sock"];
            non_smtpd_milters = ["unix:/run/rspamd/rspamd-milter.sock"];
          };
          example = {
            smtpd_milters = ["unix:/run/rspamd/rspamd-milter.sock"];
            non_smtpd_milters = ["unix:/run/rspamd/rspamd-milter.sock"];
          };
        };
      };
    };
  };


  ###### implementation

  config = mkIf cfg.enable {
    services.rspamd.overrides = configOverrides;
    services.rspamd.workers = mkIf cfg.postfix.enable {
      controller = {};
      rspamd_proxy = {
        bindSockets = [ {
          mode = "0660";
          socket = "/run/rspamd/rspamd-milter.sock";
          owner = cfg.user;
          group = postfixCfg.group;
        } ];
        extraConfig = ''
          upstream "local" {
            default = yes; # Self-scan upstreams are always default
            self_scan = yes; # Enable self-scan
          }
        '';
      };
    };
    services.postfix.config = mkIf cfg.postfix.enable cfg.postfix.config;

    # Allow users to run 'rspamc' and 'rspamadm'.
    environment.systemPackages = [ pkgs.rspamd ];

    users.users.${cfg.user} = {
      description = "rspamd daemon";
      uid = config.ids.uids.rspamd;
      group = cfg.group;
    };

    users.groups.${cfg.group} = {
      gid = config.ids.gids.rspamd;
    };

    environment.etc.rspamd.source = rspamdDir;

    systemd.services.rspamd = {
      description = "Rspamd Service";

      wantedBy = [ "multi-user.target" ];
      after = [ "network.target" ];
      restartTriggers = [ rspamdDir ];

      serviceConfig = {
        ExecStart = "${pkgs.rspamd}/bin/rspamd ${optionalString cfg.debug "-d"} --user=${cfg.user} --group=${cfg.group} --pid=/run/rspamd.pid -c /etc/rspamd/rspamd.conf -f";
        Restart = "always";
        RuntimeDirectory = "rspamd";
        PrivateTmp = true;
      };

      preStart = ''
        ${pkgs.coreutils}/bin/mkdir -p /var/lib/rspamd
        ${pkgs.coreutils}/bin/chown ${cfg.user}:${cfg.group} /var/lib/rspamd
      '';
    };
  };
  imports = [
    (mkRemovedOptionModule [ "services" "rspamd" "socketActivation" ]
	     "Socket activation never worked correctly and could at this time not be fixed and so was removed")
    (mkRenamedOptionModule [ "services" "rspamd" "bindSocket" ] [ "services" "rspamd" "workers" "normal" "bindSockets" ])
    (mkRenamedOptionModule [ "services" "rspamd" "bindUISocket" ] [ "services" "rspamd" "workers" "controller" "bindSockets" ])
    (mkRemovedOptionModule [ "services" "rmilter" ] "Use services.rspamd.* instead to set up milter service")
  ];
}