summaryrefslogtreecommitdiff
path: root/os/srv/postgres.nix
blob: f669f637e945c7e4c7a7131756f84523452a0fe6 (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
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.os.srv.postgres;
in
{
  options.os.srv.postgres.enable = lib.mkEnableOption "";
  config = lib.mkIf cfg.enable {
    assertions = [
      {
        assertion = config.os.srv.sops.enable;
        message = "Required for password secure password storing";
      }
      {
        assertion = config.os.core.network.enableFirewall;
        message = "Requires firewall";
      }
    ];

    sops.secrets."postgres/authelia_password" = {
      owner = "postgres";
      group = "postgres";
      restartUnits = [ "postgresql.service" ];
    };

    services.postgresql = {
      enable = true;
      package = pkgs.postgresql_18;

      extraPlugins = [ config.services.postgresql.package.pkgs.pgvector ];

      settings = {
        listen_addresses = config.os.core.network.ips.database-vm;

        max_connections = 100;
        shared_buffers = "256MB";
        work_mem = "4MB";
      };

      ensureDatabases = [ "authelia" ];
      ensureUsers = [
        {
          name = "authelia";
          ensureDBOwnership = true;
        }
      ];

      initialScript = pkgs.writeText "init-postgres-passwords.sql" ''
        CREATE USER authelia;
        ALTER USER authelia WITH PASSWORD 'scram-sha-256';
      '';

      authentication = pkgs.lib.mkForce ''
        local   all             all                                     trust
        host    all             all             10.0.0.0/24             scram-sha-256
      '';
    };

    systemd.services.postgresql.postStart = lib.mkAfter ''
      PASS=$(cat ${config.sops.secrets."postgres/authelia_password".path})
      ${config.services.postgresql.package}/bin/psql -tAc "ALTER USER authelia WITH PASSWORD '$PASS';"
    '';

    networking.firewall.extraInputRules = ''
      ip saddr 10.0.0.0/24 tcp dport 5432 accept
    '';
  };
}