summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/web-apps/part-db.nix
blob: ef5f5d076163d1359eebea7e536b2a1da10f02c8 (plain)
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
{
  pkgs,
  config,
  lib,
  ...
}:
let
  cfg = config.services.part-db;
  pkg = cfg.package;

  envFile = pkgs.writeText "part-db-env" (
    lib.concatStringsSep "\n" (lib.mapAttrsToList (key: value: "${key}=\"${value}\"") cfg.settings)
    + "\n"
  );

  inherit (lib)
    mkEnableOption
    mkPackageOption
    mkOption
    types
    mkIf
    ;
in
{
  meta.maintainers = with lib.maintainers; [ felbinger ];

  options.services.part-db = {
    enable = mkEnableOption "PartDB";

    package = mkPackageOption pkgs "part-db" { };

    phpPackage = mkPackageOption pkgs "php" { } // {
      apply =
        pkg:
        pkg.buildEnv {
          extraConfig = ''
            memory_limit = 256M;
          '';
        };
    };

    enableNginx = mkOption {
      type = types.bool;
      default = true;
      description = ''
        Whether to enable nginx or not. If enabled, an nginx virtual host will
        be created for access to part-db. If not enabled, then you may use
        `''${config.services.part-db.package}/public` as your document root in
        whichever webserver you wish to setup.
      '';
    };

    enablePostgresql = mkOption {
      type = types.bool;
      default = true;
      description = ''
        Whether to configure the postgresql database for part-db. If enabled,
        a database and user will be created for part-db.
      '';
    };

    virtualHost = mkOption {
      type = types.str;
      default = "localhost";
      description = ''
        The virtualHost at which you wish part-db to be served.
      '';
    };

    environmentFile = mkOption {
      type = types.nullOr types.path;
      default = null;
      example = "/run/secrets/part-db.env";
      description = ''
        Path to a file containing extra Part-DB environment variables in dotenv
        format. This can be used for secrets such as `APP_SECRET` without
        putting them in the Nix store.
      '';
    };

    poolConfig = lib.mkOption {
      type = lib.types.attrsOf (
        lib.types.oneOf [
          lib.types.str
          lib.types.int
          lib.types.bool
        ]
      );
      default = { };
      defaultText = ''
        {
          "pm" = "dynamic";
          "pm.max_children" = 32;
          "pm.start_servers" = 2;
          "pm.min_spare_servers" = 2;
          "pm.max_spare_servers" = 4;
          "pm.max_requests" = 500;
        }
      '';
      description = ''
        Options for the PartDB PHP pool. See the documentation on <literal>php-fpm.conf</literal>
        for details on configuration directives.
      '';
    };

    settings = lib.mkOption {
      default = { };
      description = ''
        Options for part-db configuration. Refer to
        <https://github.com/Part-DB/Part-DB-server/blob/master/.env> for
        details on supported values. All <option>_FILE values supported by
        upstream are supported here.
      '';
      example = lib.literalExpression ''
        {
          DATABASE_URL = "postgresql://db_user@localhost/db_name?serverVersion=16.6&charset=utf8&host=/var/run/postgresql";
        }
      '';
      type = lib.types.submodule {
        freeformType = lib.types.attrsOf (
          with lib.types;
          oneOf [
            str
            int
            bool
          ]
        );
        options = {
          DATABASE_URL = lib.mkOption {
            type = lib.types.str;
            default = "postgresql://part-db@localhost/part-db?serverVersion=${config.services.postgresql.package.version}&host=/run/postgresql";
            defaultText = "postgresql://part-db@localhost/part-db?serverVersion=\${config.services.postgresql.package.version}&host=/run/postgresql";
            description = ''
              The postgresql database server to connect to.
              Defauls to local postgresql unix socket
            '';
          };
        };
      };
    };
  };

  config = mkIf cfg.enable {
    users.groups.part-db = { };
    users.users.part-db = {
      group = "part-db";
      isSystemUser = true;
    };

    services = {
      phpfpm.pools.part-db = {
        user = "part-db";
        group = "part-db";
        phpPackage = cfg.phpPackage;
        phpOptions = ''
          log_errors = on
        '';
        settings = {
          "listen.mode" = lib.mkDefault "0660";
          "listen.owner" = lib.mkDefault "part-db";
          "listen.group" = lib.mkDefault "part-db";
          "pm" = lib.mkDefault "dynamic";
          "pm.max_children" = lib.mkDefault 32;
          "pm.start_servers" = lib.mkDefault 2;
          "pm.min_spare_servers" = lib.mkDefault 2;
          "pm.max_spare_servers" = lib.mkDefault 4;
          "pm.max_requests" = lib.mkDefault 500;
        }
        // cfg.poolConfig;
      };

      # Required for symphony
      part-db.settings.APP_SHARE_DIR = "/var/lib/part-db/share";

      postgresql = mkIf cfg.enablePostgresql {
        enable = true;
        ensureUsers = [
          {
            name = "part-db";
            ensureDBOwnership = true;
          }
        ];
        ensureDatabases = [ "part-db" ];
      };

      nginx = mkIf cfg.enableNginx {
        enable = true;
        recommendedTlsSettings = lib.mkDefault true;
        recommendedOptimisation = lib.mkDefault true;
        recommendedGzipSettings = lib.mkDefault true;
        virtualHosts.${cfg.virtualHost} = {
          root = "${pkg}/public";
          locations = {
            "/" = {
              tryFiles = "$uri $uri/ /index.php$is_args$args";
              index = "index.php";
              extraConfig = ''
                add_header Content-Security-Policy "default-src 'self'; script-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; sandbox;" always;
                add_header X-Content-Type-Options "nosniff" always;
                sendfile off;
              '';
            };
            "= /index.php" = {
              extraConfig = ''
                include ${config.services.nginx.package}/conf/fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root;
                fastcgi_param modHeadersAvailable true; # Avoid sending the security headers twice
                fastcgi_pass unix:${config.services.phpfpm.pools.part-db.socket};
                internal;
              '';
            };
            "~ \\.php$" = {
              return = "404";
            };
            "~* ^/media/.*\\.(php[3-8]?|phar|phtml|pht|phps)$" = {
              return = "403";
            };
            "~* \\.svg$" = {
              extraConfig = ''
                add_header Content-Security-Policy "default-src 'self'; script-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; sandbox;" always;
                add_header X-Content-Type-Options "nosniff" always;
              '';
            };
          };
        };
      };
    };

    systemd = {
      services = {
        part-db-setup = {
          before = [ "part-db-migrate.service" ];
          wantedBy = [ "multi-user.target" ];
          serviceConfig = {
            Type = "oneshot";
            RemainAfterExit = true;
          };
          restartTriggers = [ envFile ];
          script = ''
            install -Dm0600 -o part-db -g part-db ${envFile} /var/lib/part-db/env.local
          ''
          + lib.optionalString (cfg.environmentFile != null) ''
            cat ${lib.escapeShellArg cfg.environmentFile} >> /var/lib/part-db/env.local
          '';
        };

        part-db-migrate = {
          before = [ "phpfpm-part-db.service" ];
          after = [
            "postgresql.target"
            "part-db-setup.service"
          ];
          requires = [
            "postgresql.target"
            "part-db-setup.service"
          ];
          wantedBy = [ "multi-user.target" ];
          serviceConfig = {
            ExecStart = "${lib.getExe cfg.phpPackage} ${lib.getExe' cfg.package "console"} doctrine:migrations:migrate --no-interaction";
            Type = "oneshot";
            RemainAfterExit = true;
            User = "part-db";
          };
          restartTriggers = [
            cfg.package
          ];
        };

        phpfpm-part-db = {
          after = [ "part-db-migrate.service" ];
          requires = [
            "part-db-migrate.service"
            "postgresql.target"
          ];
          # ensure nginx can access the php-fpm socket
          postStart = ''
            ${lib.getExe' pkgs.acl "setfacl"} -m 'u:${config.services.nginx.user}:rw' ${config.services.phpfpm.pools.part-db.socket}
          '';
        };
      };

      tmpfiles.settings."part-db" = {
        "/var/cache/part-db/".d = {
          mode = "0750";
          user = "part-db";
          group = "part-db";
        };
        "/var/lib/part-db/".d = {
          mode = "0755";
          user = "part-db";
          group = "part-db";
        };
        "/var/lib/part-db/public/".d = {
          mode = "0755";
          user = "part-db";
          group = "part-db";
        };
        "/var/lib/part-db/public/media/".d = {
          mode = "0755";
          user = "part-db";
          group = "part-db";
        };
        "/var/lib/part-db/uploads/".d = {
          mode = "0750";
          user = "part-db";
          group = "part-db";
        };
        "/var/lib/part-db/share/".d = {
          mode = "0750";
          user = "part-db";
          group = "part-db";
        };
        "/var/log/part-db/".d = {
          mode = "0750";
          user = "part-db";
          group = "part-db";
        };
      };
    };
  };
}