about summary refs log tree commit diff
path: root/nixos/tests/gitlab.nix
blob: 52fe588930dfc9b1eacb35c842b5c26c8258858f (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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# This test runs gitlab and performs the following tests:
# - Creating users
# - Pushing commits
#   - over the API
#   - over SSH
# - Creating Merge Requests and merging them
# - Opening and closing issues.
# - Downloading repository archives as tar.gz and tar.bz2
# Run with
# [nixpkgs]$ nix-build -A nixosTests.gitlab

{ pkgs, lib, ... }:

let
  inherit (import ./ssh-keys.nix pkgs) snakeOilPrivateKey snakeOilPublicKey;
  initialRootPassword = "notproduction";
  rootProjectId = "2";

  aliceUsername = "alice";
  aliceUserId = "2";
  alicePassword = "R5twyCgU0uXC71wT9BBTCqLs6HFZ7h3L";
  aliceProjectId = "1";
  aliceProjectName = "test-alice";

  bobUsername = "bob";
  bobUserId = "3";
  bobPassword = "XwkkBbl2SiIwabQzgcoaTbhsotijEEtF";
  bobProjectId = "2";
in {
  name = "gitlab";
  meta.maintainers = with lib.maintainers; [ globin yayayayaka ];

  nodes = {
    gitlab = { ... }: {
      imports = [ common/user-account.nix ];

      virtualisation.memorySize = 6144;
      virtualisation.cores = 4;
      virtualisation.useNixStoreImage = true;
      virtualisation.writableStore = false;

      systemd.services.gitlab.serviceConfig.Restart = lib.mkForce "no";
      systemd.services.gitlab-workhorse.serviceConfig.Restart = lib.mkForce "no";
      systemd.services.gitaly.serviceConfig.Restart = lib.mkForce "no";
      systemd.services.gitlab-sidekiq.serviceConfig.Restart = lib.mkForce "no";

      services.nginx = {
        enable = true;
        recommendedProxySettings = true;
        virtualHosts = {
          localhost = {
            locations."/".proxyPass = "http://unix:/run/gitlab/gitlab-workhorse.socket";
          };
        };
      };

      services.openssh.enable = true;

      services.dovecot2 = {
        enable = true;
        enableImap = true;
      };

      systemd.services.gitlab-backup.environment.BACKUP = "dump";

      services.gitlab = {
        enable = true;
        databasePasswordFile = pkgs.writeText "dbPassword" "xo0daiF4";
        initialRootPasswordFile = pkgs.writeText "rootPassword" initialRootPassword;
        smtp.enable = true;
        pages = {
          enable = true;
          settings.pages-domain = "localhost";
        };
        extraConfig = {
          incoming_email = {
            enabled = true;
            mailbox = "inbox";
            address = "alice@localhost";
            user = "alice";
            password = "foobar";
            host = "localhost";
            port = 143;
          };
        };
        secrets = {
          secretFile = pkgs.writeText "secret" "Aig5zaic";
          otpFile = pkgs.writeText "otpsecret" "Riew9mue";
          dbFile = pkgs.writeText "dbsecret" "we2quaeZ";
          jwsFile = pkgs.runCommand "oidcKeyBase" {} "${pkgs.openssl}/bin/openssl genrsa 2048 > $out";
        };

        # reduce memory usage
        sidekiq.concurrency = 1;
        puma.workers = 2;
      };
    };
  };

  testScript = { nodes, ... }:
    let
      auth = pkgs.writeText "auth.json" (builtins.toJSON {
        grant_type = "password";
        username = "root";
        password = initialRootPassword;
      });

      createUserAlice = pkgs.writeText "create-user-alice.json" (builtins.toJSON rec {
        username = aliceUsername;
        name = username;
        email = "alice@localhost";
        password = alicePassword;
        skip_confirmation = true;
      });

      createUserBob = pkgs.writeText "create-user-bob.json" (builtins.toJSON rec {
        username = bobUsername;
        name = username;
        email = "bob@localhost";
        password = bobPassword;
        skip_confirmation = true;
      });

      aliceAuth = pkgs.writeText "alice-auth.json" (builtins.toJSON {
        grant_type = "password";
        username = aliceUsername;
        password = alicePassword;
      });

      bobAuth = pkgs.writeText "bob-auth.json" (builtins.toJSON {
        grant_type = "password";
        username = bobUsername;
        password = bobPassword;
      });

      aliceAddSSHKey = pkgs.writeText "alice-add-ssh-key.json" (builtins.toJSON {
        id = aliceUserId;
        title = "snakeoil@nixos";
        key = snakeOilPublicKey;
      });

      createProjectAlice = pkgs.writeText "create-project-alice.json" (builtins.toJSON {
        name = aliceProjectName;
        visibility = "public";
      });

      putFile = pkgs.writeText "put-file.json" (builtins.toJSON {
        branch = "master";
        author_email = "author@example.com";
        author_name = "Firstname Lastname";
        content = "some content";
        commit_message = "create a new file";
      });

      mergeRequest = pkgs.writeText "merge-request.json" (builtins.toJSON {
        id = bobProjectId;
        target_project_id = aliceProjectId;
        source_branch = "master";
        target_branch = "master";
        title = "Add some other file";
      });

      newIssue = pkgs.writeText "new-issue.json" (builtins.toJSON {
        title = "useful issue title";
      });

      closeIssue = pkgs.writeText "close-issue.json" (builtins.toJSON {
        issue_iid = 1;
        state_event = "close";
      });

      # Wait for all GitLab services to be fully started.
      waitForServices = ''
        gitlab.wait_for_unit("gitaly.service")
        gitlab.wait_for_unit("gitlab-workhorse.service")
        gitlab.wait_for_unit("gitlab-mailroom.service")
        gitlab.wait_for_unit("gitlab.service")
        gitlab.wait_for_unit("gitlab-pages.service")
        gitlab.wait_for_unit("gitlab-sidekiq.service")
        gitlab.wait_for_file("${nodes.gitlab.services.gitlab.statePath}/tmp/sockets/gitlab.socket")
        gitlab.wait_until_succeeds("curl -sSf http://gitlab/users/sign_in")
      '';

      # The actual test of GitLab. Only push data to GitLab if
      # `doSetup` is is true.
      test = doSetup: ''
        GIT_SSH_COMMAND = "ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/dev/null"

        gitlab.succeed(
            "curl -isSf http://gitlab | grep -i location | grep http://gitlab/users/sign_in"
        )
        gitlab.succeed(
            "${pkgs.sudo}/bin/sudo -u gitlab -H gitlab-rake gitlab:check 1>&2"
        )
        gitlab.succeed(
            "echo \"Authorization: Bearer $(curl -X POST -H 'Content-Type: application/json' -d @${auth} http://gitlab/oauth/token | ${pkgs.jq}/bin/jq -r '.access_token')\" >/tmp/headers"
        )
      '' + lib.optionalString doSetup ''
        with subtest("Create user Alice"):
            gitlab.succeed(
                """[ "$(curl -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' -H @/tmp/headers -d @${createUserAlice} http://gitlab/api/v4/users)" = "201" ]"""
            )
            gitlab.succeed(
                "echo \"Authorization: Bearer $(curl -X POST -H 'Content-Type: application/json' -d @${aliceAuth} http://gitlab/oauth/token | ${pkgs.jq}/bin/jq -r '.access_token')\" >/tmp/headers-alice"
            )

        with subtest("Create user Bob"):
            gitlab.succeed(
                """ [ "$(curl -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' -H @/tmp/headers -d @${createUserBob} http://gitlab/api/v4/users)" = "201" ]"""
            )
            gitlab.succeed(
                "echo \"Authorization: Bearer $(curl -X POST -H 'Content-Type: application/json' -d @${bobAuth} http://gitlab/oauth/token | ${pkgs.jq}/bin/jq -r '.access_token')\" >/tmp/headers-bob"
            )

        with subtest("Setup Git and SSH for Alice"):
            gitlab.succeed("git config --global user.name Alice")
            gitlab.succeed("git config --global user.email alice@nixos.invalid")
            gitlab.succeed("mkdir -m 700 /root/.ssh")
            gitlab.succeed("cat ${snakeOilPrivateKey} > /root/.ssh/id_ecdsa")
            gitlab.succeed("chmod 600 /root/.ssh/id_ecdsa")
            gitlab.succeed(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X POST \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-alice -d @${aliceAddSSHKey} \
                    http://gitlab/api/v4/user/keys)" = "201" ]
                """
            )

        with subtest("Create a new repository"):
            # Alice creates a new repository
            gitlab.succeed(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X POST \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-alice \
                    -d @${createProjectAlice} \
                    http://gitlab/api/v4/projects)" = "201" ]
                """
            )

            # Alice commits an initial commit
            gitlab.succeed(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X POST \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-alice \
                    -d @${putFile} \
                    http://gitlab/api/v4/projects/${aliceProjectId}/repository/files/some-file.txt)" = "201" ]"""
            )

        with subtest("git clone over HTTP"):
            gitlab.succeed(
                """git clone http://gitlab/alice/${aliceProjectName}.git clone-via-http""",
                timeout=15
            )

        with subtest("Push a commit via SSH"):
            gitlab.succeed(
                f"""GIT_SSH_COMMAND="{GIT_SSH_COMMAND}" git clone gitlab@gitlab:alice/${aliceProjectName}.git""",
                timeout=15
            )
            gitlab.succeed(
                """echo "a commit sent over ssh" > ${aliceProjectName}/ssh.txt"""
            )
            gitlab.succeed(
                """
                cd ${aliceProjectName} || exit 1
                git add .
                """
            )
            gitlab.succeed(
                """
                cd ${aliceProjectName} || exit 1
                git commit -m "Add a commit to be sent over ssh"
                """
            )
            gitlab.succeed(
                f"""
                cd ${aliceProjectName} || exit 1
                GIT_SSH_COMMAND="{GIT_SSH_COMMAND}" git push --set-upstream origin master
                """,
                timeout=15
            )

        with subtest("Fork a project"):
            # Bob forks Alice's project
            gitlab.succeed(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X POST \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-bob \
                    http://gitlab/api/v4/projects/${aliceProjectId}/fork)" = "201" ]
                """
            )

            # Bob creates a commit
            gitlab.wait_until_succeeds(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X POST \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-bob \
                    -d @${putFile} \
                    http://gitlab/api/v4/projects/${bobProjectId}/repository/files/some-other-file.txt)" = "201" ]
                """
            )

        with subtest("Create a Merge Request"):
            # Bob opens a merge request against Alice's repository
            gitlab.wait_until_succeeds(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X POST \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-bob \
                    -d @${mergeRequest} \
                    http://gitlab/api/v4/projects/${bobProjectId}/merge_requests)" = "201" ]
                """
            )

            # Alice merges the MR
            gitlab.wait_until_succeeds(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X PUT \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-alice \
                    -d @${mergeRequest} \
                    http://gitlab/api/v4/projects/${aliceProjectId}/merge_requests/1/merge)" = "200" ]
                """
            )

        with subtest("Create an Issue"):
            # Bob opens an issue on Alice's repository
            gitlab.succeed(
                """[ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X POST \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-bob \
                    -d @${newIssue} \
                    http://gitlab/api/v4/projects/${aliceProjectId}/issues)" = "201" ]
                """
            )

            # Alice closes the issue
            gitlab.wait_until_succeeds(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -X PUT \
                    -H 'Content-Type: application/json' \
                    -H @/tmp/headers-alice -d @${closeIssue} http://gitlab/api/v4/projects/${aliceProjectId}/issues/1)" = "200" ]
                """
            )
      '' + ''
        with subtest("Download archive.tar.gz"):
            gitlab.succeed(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -H @/tmp/headers-alice \
                    http://gitlab/api/v4/projects/${aliceProjectId}/repository/archive.tar.gz)" = "200" ]
                """
            )
            gitlab.succeed(
                """
                curl \
                    -H @/tmp/headers-alice \
                    http://gitlab/api/v4/projects/${aliceProjectId}/repository/archive.tar.gz > /tmp/archive.tar.gz
                """
            )
            gitlab.succeed("test -s /tmp/archive.tar.gz")

        with subtest("Download archive.tar.bz2"):
            gitlab.succeed(
                """
                [ "$(curl \
                    -o /dev/null \
                    -w '%{http_code}' \
                    -H @/tmp/headers-alice \
                    http://gitlab/api/v4/projects/${aliceProjectId}/repository/archive.tar.bz2)" = "200" ]
                """
            )
            gitlab.succeed(
                """
                curl \
                    -H @/tmp/headers-alice \
                    http://gitlab/api/v4/projects/${aliceProjectId}/repository/archive.tar.bz2 > /tmp/archive.tar.bz2
                """
            )
            gitlab.succeed("test -s /tmp/archive.tar.bz2")
      '';

  in ''
      gitlab.start()
    ''
    + waitForServices
    + test true
    + ''
      gitlab.systemctl("start gitlab-backup.service")
      gitlab.wait_for_unit("gitlab-backup.service")
      gitlab.wait_for_file("${nodes.gitlab.services.gitlab.statePath}/backup/dump_gitlab_backup.tar")
      gitlab.systemctl("stop postgresql.service gitlab-config.service gitlab.target")
      gitlab.succeed(
          "find ${nodes.gitlab.services.gitlab.statePath} -mindepth 1 -maxdepth 1 -not -name backup -execdir rm -r {} +"
      )
      gitlab.succeed("systemd-tmpfiles --create")
      gitlab.succeed("rm -rf ${nodes.gitlab.services.postgresql.dataDir}")
      gitlab.systemctl("start gitlab-config.service gitaly.service gitlab-postgresql.service")
      gitlab.wait_for_file("${nodes.gitlab.services.gitlab.statePath}/tmp/sockets/gitaly.socket")
      gitlab.succeed(
          "sudo -u gitlab -H gitlab-rake gitlab:backup:restore RAILS_ENV=production BACKUP=dump force=yes"
      )
      gitlab.systemctl("start gitlab.target")
    ''
    + waitForServices
    + test false;
}