···4545 config.nix.package
4646 ] ++ cfg.extraPackages;
47474848- serviceConfig = mkMerge [{
4949- ExecStart = "${cfg.package}/bin/Runner.Listener run --startuptype service";
4848+ serviceConfig = mkMerge [
4949+ {
5050+ ExecStart = "${cfg.package}/bin/Runner.Listener run --startuptype service";
50515151- # Does the following, sequentially:
5252- # - If the module configuration or the token has changed, purge the state directory,
5353- # and create the current and the new token file with the contents of the configured
5454- # token. While both files have the same content, only the later is accessible by
5555- # the service user.
5656- # - Configure the runner using the new token file. When finished, delete it.
5757- # - Set up the directory structure by creating the necessary symlinks.
5858- ExecStartPre =
5959- let
6060- # Wrapper script which expects the full path of the state, working and logs
6161- # directory as arguments. Overrides the respective systemd variables to provide
6262- # unambiguous directory names. This becomes relevant, for example, if the
6363- # caller overrides any of the StateDirectory=, RuntimeDirectory= or LogDirectory=
6464- # to contain more than one directory. This causes systemd to set the respective
6565- # environment variables with the path of all of the given directories, separated
6666- # by a colon.
6767- writeScript = name: lines: pkgs.writeShellScript "${svcName}-${name}.sh" ''
6868- set -euo pipefail
5252+ # Does the following, sequentially:
5353+ # - If the module configuration or the token has changed, purge the state directory,
5454+ # and create the current and the new token file with the contents of the configured
5555+ # token. While both files have the same content, only the later is accessible by
5656+ # the service user.
5757+ # - Configure the runner using the new token file. When finished, delete it.
5858+ # - Set up the directory structure by creating the necessary symlinks.
5959+ ExecStartPre =
6060+ let
6161+ # Wrapper script which expects the full path of the state, working and logs
6262+ # directory as arguments. Overrides the respective systemd variables to provide
6363+ # unambiguous directory names. This becomes relevant, for example, if the
6464+ # caller overrides any of the StateDirectory=, RuntimeDirectory= or LogDirectory=
6565+ # to contain more than one directory. This causes systemd to set the respective
6666+ # environment variables with the path of all of the given directories, separated
6767+ # by a colon.
6868+ writeScript = name: lines: pkgs.writeShellScript "${svcName}-${name}.sh" ''
6969+ set -euo pipefail
69707070- STATE_DIRECTORY="$1"
7171- WORK_DIRECTORY="$2"
7272- LOGS_DIRECTORY="$3"
7171+ STATE_DIRECTORY="$1"
7272+ WORK_DIRECTORY="$2"
7373+ LOGS_DIRECTORY="$3"
73747474- ${lines}
7575- '';
7676- runnerRegistrationConfig = getAttrs [ "name" "tokenFile" "url" "runnerGroup" "extraLabels" "ephemeral" "workDir" ] cfg;
7777- newConfigPath = builtins.toFile "${svcName}-config.json" (builtins.toJSON runnerRegistrationConfig);
7878- currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json";
7979- newConfigTokenPath= "$STATE_DIRECTORY/.new-token";
8080- currentConfigTokenPath = "$STATE_DIRECTORY/${currentConfigTokenFilename}";
7575+ ${lines}
7676+ '';
7777+ runnerRegistrationConfig = getAttrs [ "name" "tokenFile" "url" "runnerGroup" "extraLabels" "ephemeral" "workDir" ] cfg;
7878+ newConfigPath = builtins.toFile "${svcName}-config.json" (builtins.toJSON runnerRegistrationConfig);
7979+ currentConfigPath = "$STATE_DIRECTORY/.nixos-current-config.json";
8080+ newConfigTokenPath = "$STATE_DIRECTORY/.new-token";
8181+ currentConfigTokenPath = "$STATE_DIRECTORY/${currentConfigTokenFilename}";
81828282- runnerCredFiles = [
8383- ".credentials"
8484- ".credentials_rsaparams"
8585- ".runner"
8686- ];
8787- unconfigureRunner = writeScript "unconfigure" ''
8888- copy_tokens() {
8989- # Copy the configured token file to the state dir and allow the service user to read the file
9090- install --mode=666 ${escapeShellArg cfg.tokenFile} "${newConfigTokenPath}"
9191- # Also copy current file to allow for a diff on the next start
9292- install --mode=600 ${escapeShellArg cfg.tokenFile} "${currentConfigTokenPath}"
9393- }
9494- clean_state() {
9595- find "$STATE_DIRECTORY/" -mindepth 1 -delete
9696- copy_tokens
9797- }
9898- diff_config() {
9999- changed=0
100100- # Check for module config changes
101101- [[ -f "${currentConfigPath}" ]] \
102102- && ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 \
103103- || changed=1
104104- # Also check the content of the token file
105105- [[ -f "${currentConfigTokenPath}" ]] \
106106- && ${pkgs.diffutils}/bin/diff -q "${currentConfigTokenPath}" ${escapeShellArg cfg.tokenFile} >/dev/null 2>&1 \
107107- || changed=1
108108- # If the config has changed, remove old state and copy tokens
109109- if [[ "$changed" -eq 1 ]]; then
110110- echo "Config has changed, removing old runner state."
111111- echo "The old runner will still appear in the GitHub Actions UI." \
112112- "You have to remove it manually."
8383+ runnerCredFiles = [
8484+ ".credentials"
8585+ ".credentials_rsaparams"
8686+ ".runner"
8787+ ];
8888+ unconfigureRunner = writeScript "unconfigure" ''
8989+ copy_tokens() {
9090+ # Copy the configured token file to the state dir and allow the service user to read the file
9191+ install --mode=666 ${escapeShellArg cfg.tokenFile} "${newConfigTokenPath}"
9292+ # Also copy current file to allow for a diff on the next start
9393+ install --mode=600 ${escapeShellArg cfg.tokenFile} "${currentConfigTokenPath}"
9494+ }
9595+ clean_state() {
9696+ find "$STATE_DIRECTORY/" -mindepth 1 -delete
9797+ copy_tokens
9898+ }
9999+ diff_config() {
100100+ changed=0
101101+ # Check for module config changes
102102+ [[ -f "${currentConfigPath}" ]] \
103103+ && ${pkgs.diffutils}/bin/diff -q '${newConfigPath}' "${currentConfigPath}" >/dev/null 2>&1 \
104104+ || changed=1
105105+ # Also check the content of the token file
106106+ [[ -f "${currentConfigTokenPath}" ]] \
107107+ && ${pkgs.diffutils}/bin/diff -q "${currentConfigTokenPath}" ${escapeShellArg cfg.tokenFile} >/dev/null 2>&1 \
108108+ || changed=1
109109+ # If the config has changed, remove old state and copy tokens
110110+ if [[ "$changed" -eq 1 ]]; then
111111+ echo "Config has changed, removing old runner state."
112112+ echo "The old runner will still appear in the GitHub Actions UI." \
113113+ "You have to remove it manually."
114114+ clean_state
115115+ fi
116116+ }
117117+ if [[ "${optionalString cfg.ephemeral "1"}" ]]; then
118118+ # In ephemeral mode, we always want to start with a clean state
113119 clean_state
114114- fi
115115- }
116116- if [[ "${optionalString cfg.ephemeral "1"}" ]]; then
117117- # In ephemeral mode, we always want to start with a clean state
118118- clean_state
119119- elif [[ "$(ls -A "$STATE_DIRECTORY")" ]]; then
120120- # There are state files from a previous run; diff them to decide if we need a new registration
121121- diff_config
122122- else
123123- # The state directory is entirely empty which indicates a first start
124124- copy_tokens
125125- fi
126126- '';
127127- configureRunner = writeScript "configure" ''
128128- if [[ -e "${newConfigTokenPath}" ]]; then
129129- echo "Configuring GitHub Actions Runner"
130130- args=(
131131- --unattended
132132- --disableupdate
133133- --work "$WORK_DIRECTORY"
134134- --url ${escapeShellArg cfg.url}
135135- --labels ${escapeShellArg (concatStringsSep "," cfg.extraLabels)}
136136- --name ${escapeShellArg cfg.name}
137137- ${optionalString cfg.replace "--replace"}
138138- ${optionalString (cfg.runnerGroup != null) "--runnergroup ${escapeShellArg cfg.runnerGroup}"}
139139- ${optionalString cfg.ephemeral "--ephemeral"}
140140- )
141141- # If the token file contains a PAT (i.e., it starts with "ghp_" or "github_pat_"), we have to use the --pat option,
142142- # if it is not a PAT, we assume it contains a registration token and use the --token option
143143- token=$(<"${newConfigTokenPath}")
144144- if [[ "$token" =~ ^ghp_* ]] || [[ "$token" =~ ^github_pat_* ]]; then
145145- args+=(--pat "$token")
120120+ elif [[ "$(ls -A "$STATE_DIRECTORY")" ]]; then
121121+ # There are state files from a previous run; diff them to decide if we need a new registration
122122+ diff_config
146123 else
147147- args+=(--token "$token")
124124+ # The state directory is entirely empty which indicates a first start
125125+ copy_tokens
148126 fi
149149- ${cfg.package}/bin/config.sh "''${args[@]}"
150150- # Move the automatically created _diag dir to the logs dir
151151- mkdir -p "$STATE_DIRECTORY/_diag"
152152- cp -r "$STATE_DIRECTORY/_diag/." "$LOGS_DIRECTORY/"
153153- rm -rf "$STATE_DIRECTORY/_diag/"
154154- # Cleanup token from config
155155- rm "${newConfigTokenPath}"
156156- # Symlink to new config
157157- ln -s '${newConfigPath}' "${currentConfigPath}"
158158- fi
159159- '';
160160- setupWorkDir = writeScript "setup-work-dirs" ''
161161- # Cleanup previous service
162162- ${pkgs.findutils}/bin/find -H "$WORK_DIRECTORY" -mindepth 1 -delete
127127+ '';
128128+ configureRunner = writeScript "configure" ''
129129+ if [[ -e "${newConfigTokenPath}" ]]; then
130130+ echo "Configuring GitHub Actions Runner"
131131+ args=(
132132+ --unattended
133133+ --disableupdate
134134+ --work "$WORK_DIRECTORY"
135135+ --url ${escapeShellArg cfg.url}
136136+ --labels ${escapeShellArg (concatStringsSep "," cfg.extraLabels)}
137137+ --name ${escapeShellArg cfg.name}
138138+ ${optionalString cfg.replace "--replace"}
139139+ ${optionalString (cfg.runnerGroup != null) "--runnergroup ${escapeShellArg cfg.runnerGroup}"}
140140+ ${optionalString cfg.ephemeral "--ephemeral"}
141141+ )
142142+ # If the token file contains a PAT (i.e., it starts with "ghp_" or "github_pat_"), we have to use the --pat option,
143143+ # if it is not a PAT, we assume it contains a registration token and use the --token option
144144+ token=$(<"${newConfigTokenPath}")
145145+ if [[ "$token" =~ ^ghp_* ]] || [[ "$token" =~ ^github_pat_* ]]; then
146146+ args+=(--pat "$token")
147147+ else
148148+ args+=(--token "$token")
149149+ fi
150150+ ${cfg.package}/bin/config.sh "''${args[@]}"
151151+ # Move the automatically created _diag dir to the logs dir
152152+ mkdir -p "$STATE_DIRECTORY/_diag"
153153+ cp -r "$STATE_DIRECTORY/_diag/." "$LOGS_DIRECTORY/"
154154+ rm -rf "$STATE_DIRECTORY/_diag/"
155155+ # Cleanup token from config
156156+ rm "${newConfigTokenPath}"
157157+ # Symlink to new config
158158+ ln -s '${newConfigPath}' "${currentConfigPath}"
159159+ fi
160160+ '';
161161+ setupWorkDir = writeScript "setup-work-dirs" ''
162162+ # Cleanup previous service
163163+ ${pkgs.findutils}/bin/find -H "$WORK_DIRECTORY" -mindepth 1 -delete
163164164164- # Link _diag dir
165165- ln -s "$LOGS_DIRECTORY" "$WORK_DIRECTORY/_diag"
165165+ # Link _diag dir
166166+ ln -s "$LOGS_DIRECTORY" "$WORK_DIRECTORY/_diag"
166167167167- # Link the runner credentials to the work dir
168168- ln -s "$STATE_DIRECTORY"/{${lib.concatStringsSep "," runnerCredFiles}} "$WORK_DIRECTORY/"
169169- '';
170170- in
168168+ # Link the runner credentials to the work dir
169169+ ln -s "$STATE_DIRECTORY"/{${lib.concatStringsSep "," runnerCredFiles}} "$WORK_DIRECTORY/"
170170+ '';
171171+ in
171172 map (x: "${x} ${escapeShellArgs [ stateDir workDir logsDir ]}") [
172173 "+${unconfigureRunner}" # runs as root
173174 configureRunner
174175 setupWorkDir
175176 ];
176177177177- # If running in ephemeral mode, restart the service on-exit (i.e., successful de-registration of the runner)
178178- # to trigger a fresh registration.
179179- Restart = if cfg.ephemeral then "on-success" else "no";
180180- # If the runner exits with `ReturnCode.RetryableError = 2`, always restart the service:
181181- # https://github.com/actions/runner/blob/40ed7f8/src/Runner.Common/Constants.cs#L146
182182- RestartForceExitStatus = [ 2 ];
178178+ # If running in ephemeral mode, restart the service on-exit (i.e., successful de-registration of the runner)
179179+ # to trigger a fresh registration.
180180+ Restart = if cfg.ephemeral then "on-success" else "no";
181181+ # If the runner exits with `ReturnCode.RetryableError = 2`, always restart the service:
182182+ # https://github.com/actions/runner/blob/40ed7f8/src/Runner.Common/Constants.cs#L146
183183+ RestartForceExitStatus = [ 2 ];
183184184184- # Contains _diag
185185- LogsDirectory = [ systemdDir ];
186186- # Default RUNNER_ROOT which contains ephemeral Runner data
187187- RuntimeDirectory = [ systemdDir ];
188188- # Home of persistent runner data, e.g., credentials
189189- StateDirectory = [ systemdDir ];
190190- StateDirectoryMode = "0700";
191191- WorkingDirectory = workDir;
185185+ # Contains _diag
186186+ LogsDirectory = [ systemdDir ];
187187+ # Default RUNNER_ROOT which contains ephemeral Runner data
188188+ RuntimeDirectory = [ systemdDir ];
189189+ # Home of persistent runner data, e.g., credentials
190190+ StateDirectory = [ systemdDir ];
191191+ StateDirectoryMode = "0700";
192192+ WorkingDirectory = workDir;
192193193193- InaccessiblePaths = [
194194- # Token file path given in the configuration, if visible to the service
195195- "-${cfg.tokenFile}"
196196- # Token file in the state directory
197197- "${stateDir}/${currentConfigTokenFilename}"
198198- ];
194194+ InaccessiblePaths = [
195195+ # Token file path given in the configuration, if visible to the service
196196+ "-${cfg.tokenFile}"
197197+ # Token file in the state directory
198198+ "${stateDir}/${currentConfigTokenFilename}"
199199+ ];
199200200200- KillSignal = "SIGINT";
201201+ KillSignal = "SIGINT";
201202202202- # Hardening (may overlap with DynamicUser=)
203203- # The following options are only for optimizing:
204204- # systemd-analyze security github-runner
205205- AmbientCapabilities = mkBefore [ "" ];
206206- CapabilityBoundingSet = mkBefore [ "" ];
207207- # ProtectClock= adds DeviceAllow=char-rtc r
208208- DeviceAllow = mkBefore [ "" ];
209209- NoNewPrivileges = mkDefault true;
210210- PrivateDevices = mkDefault true;
211211- PrivateMounts = mkDefault true;
212212- PrivateTmp = mkDefault true;
213213- PrivateUsers = mkDefault true;
214214- ProtectClock = mkDefault true;
215215- ProtectControlGroups = mkDefault true;
216216- ProtectHome = mkDefault true;
217217- ProtectHostname = mkDefault true;
218218- ProtectKernelLogs = mkDefault true;
219219- ProtectKernelModules = mkDefault true;
220220- ProtectKernelTunables = mkDefault true;
221221- ProtectSystem = mkDefault "strict";
222222- RemoveIPC = mkDefault true;
223223- RestrictNamespaces = mkDefault true;
224224- RestrictRealtime = mkDefault true;
225225- RestrictSUIDSGID = mkDefault true;
226226- UMask = mkDefault "0066";
227227- ProtectProc = mkDefault "invisible";
228228- SystemCallFilter = mkBefore [
229229- "~@clock"
230230- "~@cpu-emulation"
231231- "~@module"
232232- "~@mount"
233233- "~@obsolete"
234234- "~@raw-io"
235235- "~@reboot"
236236- "~capset"
237237- "~setdomainname"
238238- "~sethostname"
239239- ];
240240- RestrictAddressFamilies = mkBefore [ "AF_INET" "AF_INET6" "AF_UNIX" "AF_NETLINK" ];
203203+ # Hardening (may overlap with DynamicUser=)
204204+ # The following options are only for optimizing:
205205+ # systemd-analyze security github-runner
206206+ AmbientCapabilities = mkBefore [ "" ];
207207+ CapabilityBoundingSet = mkBefore [ "" ];
208208+ # ProtectClock= adds DeviceAllow=char-rtc r
209209+ DeviceAllow = mkBefore [ "" ];
210210+ NoNewPrivileges = mkDefault true;
211211+ PrivateDevices = mkDefault true;
212212+ PrivateMounts = mkDefault true;
213213+ PrivateTmp = mkDefault true;
214214+ PrivateUsers = mkDefault true;
215215+ ProtectClock = mkDefault true;
216216+ ProtectControlGroups = mkDefault true;
217217+ ProtectHome = mkDefault true;
218218+ ProtectHostname = mkDefault true;
219219+ ProtectKernelLogs = mkDefault true;
220220+ ProtectKernelModules = mkDefault true;
221221+ ProtectKernelTunables = mkDefault true;
222222+ ProtectSystem = mkDefault "strict";
223223+ RemoveIPC = mkDefault true;
224224+ RestrictNamespaces = mkDefault true;
225225+ RestrictRealtime = mkDefault true;
226226+ RestrictSUIDSGID = mkDefault true;
227227+ UMask = mkDefault "0066";
228228+ ProtectProc = mkDefault "invisible";
229229+ SystemCallFilter = mkBefore [
230230+ "~@clock"
231231+ "~@cpu-emulation"
232232+ "~@module"
233233+ "~@mount"
234234+ "~@obsolete"
235235+ "~@raw-io"
236236+ "~@reboot"
237237+ "~capset"
238238+ "~setdomainname"
239239+ "~sethostname"
240240+ ];
241241+ RestrictAddressFamilies = mkBefore [ "AF_INET" "AF_INET6" "AF_UNIX" "AF_NETLINK" ];
241242242242- BindPaths = lib.optionals (cfg.workDir != null) [ cfg.workDir ];
243243+ BindPaths = lib.optionals (cfg.workDir != null) [ cfg.workDir ];
243244244244- # Needs network access
245245- PrivateNetwork = mkDefault false;
246246- # Cannot be true due to Node
247247- MemoryDenyWriteExecute = mkDefault false;
245245+ # Needs network access
246246+ PrivateNetwork = mkDefault false;
247247+ # Cannot be true due to Node
248248+ MemoryDenyWriteExecute = mkDefault false;
248249249249- # The more restrictive "pid" option makes `nix` commands in CI emit
250250- # "GC Warning: Couldn't read /proc/stat"
251251- # You may want to set this to "pid" if not using `nix` commands
252252- ProcSubset = mkDefault "all";
253253- # Coverage programs for compiled code such as `cargo-tarpaulin` disable
254254- # ASLR (address space layout randomization) which requires the
255255- # `personality` syscall
256256- # You may want to set this to `true` if not using coverage tooling on
257257- # compiled code
258258- LockPersonality = mkDefault false;
250250+ # The more restrictive "pid" option makes `nix` commands in CI emit
251251+ # "GC Warning: Couldn't read /proc/stat"
252252+ # You may want to set this to "pid" if not using `nix` commands
253253+ ProcSubset = mkDefault "all";
254254+ # Coverage programs for compiled code such as `cargo-tarpaulin` disable
255255+ # ASLR (address space layout randomization) which requires the
256256+ # `personality` syscall
257257+ # You may want to set this to `true` if not using coverage tooling on
258258+ # compiled code
259259+ LockPersonality = mkDefault false;
259260260260- # Note that this has some interactions with the User setting; so you may
261261- # want to consult the systemd docs if using both.
262262- DynamicUser = mkDefault true;
263263- }
261261+ # Note that this has some interactions with the User setting; so you may
262262+ # want to consult the systemd docs if using both.
263263+ DynamicUser = mkDefault true;
264264+ }
264265 (mkIf (cfg.user != null) { User = cfg.user; })
265265- cfg.serviceOverrides];
266266+ cfg.serviceOverrides
267267+ ];
266268}