about summary refs log tree commit diff
path: root/modules/services/unifi/default.nix
blob: 3c702380975ad83f731905b16157d100a8c4ef6d (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
{ config, lib, pkgs, ... }:

let
  cfg = config.my.services.unifi;
  secrets = config.age.secrets;
  allowedRules = {
    # https://help.ubnt.com/hc/en-us/articles/218506997
    allowedTCPPorts = [
      8080 # Port for UAP to inform controller.
      8880 # Port for HTTP portal redirect, if guest portal is enabled.
      8843 # Port for HTTPS portal redirect, ditto.
      6789 # Port for UniFi mobile speed test.
      9130 # Port for the prometheus exporter
    ];
    allowedUDPPorts = [
      3478 # UDP port used for STUN.
      10001 # UDP port used for device discovery.
    ];
  };
in {
  options.my.services.unifi = with lib; {
    enable = mkEnableOption "Unifi controller";
    vhostName = mkOption {
      type = types.str;
      example = "music.fcuny.net";
      description = "Name for the virtual host";
    };
  };

  config = lib.mkIf cfg.enable {
    networking.firewall = allowedRules;
    users.users.unifi.group = "unifi";
    users.users.unifi.isSystemUser = true;
    users.groups.unifi = { };

    services.unifi = {
      enable = true;
      openFirewall = true;
      unifiPackage = pkgs.unifiStable;
    };

    services.unifi-poller = {
      enable = true;

      unifi.defaults = {
        url = "https://127.0.0.1:8443";
        user = "unifipoller";
        pass = secrets."unifi/unifi-poller".path;
        verify_ssl = false;
      };

      influxdb.disable = true;

      prometheus = { http_listen = ":9130"; };
    };

    systemd.services.unifi-available = {
      description = "Wait for Unifi to be available";
      after = [ "unifi.service" ];
      before = [ "unifi-poller.service" ];
      wantedBy = [ "unifi-poller.service" ];
      serviceConfig = {
        ExecStart =
          "${pkgs.curl}/bin/curl --insecure 'https://localhost:8443/'";
        Restart = "on-failure";
        RestartSec = "10";
        Type = "oneshot";
      };
    };

    services.nginx.virtualHosts."${cfg.vhostName}" = {
      forceSSL = true;
      useACMEHost = cfg.vhostName;
      locations."/" = {
        proxyPass = "http://127.0.0.1:8443";
        proxyWebsockets = true;
      };
    };

    security.acme.certs."${cfg.vhostName}" = {
      dnsProvider = "gcloud";
      credentialsFile = secrets."acme/credentials".path;
    };

    my.services.backup = { paths = [ "/var/lib/unifi" ]; };
  };
}