aboutsummaryrefslogtreecommitdiff
path: root/nixops/modules/task/default.nix
blob: 9671725b7f9f4d38f08a0ad35e134562ad0ad6ae (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
{ lib, pkgs, config, myconfig, mylibs, ... }:
let
  cfg = config.services.myTasks;
  vardir = config.services.taskserver.dataDir;
  fqdn = "task.immae.eu";
  user = config.services.taskserver.user;
  env = myconfig.env.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 "${vardir}/userkeys/$user.key.pem"
    ${pkgs.gnused}/bin/sed -i -n -e '/^-----BEGIN RSA PRIVATE KEY-----$/,$p' "${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 "${vardir}/keys/ca.cert" \
      --load-ca-privkey "${vardir}/keys/ca.key" \
      --load-privkey "${vardir}/userkeys/$user.key.pem" \
      --outfile "${vardir}/userkeys/$user.cert.pem"
    EOF
    chmod a+x $out/bin/taskserver-user-certs
    patchShebangs $out/bin/taskserver-user-certs
    '';
  taskwarrior-web = pkgs.callPackage ./taskwarrior-web.nix {
    inherit (mylibs) fetchedGithub;
    inherit env;
  };
  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.services.myTasks = {
    enable = lib.mkEnableOption "my tasks service";
  };

  config = lib.mkIf cfg.enable {
    mySecrets.keys = [{
      dest = "webapps/tools-taskwarrior-web";
      user = "wwwrun";
      group = "wwwrun";
      permissions = "0400";
      text = ''
          SetEnv TASKD_HOST          "${fqdn}:${toString config.services.taskserver.listenPort}"
          SetEnv TASKD_VARDIR        "${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.search}"
        '';
    }];
    security.acme.certs."eldiron".extraDomains.${fqdn} = null;
    services.myWebsites.tools.modules = [ "proxy_fcgi" "sed" ];
    services.myWebsites.tools.vhostConfs.task = {
      certName    = "eldiron";
      hosts       = [ "task.immae.eu" ];
      root        = "/run/current-system/webapps/_task";
      extraConfig = [ ''
        <Directory /run/current-system/webapps/_task>
          DirectoryIndex index.php
          Use LDAPConnect
          Require ldap-group cn=users,cn=taskwarrior,ou=services,dc=immae,dc=eu
          <FilesMatch "\.php$">
            SetHandler "proxy:unix:/var/run/phpfpm/task.sock|fcgi://localhost"
          </FilesMatch>
          Include /var/secrets/webapps/tools-taskwarrior-web
        </Directory>
        ''
        ''
        <Macro Taskwarrior %{folderName}>
          ProxyPass        "unix://${taskwarrior-web.socketsDir}/%{folderName}.sock|http://localhost-%{folderName}/"
          ProxyPassReverse "unix://${taskwarrior-web.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.myPhpfpm.poolConfigs = {
      tasks = ''
        listen = /var/run/phpfpm/task.sock
        user = ${user}
        group = ${group}
        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)
        env[PATH] = "/etc/profiles/per-user/${user}/bin"
        php_value[session.name] = TaskPHPSESSID
        php_admin_value[open_basedir] = "${./www}:/tmp:${vardir}:/etc/profiles/per-user/${user}/bin/"
      '';
    };

    system.extraSystemBuilderCmds = ''
      ln -s ${./www} $out/webapps/_task
      '';

    security.acme.certs."task" = config.services.myCertificates.certConfig // {
      inherit user group;
      plugins = [ "fullchain.pem" "key.pem" "cert.pem" "account_key.json" ];
      domain = fqdn;
      postRun = ''
        systemctl restart taskserver.service
      '';
    };

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

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

        if [ ! -e "${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 "${vardir}/keys/ca.key"

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

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

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

    system.activationScripts.taskwarrior-web = {
      deps = [ "users" ];
      text = ''
        install -m 0755 -o ${user} -g ${group} -d ${taskwarrior-web.socketsDir}
        install -m 0750 -o ${user} -g ${group} -d ${taskwarrior-web.varDir}
        ${builtins.concatStringsSep "\n" (lib.attrsets.mapAttrsToList
          (k: v: "install -m 0750 -o ${user} -g ${group} -d ${taskwarrior-web.varDir}/${k}")
          env.taskwarrior-web
        )}
        if [ ! -f ${vardir}/userkeys/taskwarrior-web.cert.pem ]; then
          ${taskserver-user-certs}/bin/taskserver-user-certs taskwarrior-web
          chown taskd:taskd ${vardir}/userkeys/taskwarrior-web.cert.pem ${vardir}/userkeys/taskwarrior-web.key.pem
        fi
      '';
    };

    systemd.services = (lib.attrsets.mapAttrs' (name: userConfig:
      let
        credentials = "${userConfig.org}/${name}/${userConfig.key}";
        dateFormat = userConfig.date;
        taskrc = pkgs.writeText "taskrc" ''
          data.location=${taskwarrior-web.varDir}/${name}
          taskd.certificate=${vardir}/userkeys/taskwarrior-web.cert.pem
          taskd.key=${vardir}/userkeys/taskwarrior-web.key.pem
          # IdenTrust DST Root CA X3
          # obtained here: https://letsencrypt.org/fr/certificates/
          taskd.ca=${pkgs.writeText "ca.cert" ''
            -----BEGIN CERTIFICATE-----
            MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/
            MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
            DkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow
            PzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD
            Ew5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
            AN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmTrE4O
            rz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEq
            OLl5CjH9UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9b
            xiqKqy69cK3FCxolkHRyxXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw
            7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40dutolucbY38EVAjqr2m7xPi71XAicPNaD
            aeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV
            HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQMA0GCSqG
            SIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69
            ikugdB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXr
            AvHRAosZy5Q6XkjEGB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZz
            R8srzJmwN0jP41ZL9c8PDHIyh8bwRLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5
            JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubSfZGL+T0yjWW06XyxV3bqxbYo
            Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ
            -----END CERTIFICATE-----''}
          taskd.server=${fqdn}:${toString config.services.taskserver.listenPort}
          taskd.credentials=${credentials}
          dateformat=${dateFormat}
          '';
      in lib.attrsets.nameValuePair "taskwarrior-web-${name}" {
        description = "Taskwarrior webapp for ${name}";
        wantedBy = [ "multi-user.target" ];
        after = [ "network.target" ];
        path = [ pkgs.taskwarrior ];

        environment.TASKRC = 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 ${taskwarrior-web.socketsDir}/${name}.sock
        '';

        serviceConfig = {
          User = user;
          PrivateTmp = true;
          Restart = "always";
          TimeoutSec = 60;
          Type = "simple";
          WorkingDirectory = taskwarrior-web.rubyRoot;
        };

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

  };
}