summary refs log tree commit diff stats
path: root/system/services/nix-sync/default.nix
blob: 8c466b877199143c15cfe349273a6d2983d099b9 (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
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
{
  config,
  lib,
  pkgs,
  ...
}: let
  cfg = config.services.nix-sync;

  mkTimer = name: repo: {
    description = "Nix sync ${name} timer";
    wantedBy = ["timers.target"];
    timerConfig = {
      OnUnitActiveSec = repo.interval;
    };
    after = ["network-online.target"];
  };

  parents = path: let
    split_path = builtins.split "/" path;
    filename = builtins.elemAt split_path (builtins.length split_path - 1);
  in
    lib.strings.removeSuffix "/" (builtins.replaceStrings [filename] [""] path);
  esa = lib.strings.escapeShellArg;
  mkUnit = name: repo: let
    optionalPathSeparator =
      if lib.strings.hasPrefix "/" repo.path
      then ""
      else "/";
    repoCachePath = cfg.cachePath + optionalPathSeparator + repo.path;
    execStartScript = pkgs.writeScript "nix-sync-exec" ''
      #! /usr/bin/env dash
      export XDG_CACHE_HOME="$CACHE_DIRECTORY";
      cd ${esa repoCachePath};

      git fetch
      origin="$(git rev-parse @{u})";
      branch="$(git rev-parse @)";

      if ! [ "$origin" = "$branch" ]; then
        git pull --rebase;

        out_paths=$(mktemp);
        nix build . --print-out-paths --experimental-features 'nix-command flakes' > "$out_paths";
        [ "$(wc -l < "$out_paths")" -gt 1 ] && (echo "To many out-paths"; exit 1)
        out_path="$(cat "$out_paths")";
        rm ${esa repo.path};
        ln -s "$out_path" ${esa repo.path};
        rm "$out_paths";
      fi
    '';
    execStartPreScript = ''
      export XDG_CACHE_HOME="$CACHE_DIRECTORY";

      if ! [ -d ${esa repoCachePath}/.git ]; then
          mkdir --parents ${esa repoCachePath};
          git clone ${esa repo.uri} ${esa repoCachePath};

          out_paths=$(mktemp);
          nix build ${esa repoCachePath} --print-out-paths --experimental-features 'nix-command flakes' > "$out_paths";
          [ "$(wc -l < "$out_paths")" -gt 1 ] && (echo "To many out-paths"; exit 1)
          out_path="$(cat "$out_paths")";
          ln -s "$out_path" ${esa repo.path};
          rm "$out_paths";
      fi

      if ! [ -L ${esa repo.path} ]; then
        cd ${esa repoCachePath};

        git pull --rebase;

        out_paths=$(mktemp);
        nix build . --print-out-paths --experimental-features 'nix-command flakes' > "$out_paths";
        [ "$(wc -l < "$out_paths")" -gt 1 ] && (echo "To many out-paths"; exit 1)
        out_path="$(cat "$out_paths")";

        [ -d ${esa repo.path} ] && rm -d ${esa repo.path};
        [ -e ${esa repo.path} ] && rm ${esa repo.path};

        ln -s "$out_path" ${esa repo.path};
        rm "$out_paths";
      fi
    '';
  in {
    description = "Nix Sync ${name}";
    wantedBy = ["default.target"];
    after = ["network.target"];
    path = with pkgs; [openssh git nix mktemp coreutils dash];
    preStart = execStartPreScript;

    serviceConfig = {
      TimeoutSec = 0;
      ExecStart = execStartScript;
      Restart = "on-abort";
      # User and group
      User = cfg.user;
      Group = cfg.group;
      # Runtime directory and mode
      RuntimeDirectory = "nix-sync";
      RuntimeDirectoryMode = "0750";
      # Cache directory and mode
      CacheDirectory = "nix-sync";
      CacheDirectoryMode = "0750";
      # Logs directory and mode
      LogsDirectory = "nix-sync";
      LogsDirectoryMode = "0750";
      # Proc filesystem
      ProcSubset = "all";
      ProtectProc = "invisible";
      # New file permissions
      UMask = "0027"; # 0640 / 0750
      # Capabilities
      AmbientCapabilities = ["CAP_CHOWN"];
      CapabilityBoundingSet = ["CAP_CHOWN"];
      # Security
      NoNewPrivileges = true;
      # Sandboxing (sorted by occurrence in https://www.freedesktop.org/software/systemd/man/systemd.exec.html)
      ReadWritePaths = ["${esa (parents repo.path)}" "-${esa repoCachePath}" "-${esa cfg.cachePath}"];
      ReadOnlyPaths = ["/nix"];
      ProtectSystem = "strict";
      ProtectHome = true;
      PrivateTmp = true;
      PrivateDevices = true;
      ProtectHostname = true;
      ProtectClock = true;
      ProtectKernelTunables = true;
      ProtectKernelModules = true;
      ProtectKernelLogs = true;
      ProtectControlGroups = true;
      RestrictAddressFamilies = ["AF_UNIX" "AF_INET" "AF_INET6"];
      RestrictNamespaces = true;
      LockPersonality = true;
      MemoryDenyWriteExecute = true;
      RestrictRealtime = true;
      RestrictSUIDSGID = true;
      RemoveIPC = true;
      PrivateMounts = true;
      # System Call Filtering
      SystemCallArchitectures = "native";
      SystemCallFilter = ["~@cpu-emulation @debug @keyring @mount @obsolete @privileged @setuid"];
    };
  };

  services =
    lib.mapAttrs' (name: repo: {
      name = "nix-sync-${name}";
      value = mkUnit name repo;
    })
    cfg.repositories;
  timers =
    lib.mapAttrs' (name: repo: {
      name = "nix-sync-${name}";
      value = mkTimer name repo;
    })
    cfg.repositories;

  # generate the websites directory, so systemd can mount it read write
  generatedDirectories =
    lib.mapAttrsToList (
      _: repo: "d ${esa (parents repo.path)} 0755 ${cfg.user} ${cfg.group}"
    )
    cfg.repositories;

  repositoryType = lib.types.submodule ({name, ...}: {
    options = {
      name = lib.mkOption {
        internal = true;
        default = name;
        type = lib.types.str;
        description = "The name that should be given to this unit.";
      };

      path = lib.mkOption {
        type = lib.types.str;
        description = "The path at which to sync the repository";
      };

      uri = lib.mkOption {
        type = lib.types.str;
        example = "ssh://user@example.com:/~[user]/path/to/repo.git";
        description = ''
          The URI of the remote to be synchronized. This is only used in the
          event that the directory does not already exist. See
          <link xlink:href="https://git-scm.com/docs/git-clone#_git_urls"/>
          for the supported URIs.
        '';
      };

      interval = lib.mkOption {
        type = lib.types.int;
        default = 500;
        description = ''
          The interval, specified in seconds, at which the synchronization will
          be triggered.
        '';
      };
    };
  });
in {
  options = {
    services.nix-sync = {
      enable = lib.mkEnableOption "nix-sync services";

      user = lib.mkOption {
        type = lib.types.str;
        default = "nix-sync";
        description = lib.mdDoc "User account under which nix-sync units runs.";
      };

      group = lib.mkOption {
        type = lib.types.str;
        default = "nix-sync";
        description = lib.mdDoc "Group account under which nix-sync units runs.";
      };

      cachePath = lib.mkOption {
        type = lib.types.str;
        default = "/var/lib/nix-sync";
        description = lib.mdDoc ''
          Where to cache git directories. Should not end with a slash ("/")
        '';
      };

      repositories = lib.mkOption {
        type = with lib.types; attrsOf repositoryType;
        description = ''
          The repositories that should be synchronized.
        '';
      };
    };
  };

  config = lib.mkIf cfg.enable {
    assertions = [
      {
        assertion = !lib.strings.hasSuffix "/" cfg.cachePath;
        message = "Your cachePath ('${cfg.cachePath}') ends with a slash ('/'), please use: '${lib.strings.removeSuffix "/" cfg.cachePath}'.";
      }
    ];

    systemd.tmpfiles.rules =
      generatedDirectories;

    systemd.services = services;
    systemd.timers = timers;
    users.users =
      if cfg.user == "nix-sync"
      then {
        nix-sync = {
          group = "${cfg.group}";
          isSystemUser = true;
        };
      }
      else lib.warnIf (cfg.user != "nix-sync") "The user (${cfg.user}) is not \"nix-sync\", thus you are responible for generating it.";
    users.groups =
      if cfg.group == "nix-sync"
      then {
        nix-sync = {
          members = ["${cfg.user}"];
        };
      }
      else lib.warnIf (cfg.group != "nix-sync") "The group (${cfg.group}) is not \"nix-sync\", thus you are responible for generating it.";
  };
}