aboutsummaryrefslogblamecommitdiff
path: root/modules/private/tasks/default.nix
blob: b523995370416e77affe6baf329f2fa84555c188 (plain) (tree)
1
2
3
4
5
6
7
8
                            
   
                                
                                                     

                                         
                                
                                           















                                                                        

                                                                                                                      







                                                              



                                                                



                                                


                                                 




































                                                                                                                             
    
                              



                                                   
                                           







                                  
                     
                                             




                                                                                                
                                                       



                                                               
                                                         
           
       


                                                                                              
                              
                         







                                                                               
                                                                                                 
                       
                                                            
                    


                                         

                                                                                                    




































                                                                                                    
      

                             

















                                                                                                                 
                                
        

      
                                               
 
                                                                               
                         





                                            
                                                             



                                           


                                                                           
 
                                                        








                                                                              
                                                    







                                                                    

                                                           
 

                                                        
          







                                                            
                                                           


                                                                                            

                               



                                                
                                                                            
                                                                            
                                                                                                                                



          



                                        




                                                                    


                                                                              






















                                                                            










                                                                                
                                                                                                 



                                                                                 
                                                                                                                                                 


                         
                                      




                             
                                             





                                                                             

          
                                              

                                    

                                                        
           


                                                                  

        

    
{ lib, pkgs, config,  ... }:
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
    '';
  taskwarrior-web = pkgs.webapps.taskwarrior-web;
  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 {
    services.duplyBackup.profiles.tasks = {
      rootDir = "/var/lib";
      excludeFile = ''
        + /var/lib/taskserver
        + /var/lib/taskwarrior-web
        - /var/lib
        '';
    };

    secrets.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        "${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}"
        '';
    }];
    services.websites.env.tools.watchPaths = [ "/var/secrets/webapps/tools-taskwarrior-web" ];
    services.websites.env.tools.modules = [ "proxy_fcgi" "sed" ];
    services.websites.env.tools.vhostConfs.task = {
      certName    = "eldiron";
      addToCerts  = true;
      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:${config.services.phpfpm.pools.tasks.socket}|fcgi://localhost"
          </FilesMatch>
          Include /var/secrets/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[open_basedir]" = "${./www}:/tmp:${server_vardir}:/etc/profiles/per-user/${user}/bin/";
        };
        phpEnv = {
          PATH = "/etc/profiles/per-user/${user}/bin";
        };
        phpPackage = pkgs.php72;
      };
    };

    services.websites.webappDirs._task = ./www;

    security.acme.certs."task" = config.myServices.certificates.certConfig // {
      inherit user group;
      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 ${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:
      let
        credentials = "${userConfig.org}/${name}/${userConfig.key}";
        dateFormat = userConfig.date;
        taskrc = pkgs.writeText "taskrc" ''
          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=${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 ${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";
      };

  };
}