# The NixOS module does not support extending the configuration with secrets. { config, lib, pkgs, ... }: let fqdn = "turn.sbruder.de"; ipAddresses = [ "195.201.139.15" "2a01:4f8:1c1c:4397::" ]; cfg = { # config adapted from synapse’s turn howto: # https://github.com/matrix-org/synapse/blob/develop/docs/turn-howto.md use-auth-secret = true; realm = fqdn; # not needed for VoIP no-tcp-relay = true; # only tls no-cli = true; no-tcp = true; no-udp = true; tls-listening-port = 5349; cert = "/run/turnserver/fullchain.pem"; pkey = "/run/turnserver/key.pem"; min-port = 49160; max-port = 49200; listening-ip = ipAddresses; relay-ip = ipAddresses; pidfile = "/run/turnserver/turnserver.pid"; # logging no-stdout-log = true; syslog = true; denied-peer-ip = [ "10.0.0.0-10.255.255.255" "172.16.0.0-172.31.255.255" "192.168.0.0-192.168.255.255" ]; user-quota = 12; total-quota = 1200; }; extraConfigFiles = with config.sops.secrets; [ turn-static-auth-secret.path ]; configToText = config: lib.concatStrings (lib.mapAttrsToList (name: value: if lib.isList value then lib.concatMapStrings (value: "${name}=${toString value}\n") value else (if lib.isBool value then "${name}\n" else "${name}=${toString value}\n")) config); configFile = pkgs.writeText "turnserver.conf" (configToText cfg); in { sops.secrets.turn-static-auth-secret = { owner = "turnserver"; sopsFile = ../secrets.yaml; }; users.users.turnserver = { uid = config.ids.uids.turnserver; }; users.groups.turnserver = { gid = config.ids.gids.turnserver; members = [ "turnserver" ]; }; systemd.services.coturn = { after = [ "network-online.target" "acme-finished-${fqdn}.target" ]; wants = [ "network-online.target" ]; wantedBy = [ "multi-user.target" ]; serviceConfig = { Type = "simple"; ExecStartPre = [ ("!" + (pkgs.writeShellScript "coturn-setup-tls" '' cp ${config.security.acme.certs."${fqdn}".directory}/{fullchain,key}.pem /run/turnserver/ chgrp turnserver /run/turnserver/{fullchain,key}.pem '')) (pkgs.writeShellScript "coturn-setup-config" '' ${pkgs.coreutils}/bin/cat ${configFile} ${lib.concatStringsSep " " extraConfigFiles} > /run/turnserver/turnserver.conf '') ]; ExecStart = "${pkgs.coturn}/bin/turnserver -c /run/turnserver/turnserver.conf"; Restart = "on-abort"; RuntimeDirectory = "turnserver"; RuntimeDirectoryMode = "0750"; User = "turnserver"; Group = "turnserver"; SupplementaryGroups = lib.singleton "keys"; }; }; security.acme.certs."${fqdn}".postRun = '' if systemctl is-active coturn; then systemctl --no-block restart coturn fi ''; services.nginx.virtualHosts."${fqdn}" = { enableACME = true; forceSSL = true; }; networking.firewall = { allowedTCPPorts = [ cfg.tls-listening-port ]; allowedUDPPorts = [ cfg.tls-listening-port ]; allowedUDPPortRanges = lib.singleton { from = cfg.min-port; to = cfg.min-port; }; }; }