aboutsummaryrefslogtreecommitdiff
path: root/systems/eldiron/tasks/default.nix
blob: 0772a5fd2727e07194ce80937285f9a8536828a2 (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
{ lib, pkgs, config, taskwarrior-web, ... }:
let
  cfg = config.myServices.tasks;
  server_vardir = config.services.taskserver.dataDir;
  fqdn = "task.immae.eu";
  user = config.services.taskserver.user;
  env = config.myEnv.tools.task;
  group = config.services.taskserver.group;
  taskserver-user-certs = pkgs.runCommand "taskserver-user-certs" {} ''
    mkdir -p $out/bin
    cat > $out/bin/taskserver-user-certs <<"EOF"
    #!/usr/bin/env bash

    user=$1

    silent_certtool() {
      if ! output="$("${pkgs.gnutls.bin}/bin/certtool" "$@" 2>&1)"; then
        echo "GNUTLS certtool invocation failed with output:" >&2
        echo "$output" >&2
      fi
    }

    silent_certtool -p \
      --bits 4096 \
      --outfile "${server_vardir}/userkeys/$user.key.pem"
    ${pkgs.gnused}/bin/sed -i -n -e '/^-----BEGIN RSA PRIVATE KEY-----$/,$p' "${server_vardir}/userkeys/$user.key.pem"

    silent_certtool -c \
      --template "${pkgs.writeText "taskserver-ca.template" ''
        tls_www_client
        encryption_key
        signing_key
        expiration_days = 3650
      ''}" \
      --load-ca-certificate "${server_vardir}/keys/ca.cert" \
      --load-ca-privkey "${server_vardir}/keys/ca.key" \
      --load-privkey "${server_vardir}/userkeys/$user.key.pem" \
      --outfile "${server_vardir}/userkeys/$user.cert.pem"
    EOF
    chmod a+x $out/bin/taskserver-user-certs
    patchShebangs $out/bin/taskserver-user-certs
    '';
  socketsDir = "/run/taskwarrior-web";
  varDir = "/var/lib/taskwarrior-web";
  taskwebPages = let
    uidPages = lib.attrsets.zipAttrs (
      lib.lists.flatten
        (lib.attrsets.mapAttrsToList (k: c: map (v: { "${v}" = k; }) c.uid) env.taskwarrior-web)
      );
    pages = lib.attrsets.mapAttrs (uid: items:
      if lib.lists.length items == 1 then
      ''
        <html>
        <head>
          <meta http-equiv="refresh" content="0; url=/taskweb/${lib.lists.head items}/" />
        </head>
        <body></body>
        </html>
        ''
      else
      ''
        <html>
        <head>
        <title>To-do list disponibles</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        </head>
        <body>
          <ul>
            ${builtins.concatStringsSep "\n" (map (item: "<li><a href='/taskweb/${item}'>${item}</a></li>") items)}
          </ul>
        </body>
        </html>
        ''
    ) uidPages;
  in
    pkgs.runCommand "taskwerver-pages" {} ''
      mkdir -p $out/
      ${builtins.concatStringsSep "\n" (lib.attrsets.mapAttrsToList (k: v: "cp ${pkgs.writeText k v} $out/${k}.html") pages)}
      echo "Please login" > $out/index.html
      '';
in {
  options.myServices.tasks = {
    enable = lib.mkEnableOption "my tasks service";
  };

  config = lib.mkIf cfg.enable {
    myServices.dns.zones."immae.eu".subdomains.task =
      with config.myServices.dns.helpers; ips servers.eldiron.ips.main;

    myServices.chatonsProperties.services.taskwarrior = {
      file.datetime = "2022-08-22T00:00:00";
      service = {
        name = "Taskwarrior";
        description = "Taskwarrior is Free and Open Source Software that manages your TODO list from the command line. Web interface and synchronization server";
        website = "https://task.immae.eu/";
        logo = "https://taskwarrior.org/favicon.ico";
        status.level = "OK";
        status.description = "OK";
        registration."" = ["MEMBER" "CLIENT"];
        registration.load = "OPEN";
        install.type = "PACKAGE";
      };
      software = {
        name = "Taskwarrior";
        website = "https://taskwarrior.org/";
        license.url = "https://github.com/GothenburgBitFactory/taskwarrior/blob/develop/LICENSE";
        license.name = "MIT License";
        version = taskwarrior-web.version;
        source.url = "https://taskwarrior.org/download/";
      };
    };
    secrets.keys = {
      "webapps/tools-taskwarrior-web" = {
        user = "wwwrun";
        group = "wwwrun";
        permissions = "0400";
        text = ''
            SetEnv TASKD_HOST          "${fqdn}:${toString config.services.taskserver.listenPort}"
            SetEnv TASKD_VARDIR        "${server_vardir}"
            SetEnv TASKD_LDAP_HOST     "ldaps://${env.ldap.host}"
            SetEnv TASKD_LDAP_DN       "${env.ldap.dn}"
            SetEnv TASKD_LDAP_PASSWORD "${env.ldap.password}"
            SetEnv TASKD_LDAP_BASE     "${env.ldap.base}"
            SetEnv TASKD_LDAP_FILTER   "${env.ldap.filter}"
          '';
      };
    } // (lib.mapAttrs' (name: userConfig: lib.nameValuePair "webapps/tools-taskwarrior/${name}-taskrc" (
      let
        credentials = "${userConfig.org}/${name}/${userConfig.key}";
        dateFormat = userConfig.date;
        cacert = pkgs.writeText "ca.cert" ''
          -----BEGIN CERTIFICATE-----
          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
          -----END CERTIFICATE-----'';
      in {
      inherit user group;
      permissions = "0400";
      text = ''
        data.location=${varDir}/${name}
        taskd.certificate=${server_vardir}/userkeys/taskwarrior-web.cert.pem
        taskd.key=${server_vardir}/userkeys/taskwarrior-web.key.pem
        # IdenTrust DST Root CA X3
        # obtained here: https://letsencrypt.org/fr/certificates/
        taskd.ca=${cacert}
        taskd.server=${fqdn}:${toString config.services.taskserver.listenPort}
        taskd.credentials=${credentials}
        dateformat=${dateFormat}
      '';
      keyDependencies = [ cacert ];
    })) env.taskwarrior-web);
    security.acme.certs.eldiron.extraDomainNames = [ "task.immae.eu" ];
    services.websites.env.tools.watchPaths = [ config.secrets.fullPaths."webapps/tools-taskwarrior-web" ];
    services.websites.env.tools.modules = [ "proxy_fcgi" "sed" ];
    services.websites.env.tools.vhostConfs.task = {
      certName    = "eldiron";
      hosts       = [ "task.immae.eu" ];
      root        = ./www;
      extraConfig = [ ''
        <Directory ${./www}>
          DirectoryIndex index.php
          Use LDAPConnect
          Require ldap-group cn=users,cn=taskwarrior,ou=services,dc=immae,dc=eu
          <FilesMatch "\.php$">
            SetHandler "proxy:unix:${config.services.phpfpm.pools.tasks.socket}|fcgi://localhost"
          </FilesMatch>
          Include ${config.secrets.fullPaths."webapps/tools-taskwarrior-web"}
        </Directory>
        ''
        ''
        <Macro Taskwarrior %{folderName}>
          ProxyPass        "unix://${socketsDir}/%{folderName}.sock|http://localhost-%{folderName}/"
          ProxyPassReverse "unix://${socketsDir}/%{folderName}.sock|http://localhost-%{folderName}/"
          ProxyPassReverse http://${fqdn}/

          SetOutputFilter Sed
          OutputSed   "s|/ajax|/taskweb/%{folderName}/ajax|g"
          OutputSed   "s|\([^x]\)/tasks|\1/taskweb/%{folderName}/tasks|g"
          OutputSed   "s|\([^x]\)/projects|\1/taskweb/%{folderName}/projects|g"
          OutputSed   "s|http://${fqdn}/|/taskweb/%{folderName}/|g"
          OutputSed   "s|/img/relax.jpg|/taskweb/%{folderName}/img/relax.jpg|g"
        </Macro>
        ''
        ''
        Alias /taskweb ${taskwebPages}
        <Directory "${taskwebPages}">
          DirectoryIndex index.html
          Require all granted
        </Directory>

        RewriteEngine on
        RewriteRule ^/taskweb$ /taskweb/ [R=301,L]
        RedirectMatch permanent ^/taskweb/([^/]+)$ /taskweb/$1/

        RewriteCond %{LA-U:REMOTE_USER} !=""
        RewriteCond ${taskwebPages}/%{LA-U:REMOTE_USER}.html -f
        RewriteRule ^/taskweb/?$ ${taskwebPages}/%{LA-U:REMOTE_USER}.html [L]

        <Location /taskweb/>
          Use LDAPConnect
          Require ldap-group cn=users,cn=taskwarrior,ou=services,dc=immae,dc=eu
        </Location>
        ''
      ] ++ (lib.attrsets.mapAttrsToList (k: v: ''
        <Location /taskweb/${k}/>
          ${builtins.concatStringsSep "\n" (map (uid: "Require ldap-attribute   uid=${uid}") v.uid)}

          Use Taskwarrior ${k}
        </Location>
        '') env.taskwarrior-web);
    };
    services.phpfpm.pools = {
      tasks = {
        user = user;
        group = group;
        settings = {
          "listen.owner" = "wwwrun";
          "listen.group" = "wwwrun";
          "pm" = "dynamic";
          "pm.max_children" = "60";
          "pm.start_servers" = "2";
          "pm.min_spare_servers" = "1";
          "pm.max_spare_servers" = "10";

          # Needed to avoid clashes in browser cookies (same domain)
          "php_value[session.name]" = "TaskPHPSESSID";
          "php_admin_value[session.save_handler]" = "redis";
          "php_admin_value[session.save_path]" = "'unix:///run/redis-php-sessions/redis.sock?persistent=1&prefix=Tools:Task:'";
          "php_admin_value[open_basedir]" = "${./www}:/tmp:${server_vardir}:/etc/profiles/per-user/${user}/bin/";
        };
        phpEnv = {
          PATH = "/etc/profiles/per-user/${user}/bin";
        };
        phpPackage = pkgs.php72.withExtensions({ enabled, all }: enabled ++ [ all.redis ]);
      };
    };

    security.acme.certs."task" = {
      inherit group;
      domain = fqdn;
      postRun = ''
        systemctl restart taskserver.service
      '';
    };

    users.users.${user} = {
      extraGroups = [ "keys" ];
      packages = [ taskserver-user-certs ];
    };

    system.activationScripts.taskserver = {
      deps = [ "users" ];
      text = ''
        install -m 0750 -o ${user} -g ${group} -d ${server_vardir}
        install -m 0750 -o ${user} -g ${group} -d ${server_vardir}/userkeys
        install -m 0750 -o ${user} -g ${group} -d ${server_vardir}/keys

        if [ ! -e "${server_vardir}/keys/ca.key" ]; then
          silent_certtool() {
            if ! output="$("${pkgs.gnutls.bin}/bin/certtool" "$@" 2>&1)"; then
              echo "GNUTLS certtool invocation failed with output:" >&2
              echo "$output" >&2
            fi
          }

          silent_certtool -p \
            --bits 4096 \
            --outfile "${server_vardir}/keys/ca.key"

          silent_certtool -s \
            --template "${pkgs.writeText "taskserver-ca.template" ''
              cn = ${fqdn}
              expiration_days = -1
              cert_signing_key
              ca
            ''}" \
            --load-privkey "${server_vardir}/keys/ca.key" \
            --outfile "${server_vardir}/keys/ca.cert"

          chown :${group} "${server_vardir}/keys/ca.key"
          chmod g+r "${server_vardir}/keys/ca.key"
        fi
      '';
    };

    services.taskserver = {
      enable = true;
      allowedClientIDs = [ "^task [2-9]" "^Mirakel [1-9]" ];
      inherit fqdn;
      listenHost = "::";
      pki.manual.ca.cert = "${server_vardir}/keys/ca.cert";
      pki.manual.server.cert = "${config.security.acme.certs.task.directory}/fullchain.pem";
      pki.manual.server.crl = "${config.security.acme.certs.task.directory}/invalid.crl";
      pki.manual.server.key = "${config.security.acme.certs.task.directory}/key.pem";
      requestLimit = 104857600;
    };

    system.activationScripts.taskwarrior-web = {
      deps = [ "users" ];
      text = ''
        if [ ! -f ${server_vardir}/userkeys/taskwarrior-web.cert.pem ]; then
          ${taskserver-user-certs}/bin/taskserver-user-certs taskwarrior-web
          chown taskd:taskd ${server_vardir}/userkeys/taskwarrior-web.cert.pem ${server_vardir}/userkeys/taskwarrior-web.key.pem
        fi
      '';
    };

    systemd.slices.taskwarrior = {
      description = "Taskwarrior slice";
    };

    systemd.services = (lib.attrsets.mapAttrs' (name: userConfig:
      lib.attrsets.nameValuePair "taskwarrior-web-${name}" {
        description = "Taskwarrior webapp for ${name}";
        wantedBy = [ "multi-user.target" ];
        after = [ "network.target" ];
        path = [ pkgs.taskwarrior ];

        environment.TASKRC = config.secrets.fullPaths."webapps/tools-taskwarrior/${name}-taskrc";
        environment.BUNDLE_PATH = "${taskwarrior-web.gems}/${taskwarrior-web.gems.ruby.gemPath}";
        environment.BUNDLE_GEMFILE = "${taskwarrior-web.gems.confFiles}/Gemfile";
        environment.LC_ALL = "fr_FR.UTF-8";

        script = ''
          exec ${taskwarrior-web.gems}/${taskwarrior-web.gems.ruby.gemPath}/bin/bundle exec thin start -R config.ru -S ${socketsDir}/${name}.sock
        '';

        serviceConfig = {
          Slice = "taskwarrior.slice";
          User = user;
          PrivateTmp = true;
          Restart = "always";
          TimeoutSec = 60;
          Type = "simple";
          WorkingDirectory = taskwarrior-web;
          StateDirectoryMode = 0750;
          StateDirectory = assert lib.strings.hasPrefix "/var/lib/" varDir;
            (lib.strings.removePrefix "/var/lib/" varDir + "/${name}");
          RuntimeDirectoryPreserve = "yes";
          RuntimeDirectory = assert lib.strings.hasPrefix "/run/" socketsDir;
            lib.strings.removePrefix "/run/" socketsDir;
        };

        unitConfig.RequiresMountsFor = varDir;
      }) env.taskwarrior-web) // {
        taskserver-ca.postStart = ''
          chown :${group} "${server_vardir}/keys/ca.key"
          chmod g+r "${server_vardir}/keys/ca.key"
        '';
        taskserver-ca.serviceConfig.Slice = "taskwarrior.slice";
        taskserver-init.serviceConfig.Slice = "taskwarrior.slice";
        taskserver.serviceConfig.Slice = "taskwarrior.slice";
      };

  };
}