summary refs log tree commit diff
path: root/nixos/modules/services/misc/taskserver/default.nix
blob: 063002167cf582e50522488377f4d8ecd8f0587f (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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.services.taskserver;

  taskd = "${pkgs.taskserver}/bin/taskd";

  mkVal = val:
    if val == true then "true"
    else if val == false then "false"
    else if isList val then concatStringsSep ", " val
    else toString val;

  mkConfLine = key: val: let
    result = "${key} = ${mkVal val}";
  in optionalString (val != null && val != []) result;

  needToCreateCA = all isNull (with cfg.pki; [ key cert crl caCert ]);

  configFile = pkgs.writeText "taskdrc" ''
    # systemd related
    daemon = false
    log = -

    # logging
    ${mkConfLine "debug" cfg.debug}
    ${mkConfLine "ip.log" cfg.ipLog}

    # general
    ${mkConfLine "ciphers" cfg.ciphers}
    ${mkConfLine "confirmation" cfg.confirmation}
    ${mkConfLine "extensions" cfg.extensions}
    ${mkConfLine "queue.size" cfg.queueSize}
    ${mkConfLine "request.limit" cfg.requestLimit}

    # client
    ${mkConfLine "client.allow" cfg.allowedClientIDs}
    ${mkConfLine "client.deny" cfg.disallowedClientIDs}

    # server
    server = ${cfg.listenHost}:${toString cfg.listenPort}
    ${mkConfLine "server.crl" cfg.pki.crl}

    # certificates
    ${mkConfLine "trust" cfg.pki.trust}
    ${if needToCreateCA then ''
      ca.cert = ${cfg.dataDir}/keys/ca.cert
      server.cert = ${cfg.dataDir}/keys/server.cert
      server.key = ${cfg.dataDir}/keys/server.key
    '' else ''
      ca.cert = ${cfg.pki.caCert}
      server.cert = ${cfg.pki.cert}
      server.key = ${cfg.pki.key}
    ''}
  '';

  orgOptions = { name, ... }: {
    options.users = mkOption {
      type = types.uniq (types.listOf types.str);
      default = [];
      example = [ "alice" "bob" ];
      description = ''
        A list of user names that belong to the organization.
      '';
    };

    options.groups = mkOption {
      type = types.listOf types.str;
      default = [];
      example = [ "workers" "slackers" ];
      description = ''
        A list of group names that belong to the organization.
      '';
    };
  };

  mkShellStr = val: "'${replaceStrings ["'"] ["'\\''"] val}'";

  nixos-taskserver = pkgs.buildPythonPackage {
    name = "nixos-taskserver";
    namePrefix = "";

    src = pkgs.runCommand "nixos-taskserver-src" {} ''
      mkdir -p "$out"
      cat "${pkgs.substituteAll {
        src = ./helper-tool.py;
        certtool = "${pkgs.gnutls}/bin/certtool";
        inherit taskd;
        inherit (cfg) dataDir user group;
        inherit (cfg.pki) fqdn;
      }}" > "$out/main.py"
      cat > "$out/setup.py" <<EOF
      from setuptools import setup
      setup(name="nixos-taskserver",
            py_modules=["main"],
            install_requires=["Click"],
            entry_points="[console_scripts]\\nnixos-taskserver=main:cli")
      EOF
    '';

    propagatedBuildInputs = [ pkgs.pythonPackages.click ];
  };

  ctlcmd = "${nixos-taskserver}/bin/nixos-taskserver --service-helper";

  withMeta = meta: defs: mkMerge [ defs { inherit meta; } ];

in {

  options = {
    services.taskserver = {

      enable = mkEnableOption "the Taskwarrior server";

      user = mkOption {
        type = types.str;
        default = "taskd";
        description = "User for Taskserver.";
      };

      group = mkOption {
        type = types.str;
        default = "taskd";
        description = "Group for Taskserver.";
      };

      dataDir = mkOption {
        type = types.path;
        default = "/var/lib/taskserver";
        description = "Data directory for Taskserver.";
      };

      ciphers = mkOption {
        type = types.nullOr (types.separatedString ":");
        default = null;
        example = "NORMAL:-VERS-SSL3.0";
        description = let
          url = "https://gnutls.org/manual/html_node/Priority-Strings.html";
        in ''
          List of GnuTLS ciphers to use. See the GnuTLS documentation about
          priority strings at <link xlink:href="${url}"/> for full details.
        '';
      };

      organisations = mkOption {
        type = types.attrsOf (types.submodule orgOptions);
        default = {};
        example.myShinyOrganisation.users = [ "alice" "bob" ];
        example.myShinyOrganisation.groups = [ "staff" "outsiders" ];
        example.yetAnotherOrganisation.users = [ "foo" "bar" ];
        description = ''
          An attribute set where the keys name the organisation and the values
          are a set of lists of <option>users</option> and
          <option>groups</option>.
        '';
      };

      confirmation = mkOption {
        type = types.bool;
        default = true;
        description = ''
          Determines whether certain commands are confirmed.
        '';
      };

      debug = mkOption {
        type = types.bool;
        default = false;
        description = ''
          Logs debugging information.
        '';
      };

      extensions = mkOption {
        type = types.nullOr types.path;
        default = null;
        description = ''
          Fully qualified path of the Taskserver extension scripts.
          Currently there are none.
        '';
      };

      ipLog = mkOption {
        type = types.bool;
        default = false;
        description = ''
          Logs the IP addresses of incoming requests.
        '';
      };

      queueSize = mkOption {
        type = types.int;
        default = 10;
        description = ''
          Size of the connection backlog, see <citerefentry>
            <refentrytitle>listen</refentrytitle>
            <manvolnum>2</manvolnum>
          </citerefentry>.
        '';
      };

      requestLimit = mkOption {
        type = types.int;
        default = 1048576;
        description = ''
          Size limit of incoming requests, in bytes.
        '';
      };

      allowedClientIDs = mkOption {
        type = with types; loeOf (either (enum ["all" "none"]) str);
        default = [];
        example = [ "[Tt]ask [2-9]+" ];
        description = ''
          A list of regular expressions that are matched against the reported
          client id (such as <literal>task 2.3.0</literal>).

          The values <literal>all</literal> or <literal>none</literal> have
          special meaning. Overidden by any entry in the option
          <option>services.taskserver.client.deny</option>.
        '';
      };

      disallowedClientIDs = mkOption {
        type = with types; loeOf (either (enum ["all" "none"]) str);
        default = [];
        example = [ "[Tt]ask [2-9]+" ];
        description = ''
          A list of regular expressions that are matched against the reported
          client id (such as <literal>task 2.3.0</literal>).

          The values <literal>all</literal> or <literal>none</literal> have
          special meaning. Any entry here overrides these in
          <option>services.taskserver.client.allow</option>.
        '';
      };

      listenHost = mkOption {
        type = types.str;
        default = "localhost";
        description = ''
          The address (IPv4, IPv6 or DNS) to listen on.
        '';
      };

      listenPort = mkOption {
        type = types.int;
        default = 53589;
        description = ''
          Port number of the Taskserver.
        '';
      };

      pki = {
        fqdn = mkOption {
          type = types.str;
          default = "localhost";
          description = ''
            The fully qualified domain name of this server, which is used as the
            common name in the certificates.
          '';
        };

        cert = mkOption {
          type = types.nullOr types.path;
          default = null;
          description = "Fully qualified path to the server certificate";
        };

        caCert = mkOption {
          type = types.nullOr types.path;
          default = null;
          description = "Fully qualified path to the CA certificate.";
        };

        crl = mkOption {
          type = types.nullOr types.path;
          default = null;
          description = ''
            Fully qualified path to the server certificate revocation list.
          '';
        };

        key = mkOption {
          type = types.nullOr types.path;
          default = null;
          description = ''
            Fully qualified path to the server key.

            Note that reloading the <literal>taskserver.service</literal> causes
            a configuration file reload before the next request is handled.
          '';
        };

        trust = mkOption {
          type = types.enum [ "allow all" "strict" ];
          default = "strict";
          description = ''
            Determines how client certificates are validated.

            The value <literal>allow all</literal> performs no client
            certificate validation. This is not recommended. The value
            <literal>strict</literal> causes the client certificate to be
            validated against a CA.
          '';
        };
      };
    };
  };

  config = withMeta {
    doc = ./taskserver.xml;
  } (mkIf cfg.enable {

    environment.systemPackages = [ pkgs.taskserver nixos-taskserver ];

    users.users = optional (cfg.user == "taskd") {
      name = "taskd";
      uid = config.ids.uids.taskd;
      description = "Taskserver user";
      group = cfg.group;
    };

    users.groups = optional (cfg.group == "taskd") {
      name = "taskd";
      gid = config.ids.gids.taskd;
    };

    systemd.services.taskserver-ca = mkIf needToCreateCA {
      requiredBy = [ "taskserver.service" ];
      after = [ "taskserver-init.service" ];
      description = "Initialize CA for TaskServer";
      serviceConfig.Type = "oneshot";
      serviceConfig.UMask = "0077";

      script = ''
        mkdir -m 0700 -p "${cfg.dataDir}/keys"
        chown root:root "${cfg.dataDir}/keys"

        if [ ! -e "${cfg.dataDir}/keys/ca.key" ]; then
          ${pkgs.gnutls}/bin/certtool -p \
            --bits 2048 \
            --outfile "${cfg.dataDir}/keys/ca.key"
          ${pkgs.gnutls}/bin/certtool -s \
            --template "${pkgs.writeText "taskserver-ca.template" ''
              cn = ${cfg.pki.fqdn}
              cert_signing_key
              ca
            ''}" \
            --load-privkey "${cfg.dataDir}/keys/ca.key" \
            --outfile "${cfg.dataDir}/keys/ca.cert"

          chgrp "${cfg.group}" "${cfg.dataDir}/keys/ca.cert"
          chmod g+r "${cfg.dataDir}/keys/ca.cert"
        fi

        if [ ! -e "${cfg.dataDir}/keys/server.key" ]; then
          ${pkgs.gnutls}/bin/certtool -p \
            --bits 2048 \
            --outfile "${cfg.dataDir}/keys/server.key"

          ${pkgs.gnutls}/bin/certtool -c \
            --template "${pkgs.writeText "taskserver-cert.template" ''
              cn = ${cfg.pki.fqdn}
              tls_www_server
              encryption_key
              signing_key
            ''}" \
            --load-ca-privkey "${cfg.dataDir}/keys/ca.key" \
            --load-ca-certificate "${cfg.dataDir}/keys/ca.cert" \
            --load-privkey "${cfg.dataDir}/keys/server.key" \
            --outfile "${cfg.dataDir}/keys/server.cert"

          chgrp "${cfg.group}" "${cfg.dataDir}/keys/server.key"
          chmod g+r "${cfg.dataDir}/keys/server.key"
          chmod a+r "${cfg.dataDir}/keys/server.cert"
        fi

        chmod go+x "${cfg.dataDir}/keys"
      '';
    };

    systemd.services.taskserver-init = {
      requiredBy = [ "taskserver.service" ];
      description = "Initialize Taskserver Data Directory";

      preStart = ''
        mkdir -m 0770 -p "${cfg.dataDir}"
        chown "${cfg.user}:${cfg.group}" "${cfg.dataDir}"
      '';

      script = ''
        ${taskd} init
        echo "include ${configFile}" > "${cfg.dataDir}/config"
        touch "${cfg.dataDir}/.is_initialized"
      '';

      environment.TASKDDATA = cfg.dataDir;

      unitConfig.ConditionPathExists = "!${cfg.dataDir}/.is_initialized";

      serviceConfig.Type = "oneshot";
      serviceConfig.User = cfg.user;
      serviceConfig.Group = cfg.group;
      serviceConfig.PermissionsStartOnly = true;
    };

    systemd.services.taskserver = {
      description = "Taskwarrior Server";

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

      environment.TASKDDATA = cfg.dataDir;

      preStart = ''
        ${concatStrings (mapAttrsToList (orgName: attrs: ''
          ${ctlcmd} add-org ${mkShellStr orgName}

          ${concatMapStrings (user: ''
            echo Creating ${user} >&2
            ${ctlcmd} add-user ${mkShellStr orgName} ${mkShellStr user}
          '') attrs.users}

          ${concatMapStrings (group: ''
            ${ctlcmd} add-group ${mkShellStr orgName} ${mkShellStr user}
          '') attrs.groups}
        '') cfg.organisations)}
      '';

      serviceConfig = {
        ExecStart = "@${taskd} taskd server";
        PermissionsStartOnly = true;
        User = cfg.user;
        Group = cfg.group;
      };
    };
  });
}