summary refs log tree commit diff
path: root/nixos/modules/services/misc/heisenbridge.nix
blob: 7ce8a23d9af12e93464b52185c45c0245a1fcb45 (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
{ config, pkgs, lib, ... }:

with lib;

let
  cfg = config.services.heisenbridge;

  pkg = config.services.heisenbridge.package;
  bin = "${pkg}/bin/heisenbridge";

  jsonType = (pkgs.formats.json { }).type;

  registrationFile = "/var/lib/heisenbridge/registration.yml";
  # JSON is a proper subset of YAML
  bridgeConfig = builtins.toFile "heisenbridge-registration.yml" (builtins.toJSON {
    id = "heisenbridge";
    url = cfg.registrationUrl;
    # Don't specify as_token and hs_token
    rate_limited = false;
    sender_localpart = "heisenbridge";
    namespaces = cfg.namespaces;
  });
in
{
  options.services.heisenbridge = {
    enable = mkEnableOption "the Matrix to IRC bridge";

    package = mkOption {
      type = types.package;
      default = pkgs.heisenbridge;
      defaultText = "pkgs.heisenbridge";
      example = "pkgs.heisenbridge.override { … = …; }";
      description = ''
        Package of the application to run, exposed for overriding purposes.
      '';
    };

    homeserver = mkOption {
      type = types.str;
      description = "The URL to the home server for client-server API calls";
      example = "http://localhost:8008";
    };

    registrationUrl = mkOption {
      type = types.str;
      description = ''
        The URL where the application service is listening for HS requests, from the Matrix HS perspective.#
        The default value assumes the bridge runs on the same host as the home server, in the same network.
      '';
      example = "https://matrix.example.org";
      default = "http://${cfg.address}:${toString cfg.port}";
      defaultText = "http://$${cfg.address}:$${toString cfg.port}";
    };

    address = mkOption {
      type = types.str;
      description = "Address to listen on. IPv6 does not seem to be supported.";
      default = "127.0.0.1";
      example = "0.0.0.0";
    };

    port = mkOption {
      type = types.port;
      description = "The port to listen on";
      default = 9898;
    };

    debug = mkOption {
      type = types.bool;
      description = "More verbose logging. Recommended during initial setup.";
      default = false;
    };

    owner = mkOption {
      type = types.nullOr types.str;
      description = ''
        Set owner MXID otherwise first talking local user will claim the bridge
      '';
      default = null;
      example = "@admin:example.org";
    };

    namespaces = mkOption {
      description = "Configure the 'namespaces' section of the registration.yml for the bridge and the server";
      # TODO link to Matrix documentation of the format
      type = types.submodule {
        freeformType = jsonType;
      };

      default = {
        users = [
          {
            regex = "@irc_.*";
            exclusive = true;
          }
        ];
        aliases = [ ];
        rooms = [ ];
      };
    };

    identd.enable = mkEnableOption "identd service support";
    identd.port = mkOption {
      type = types.port;
      description = "identd listen port";
      default = 113;
    };

    extraArgs = mkOption {
      type = types.listOf types.str;
      description = "Heisenbridge is configured over the command line. Append extra arguments here";
      default = [ ];
    };
  };

  config = mkIf cfg.enable {
    systemd.services.heisenbridge = {
      description = "Matrix<->IRC bridge";
      before = [ "matrix-synapse.service" ]; # So the registration file can be used by Synapse
      wantedBy = [ "multi-user.target" ];

      preStart = ''
        umask 077
        set -e -u -o pipefail

        if ! [ -f "${registrationFile}" ]; then
          # Generate registration file if not present (actually, we only care about the tokens in it)
          ${bin} --generate --config ${registrationFile}
        fi

        # Overwrite the registration file with our generated one (the config may have changed since then),
        # but keep the tokens. Two step procedure to be failure safe
        ${pkgs.yq}/bin/yq --slurp \
          '.[0] + (.[1] | {as_token, hs_token})' \
          ${bridgeConfig} \
          ${registrationFile} \
          > ${registrationFile}.new
        mv -f ${registrationFile}.new ${registrationFile}

        # Grant Synapse access to the registration
        if ${getBin pkgs.glibc}/bin/getent group matrix-synapse > /dev/null; then
          chgrp -v matrix-synapse ${registrationFile}
          chmod -v g+r ${registrationFile}
        fi
      '';

      serviceConfig = rec {
        Type = "simple";
        ExecStart = lib.concatStringsSep " " (
          [
            bin
            (if cfg.debug then "-vvv" else "-v")
            "--config"
            registrationFile
            "--listen-address"
            (lib.escapeShellArg cfg.address)
            "--listen-port"
            (toString cfg.port)
          ]
          ++ (lib.optionals (cfg.owner != null) [
            "--owner"
            (lib.escapeShellArg cfg.owner)
          ])
          ++ (lib.optionals cfg.identd.enable [
            "--identd"
            "--identd-port"
            (toString cfg.identd.port)
          ])
          ++ [
            (lib.escapeShellArg cfg.homeserver)
          ]
          ++ (map (lib.escapeShellArg) cfg.extraArgs)
        );

        # Hardening options

        User = "heisenbridge";
        Group = "heisenbridge";
        RuntimeDirectory = "heisenbridge";
        RuntimeDirectoryMode = "0700";
        StateDirectory = "heisenbridge";
        StateDirectoryMode = "0755";

        ProtectSystem = "strict";
        ProtectHome = true;
        PrivateTmp = true;
        PrivateDevices = true;
        ProtectKernelTunables = true;
        ProtectControlGroups = true;
        RestrictSUIDSGID = true;
        PrivateMounts = true;
        ProtectKernelModules = true;
        ProtectKernelLogs = true;
        ProtectHostname = true;
        ProtectClock = true;
        ProtectProc = "invisible";
        ProcSubset = "pid";
        RestrictNamespaces = true;
        RemoveIPC = true;
        UMask = "0077";

        CapabilityBoundingSet = [ "CAP_CHOWN" ] ++ optional (cfg.port < 1024 || (cfg.identd.enable && cfg.identd.port < 1024)) "CAP_NET_BIND_SERVICE";
        AmbientCapabilities = CapabilityBoundingSet;
        NoNewPrivileges = true;
        LockPersonality = true;
        RestrictRealtime = true;
        SystemCallFilter = ["@system-service" "~@priviledged" "@chown"];
        SystemCallArchitectures = "native";
        RestrictAddressFamilies = "AF_INET AF_INET6";
      };
    };

    users.groups.heisenbridge = {};
    users.users.heisenbridge = {
      description = "Service user for the Heisenbridge";
      group = "heisenbridge";
      isSystemUser = true;
    };
  };

  meta.maintainers = [ lib.maintainers.piegames ];
}