diff options
Diffstat (limited to '')
50 files changed, 3133 insertions, 140 deletions
diff --git a/tests/README.md b/tests/README.md index 7811f32..aaa76b4 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,6 +1,6 @@ # Tests This directory tree mirrors the modules defined in the -[modules](%60../modules/%60) directory. Each module should have at least +[modules](%60../modules/%60) directory. Each module should have at least one test in the mirrored directory, effectively replacing the module's `module.nix` file. diff --git a/tests/by-name/at/atuin-sync/test.nix b/tests/by-name/at/atuin-sync/test.nix new file mode 100644 index 0000000..8645964 --- /dev/null +++ b/tests/by-name/at/atuin-sync/test.nix @@ -0,0 +1,157 @@ +{ + packageSets, + sources, + vhack, + ... +}: let + pkgs = packageSets.stable; +in + vhack.runTest { + name = "atuin-sync"; + + serverDomains = [ + {server = "atuin-sync.server";} + ]; + + nodes = let + atuinSession = "01969ec6b8d07e30a9d2df0911fbfe2a"; + atuin = sources.turtle.packages."${pkgs.stdenv.hostPlatform.system}".default; + in { + server = {config, ...}: { + vhack = { + persist.enable = true; + nginx.enable = true; + atuin-sync = { + enable = true; + fqdn = "atuin-sync.server"; + }; + }; + }; + + client1 = {config, ...}: { + environment.sessionVariables.ATUIN_SESSION = atuinSession; + + environment.systemPackages = [ + atuin + pkgs.sqlite-interactive + ]; + }; + client2 = {config, ...}: { + environment.sessionVariables.ATUIN_SESSION = atuinSession; + + environment.systemPackages = [ + atuin + pkgs.sqlite-interactive + ]; + }; + }; + + services = [ + {server = "turtle.service";} + ]; + + ports = [ + {server = 443;} + ]; + + testScript = {nodes, ...}: let + mkSyncConfig = pkgs.writeShellScript "register-atuin-sync-account" '' + mkdir --parents ~/.config/turtle/ + + cat << EOF > ~/.config/turtle/config.toml + + [sync] + address = "https://atuin-sync.server" + user_id_path = "${pkgs.writeText "user-id" "019eb88a-6b51-7e52-b12c-7d30bd8e5928"}" + encryption_key_path = "${pkgs.writeText "encryption-key" "3AAgbWsDzL7M00/Mq0LMjsyOCy3MnsypBsyQzKbMywNGzNnMrUBozIINAxdbIiDMhQ=="}" + EOF + ''; + + runCommandAndRecordInTurtle = pkgs.writeShellScript "run-command-and-record-in-atuin" '' + # SPDX-SnippetBegin + # SPDX-SnippetCopyrightText: 2023 mentalisttraceur (https://github.com/mentalisttraceur) + # Source: https://github.com/atuinsh/atuin/issues/1188#issuecomment-1698354107 + run_and_record_in_atuin() + { + local id + local status + local escaped_command="$(printf '%q ' "$@")" + id="$(turtle history start -- "$escaped_command")" + "$@" + status=$? + turtle history end --exit $status "$id" + return $status + } + # SPDX-SnippetEnd + + run_and_record_in_atuin "$@" + ''; + in + # Python + '' + # Wait for the server to acquire the acme certificate + client1.wait_until_succeeds("curl https://atuin-sync.server") + + with subtest("Setup client syncing"): + for client in [client1, client2]: + client.succeed("${mkSyncConfig}") + + with subtest("Start turtle daemon"): + for client in [client1, client2]: + client.succeed("systemd-run turtle-daemon start") + + for client in [client1, client2]: + client.wait_until_succeeds("turtle daemon status") + + with subtest("Can generate shell history"): + client1.succeed("${runCommandAndRecordInTurtle} echo hi - client 1") + client2.succeed("${runCommandAndRecordInTurtle} echo hi - client 2") + + with subtest("Can sync"): + for client in [client1, client2]: + client.succeed("turtle sync perform") + client1.succeed("turtle sync perform") + + with subtest("Have correct tasks"): + hist1 = client1.succeed("turtle history list --cmd-only").strip().split('\n') + hist2 = client2.succeed("turtle history list --cmd-only").strip().split('\n') + + hist1.sort() + hist2.sort() + + canonicalHistory = [ + "echo hi - client 1", + "echo hi - client 2" + ] + + assert hist1 == hist2, f"The clients don't have the same amount of history items, client1: '{hist1}', client2: '{hist2}'" + assert hist1 == canonicalHistory, f"The history is not correct: '{hist1}' vs. '{canonicalHistory}'" + + with subtest("Can sync again"): + client1.succeed("${runCommandAndRecordInTurtle} echo second try - client 1") + client2.succeed("${runCommandAndRecordInTurtle} echo second try - client 2") + + for client in [client1, client2]: + client.succeed("turtle sync perform") + client1.succeed("turtle sync perform") + + hist1 = client1.succeed("turtle history list --cmd-only").strip().split('\n') + hist2 = client2.succeed("turtle history list --cmd-only").strip().split('\n') + + hist1.sort() + hist2.sort() + + canonicalHistory = [ + # The old history + "echo hi - client 1", + "echo hi - client 2", + + # Our newly added history entries + "echo second try - client 1", + "echo second try - client 2" + ] + + assert hist1 == hist2, f"The clients don't have the same amount of history items, client1: '{hist1}', client2: '{hist2}'" + assert hist1 == canonicalHistory, f"The history is not correct, got: '{hist1}', expected: '{canonicalHistory}'" + ''; + } diff --git a/tests/by-name/ba/back/test.nix b/tests/by-name/ba/back/test.nix index 63f2837..ed297ec 100644 --- a/tests/by-name/ba/back/test.nix +++ b/tests/by-name/ba/back/test.nix @@ -1,121 +1,182 @@ { - nixos-lib, - pkgsUnstable, - nixpkgs-unstable, - vhackPackages, - pkgs, - extraModules, - nixLib, + packageSets, + vhack, ... }: let - gitRepoPath = "/srv/test/repo"; + pkgs = packageSets.stable; domain = "server"; -in - nixos-lib.runTest { - hostPkgs = pkgs; # the Nixpkgs package set used outside the VMs + sshKeys = + import ../../gi/git-server/ssh_keys.nix {inherit pkgs;}; + + gitoliteAdminConfSnippet = pkgs.writeText "gitolite-admin-conf-snippet" '' + repo CREATOR/[a-zA-Z0-9].* + C = @all + RW+ = CREATOR + RW = WRITERS + R = READERS + option user-configs = cgit\.owner cgit\.desc cgit\.section cgit\.homepage + ''; +in + vhack.runTest { name = "back"; - node = { - specialArgs = {inherit pkgsUnstable vhackPackages nixpkgs-unstable nixLib;}; + ignore = "We are not using back currently."; - # Use the nixpkgs as constructed by the `nixpkgs.*` options - pkgs = null; - }; + serverDomains = [ + {server = "git.${domain}";} + {server = "issues.${domain}";} + ]; nodes = { server = {config, ...}: { - environment.systemPackages = [pkgs.git pkgs.git-bug pkgs.gawk]; - - imports = - extraModules - ++ [ - ../../../../modules - ]; + environment.systemPackages = [pkgs.git]; vhack = { + persist.enable = true; + openssh.enable = true; nginx = { enable = true; - selfsign = true; }; git-server = { enable = true; + domain = "git.${domain}"; + gitolite.adminPubkey = sshKeys.admin.pub; }; - back = { + git-back = { enable = true; - repositories = { - "${gitRepoPath}" = { - enable = true; - domain = "${domain}"; - port = 9220; - }; - }; + domain = "issues.${domain}"; }; }; }; - client = {...}: { - environment.systemPackages = [pkgs.curl]; + client = {nodes, ...}: { + environment.systemPackages = [pkgs.git pkgs.curl pkgs.git-bug pkgs.gawk]; + programs.ssh.extraConfig = '' + Host * + UserKnownHostsFile /dev/null + StrictHostKeyChecking no + # there's nobody around that can input password + PreferredAuthentications publickey + ''; + users.users.alice = {isNormalUser = true;}; }; }; + services = [ + {server = "gitolite-init.service";} + {server = "sshd.service";} + ]; + testScript = {nodes, ...}: - /* - python - */ + # Python '' - start_all() + with subtest("can setup ssh keys on client"): + client.succeed( + "mkdir -p ~root/.ssh", + "cp ${sshKeys.admin.priv} ~root/.ssh/id_ed25519", + "chmod 600 ~root/.ssh/id_ed25519", + ) + client.succeed( + "sudo -u alice mkdir -p ~alice/.ssh", + "sudo -u alice cp ${sshKeys.alice.priv} ~alice/.ssh/id_ed25519", + "sudo -u alice chmod 600 ~alice/.ssh/id_ed25519", + ) - with subtest("can setup git-bug issues on server"): - server.succeed("${pkgs.writeShellScript "setup-git-repo" '' - set -ex + with subtest("gitolite server starts"): + client.succeed("ssh -n git@git.${domain} info") - mkdir --parents "${gitRepoPath}" - cd "${gitRepoPath}" + with subtest("admin can clone and configure gitolite-admin.git"): + server.succeed("sudo -u git ${pkgs.writeShellScript "delete_main_branch_on_server" '' + set -xe + + cd ~git/repositories/gitolite-admin.git + git branch --move --force main master + ''}") + client.succeed("${pkgs.writeShellScript "setup-gitolite-admin.git" '' + set -xe - git init + git clone git@git.${domain}:gitolite-admin.git + git config --global user.name 'System Administrator' + git config --global user.email root\@domain.example - git bug user create --avatar "" --email "test@email.org" --name "test user" --non-interactive + cp ${sshKeys.alice.pub} gitolite-admin/keydir/alice.pub - git bug add \ + (cd gitolite-admin && git add . && git commit -m 'Add keys for alice' && git push -u origin master) + cat ${gitoliteAdminConfSnippet} >> gitolite-admin/conf/gitolite.conf + (cd gitolite-admin && git add . && git commit -m 'Add support for wild repos' && git push) + ''}") + + with subtest("alice can create a repo"): + client.succeed("sudo -u alice ${pkgs.writeShellScript "alice-create-repo" '' + set -xe + + mkdir --parents ./alice/repo1 && cd alice/repo1; + + git init --initial-branch main + echo "# Alice's Repo" > README.md + git add README.md + git -c user.name=Alice -c user.email=alice@domain.example commit -m 'Add readme' + + git remote add origin git@git.${domain}:alice/repo1.git + git push --set-upstream origin main + ''}") + + with subtest("can setup git-bug issues in alice/repo1"): + client.succeed("sudo -u alice ${pkgs.writeShellScript "setup-git-repo" '' + set -ex + + cd alice/repo1 + + git bug user new --avatar "" --email "alice@server.org" --name "alice" --non-interactive + + git bug bug new \ --title "Some bug title" \ --message "A long description of the bug. Probably has some code segments, maybe even *markdown* mark_up_ or other things" \ --non-interactive - git bug add \ + git bug bug new \ --title "Second bug title" \ --message "" \ --non-interactive - git bug add \ + git bug bug new \ --title "Third bug title" \ --message "" \ --non-interactive - git bug select "$(git bug ls --format plain | awk '{print $1}' | head -n 1)" + git bug bug select "$(git bug bug --format plain | awk '{print $1}' | head -n 1)" + + git bug bug comment new --message "Some comment message" --non-interactive + git bug bug comment new --message "Second comment message" --non-interactive - git bug comment add --message "Some comment message" --non-interactive - git bug comment add --message "Second comment message" --non-interactive + # TODO: This should use `git bug push`, but their ssh implementation is just + # too special to work in a VM test <2025-03-08> + git push origin +refs/bugs/* + git push origin +refs/identities/* - # NOTE(@bpeetz): Currently, the `back` module assumes that the git user can write - # to the repository, as such we need to provide write access here <2024-12-24> - chown --recursive git:git "${gitRepoPath}" + ssh git@git.${domain} -- config alice/repo1 --add cgit.owner Alice + ssh git@git.${domain} -- perms alice/repo1 + READERS @all ''}") with subtest("back server starts"): - server.wait_for_unit("${builtins.replaceStrings ["/"] ["_"] "back-${domain}.service"}") + server.wait_for_unit("back.service") with subtest("client can access the server"): client.succeed("${pkgs.writeShellScript "curl-back" '' set -xe - curl --insecure --silent --fail --show-error "https://${domain}/issues/open" --output /root/issues.html - - grep -- '- 2 comments' /root/issues.html + curl --fail --show-error "https://issues.${domain}/alice/repo1/issues/?query=status:open" --output /root/issues.html grep -- 'Second bug title' /root/issues.html - ''}") + + curl --fail --show-error "https://issues.${domain}/" --output /root/repos.html + grep -- 'repo' /root/repos.html + grep -- "<No description>" /root/repos.html + grep -- '<span class="user-name">Alice</span>' /root/repos.html + ''} >&2") client.copy_from_vm("/root/issues.html", ""); + client.copy_from_vm("/root/repos.html", ""); ''; } diff --git a/tests/by-name/dn/dns/test.nix b/tests/by-name/dn/dns/test.nix new file mode 100644 index 0000000..cf1d67b --- /dev/null +++ b/tests/by-name/dn/dns/test.nix @@ -0,0 +1,131 @@ +# Inspired by this file: /nixpkgs/nixos/tests/nsd.nix +{ + packageSets, + vhack, + ... +}: let + pkgs = packageSets.stable; + + common = {...}: { + networking.firewall.enable = false; + networking.dhcpcd.enable = false; + }; + + mkClient = version: { + lib, + nodes, + ... + }: let + name = + if version == "ipv4" + then "primaryIPAddress" + else if version == "ipv6" + then "primaryIPv6Address" + else builtins.throw "Not a valid ip version: ${version}"; + in { + environment.systemPackages = [pkgs.dig pkgs.dig.dnsutils]; + + imports = [common]; + networking.nameservers = lib.mkForce [ + nodes.server.networking.${name} + ]; + }; +in + vhack.runTest { + name = "dns"; + + # Problem: The `runTest` function wants to setup TLS certificates for everything and + # sets up it's own dns server for that. That unfortunately conflicts with our test + # here. But we are implicitly testing dns anyhow with the other tests, so this test + # is not really necessary. + ignore = true; + + nodes = { + server = { + config, + lib, + ... + }: { + imports = [ + common + ]; + + vhack = { + dns = { + enable = true; + interfaces = [ + config.networking.primaryIPAddress + config.networking.primaryIPv6Address + ]; + zones = { + "example.com" = { + SOA = { + nameServer = "ns"; + adminEmail = "admin@example.com"; + serial = 2024012301; + }; + + useOrigin = false; + NS = [ + "ns.example.com." + ]; + + subdomains = { + ns = { + A = ["192.168.1.3"]; + }; + ipv4 = { + A = ["1.2.3.4"]; + }; + ipv6 = { + AAAA = ["dead:beef::1"]; + }; + openpgpkey = { + TXT = ["Hi!"]; + }; + }; + }; + }; + }; + }; + }; + + clientV4 = mkClient "ipv4"; + clientV6 = mkClient "ipv6"; + }; + + services = [ + {clientV4 = "network.target";} + {clientV6 = "network.target";} + {server = "nsd.service";} + ]; + + ports = [ + {server = 53;} + ]; + + testScript = {nodes, ...}: + /* + python + */ + '' + def assert_host(ipVersion, dnsRecordType, dnsQuery, expected): + self = clientV4 if ipVersion == 4 else clientV6 + out = self.succeed(f"host -{ipVersion} -t {dnsRecordType} {dnsQuery}").rstrip() + self.log(f"output: {out}") + import re + assert re.search(expected, out), f"DNS IPv{ipVersion} dnsQuery on {dnsQuery} gave '{out}' instead of '{expected}'" + + + for ipv in 4, 6: + with subtest(f"IPv{ipv}"): + assert_host(ipv, "a", "example.com", "has no [^ ]+ record") + assert_host(ipv, "aaaa", "example.com", "has no [^ ]+ record") + + assert_host(ipv, "soa", "example.com", "SOA.*?admin\\.example\\.com") + assert_host(ipv, "a", "ipv4.example.com", "address 1.2.3.4$") + assert_host(ipv, "aaaa", "ipv6.example.com", "address dead:beef::1$") + + assert_host(ipv, "txt", "openpgpkey.example.com", "descriptive text \"Hi!\"$") + ''; + } diff --git a/tests/by-name/gi/git-server/test.nix b/tests/by-name/gi/git-server/test.nix index 5cd8c33..a0aeb35 100644 --- a/tests/by-name/gi/git-server/test.nix +++ b/tests/by-name/gi/git-server/test.nix @@ -1,12 +1,10 @@ { - nixos-lib, - pkgsUnstable, - nixpkgs-unstable, - pkgs, - extraModules, - nixLib, + packageSets, + vhack, ... }: let + pkgs = packageSets.stable; + sshKeys = import ./ssh_keys.nix {inherit pkgs;}; @@ -35,39 +33,24 @@ option user-configs = cgit\.owner cgit\.desc cgit\.section cgit\.homepage ''; - expectedHtmlReadme = pkgs.writeText "expectedHtmlReadme" '' - <h1>Alice's Repo</h1> - ''; expectedMdReadme = pkgs.writeText "expectedMdReadme" '' # Alice's Repo ''; in - nixos-lib.runTest { - hostPkgs = pkgs; # the Nixpkgs package set used outside the VMs - + vhack.runTest { name = "git-server"; - node = { - specialArgs = {inherit pkgsUnstable nixpkgs-unstable nixLib;}; - - # Use the nixpkgs as constructed by the `nixpkgs.*` options - pkgs = null; - }; + serverDomains = [ + {server = gitServerDomain;} + ]; nodes = { server = {config, ...}: { - imports = - extraModules - ++ [ - ../../../../modules - ]; - vhack = { persist.enable = true; openssh.enable = true; nginx = { enable = true; - selfsign = true; }; git-server = { enable = true; @@ -77,7 +60,7 @@ in }; }; - client = {...}: { + client = { environment.systemPackages = [pkgs.git]; programs.ssh.extraConfig = '' Host * @@ -91,13 +74,14 @@ in }; }; - testScript = {nodes, ...}: - /* - python - */ - '' - start_all() + services = [ + {server = "gitolite-init.service";} + {server = "sshd.service";} + ]; + testScript = {...}: + # Python + '' with subtest("can setup ssh keys on client"): client.succeed( "mkdir -p ~root/.ssh", @@ -116,12 +100,16 @@ in ) with subtest("gitolite server starts"): - server.wait_for_unit("gitolite-init.service") - server.wait_for_unit("sshd.service") client.succeed("ssh -n git@server info") with subtest("admin can clone and configure gitolite-admin.git"): + server.succeed("sudo -u git ${pkgs.writeShellScript "delete_main_branch_on_server" '' + set -xe + + cd ~git/repositories/gitolite-admin.git + git branch --move --force main master + ''}") client.succeed("${pkgs.writeShellScript "setup-gitolite-admin.git" '' set -xe @@ -132,12 +120,9 @@ in cp ${sshKeys.alice.pub} gitolite-admin/keydir/alice.pub cp ${sshKeys.bob.pub} gitolite-admin/keydir/bob.pub - (cd gitolite-admin && git switch -c master && git branch -D main) - (cd gitolite-admin && git add . && git commit -m 'Add keys for alice, bob' && git push -u origin master) cat ${gitoliteAdminConfSnippet} >> gitolite-admin/conf/gitolite.conf (cd gitolite-admin && git add . && git commit -m 'Add support for wild repos' && git push) - (cd gitolite-admin && git push -d origin main) ''}") server.succeed("${pkgs.writeShellScript "verify gitolite-admin.conf" '' @@ -202,7 +187,7 @@ in cd ~bob # Disable ssl verification, as the certs are self-signed - git -c http.sslVerify=false clone https://server/alice/alice-project.git + git -c http.sslVerify=false clone https://server/alice/alice-project ''}") with subtest("Alice can change settings in her repo"): @@ -221,15 +206,13 @@ in } ''}") + with subtest("Bob can see alice's README"): + client.succeed("sudo -u bob ${pkgs.writeShellScript "bob-alice-readme" '' + set -xe - # He can't see the readme (FIXME: find out why this does not work. <2024-08-13> ) - # with subtest("Bob can see alice's README"): - # client.succeed("sudo -u bob ${pkgs.writeShellScript "bob-alice-readme" '' - # set -xe - # - # curl --insecure --silent --fail --show-error 'https://server/alice/alice-project/about' > readme.html - # cat readme.html - # diff --side-by-side ${expectedHtmlReadme} readme.html - # ''}") + curl --fail --show-error 'https://server/alice/alice-project/about/' > readme.html + grep 'alice-project - My nice project.' ./readme.html + grep 'My nice project.' ./readme.html + ''}") ''; } diff --git a/tests/by-name/mo/monitoring-basic/test.nix b/tests/by-name/mo/monitoring-basic/test.nix new file mode 100644 index 0000000..2983085 --- /dev/null +++ b/tests/by-name/mo/monitoring-basic/test.nix @@ -0,0 +1,57 @@ +{vhack, ...}: let + grafanaDomain = "grafana.server.org"; +in + vhack.runTest { + name = "monitoring"; + + serverDomains = [ + {server = grafanaDomain;} + ]; + + nodes = { + client = {}; + + server = {config, ...}: { + # there are no SMART available disk in the VM, so this service always fails. + systemd.services."smartd".enable = false; + + age.identityPaths = ["${../../../common/email/hostKey}"]; + + vhack = { + monitoring = { + grafana = { + enable = true; + contactPoints = ["me@example.com"]; + fqdn = grafanaDomain; + + adminPassword = ../../../common/email/dkim/alice.com/private.age; + secretKey = ../../../common/email/dkim/bob.com/private.age; + + # TODO: Add a test for that <2026-07-19> + smtp = null; + }; + + loki = { + enable = true; + }; + + prometheus = { + enable = true; + }; + }; + }; + }; + }; + + services = [ + {server = "grafana.service";} + {server = "fluent-bit.service";} + {server = "loki.service";} + ]; + + testScript = {...}: + # Python + '' + # TODO: We should probably query some of the prometheus metrics here? <2026-07-19> + ''; + } diff --git a/tests/by-name/mo/monitoring-federation/test.nix b/tests/by-name/mo/monitoring-federation/test.nix new file mode 100644 index 0000000..1cb2de1 --- /dev/null +++ b/tests/by-name/mo/monitoring-federation/test.nix @@ -0,0 +1,92 @@ +{ + packageSets, + vhack, + ... +}: let + pkgs = packageSets.stable; + + prometheusMain = "prometheus.server2.server.org"; + remoteWriteTo = { + url = "https://${prometheusMain}"; + }; + promPort = 3001; +in + vhack.runTest { + name = "monitoring"; + + serverDomains = [ + {server2 = prometheusMain;} + ]; + + nodes = { + server2 = {config, ...}: { + environment.systemPackages = [ + pkgs.curl + ]; + + vhack = { + monitoring = { + prometheus = { + enable = true; + port = promPort; + remoteWriteReceiver = prometheusMain; + }; + }; + }; + }; + server3 = {config, ...}: { + vhack = { + monitoring = { + prometheus = { + enable = true; + port = promPort; + inherit remoteWriteTo; + }; + }; + }; + }; + server4 = {config, ...}: { + vhack = { + monitoring = { + prometheus = { + enable = true; + port = promPort; + inherit remoteWriteTo; + }; + }; + }; + }; + }; + + services = [ + {server2 = "prometheus.service";} + {server3 = "prometheus.service";} + {server4 = "prometheus.service";} + ]; + + testScript = {...}: + # Python + '' + import json, time + + # Give the Prometheus servers some time to generate metrics and sync with the main + # one. + time.sleep(15) + + metrics = server2.succeed("${pkgs.writeShellScript "query-metrics" '' + curl --silent \ + http://127.0.0.1:${toString promPort}/api/v1/query?query="go_gc_cleanups_queued_cleanups_total" + ''}") + + metrics = json.loads(metrics) + + hosts = [] + for result in metrics["data"]["result"]: + server2.log(json.dumps(result,indent=4)) + hosts.append(result["metric"]["hostname"]) + + hosts.sort() + + assert hosts == ["server2", "server3", "server4"], f"Not all hosts used the remote write (got {hosts})" + ''; + } diff --git a/tests/by-name/ro/rocie/secrets/login.age b/tests/by-name/ro/rocie/secrets/login.age new file mode 100644 index 0000000..33d63be --- /dev/null +++ b/tests/by-name/ro/rocie/secrets/login.age @@ -0,0 +1,16 @@ +-----BEGIN AGE ENCRYPTED FILE----- +YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSAzMWE5dTBiU0hDUC9jUi93 +Y1phYllHRk9YSHBzUGQ2YmF5ZC9ydXNGV0JrClRpTjZZUHZ5MEFFa0VrYVVhTkE2 +eCtSaEU1YVlhNjFNYlRRYzNCdjhYRWMKLT4gWDI1NTE5IDUrZWdDUmpQcFBOcE0x +UE5QRDR5NXVXUHdQOVk3UGV1S3lCc0pUQmZIZ00KUldVSVF3TzB0cHFVaDZuNlZR +b2FoT0lVSTZydHFTNHhnQ3U0NGdSR1k1MAotPiBzc2gtZWQyNTUxOSBSc2dXcFEg +dldGZU15UXgrRTMxRkp2MEVKUllWQ3VFdnJDMnM4OS8wc202WW9lNW5BYwpPWjV0 +cmNuaDlPZndtUVVScm5TaGlvVUhHa0JiN1MvbDhCTTUxYzNhM3RRCi0+IDxXeEhv +cC1ncmVhc2UKM3N5OHRLNTJEY1NIeGlWYm9yR096Y1NpSlVOM1lYQk9jOHkxU3N2 +K2c3QitDYnR6QTJOOWczV0xBa2dEUE1PTQpYU2Z1elZwRzU0Tm1RVDE2VWVqekUw +bFROLzU0c2NNTXYwL2N5QkxTaGtXUWxKVVF6SE0KLS0tIGlYMHIvUkJpZUR0SHo4 +cldLSTdnbU90SGJTcGZGaHkyOTZON0hka3BLdlEKeP4nHmKWvJfqgEXuiLBMzldi +n1qIsnlF3IU1EA0abJg/RK1BFwWlx4wBlLmViw6UTL+VEw8lv23PuZl2t7UtXVzQ +smXDapW8nInNmTaElBPdwJ072/dD0Ly+KF95Qr0FDDv+jlKG/D/Mw+xD4jvuJHSo +2HQnPF6MLTjCxpyPPggleWgKrBQggHBjm/pHtOKmPC5qfp+LAjmQoJXny/0X6cA= +-----END AGE ENCRYPTED FILE----- diff --git a/tests/by-name/ro/rocie/test.nix b/tests/by-name/ro/rocie/test.nix new file mode 100644 index 0000000..d257e48 --- /dev/null +++ b/tests/by-name/ro/rocie/test.nix @@ -0,0 +1,45 @@ +{vhack, ...}: +vhack.runTest { + name = "rocie"; + + # TODO: Re-active once the new web interface lands. <2026-11-26> + ignore = true; + + serverDomains = [ + {server = "rocie.server";} + ]; + + nodes = { + server = {config, ...}: { + age.identityPaths = ["${../../../common/email/hostKey}"]; + + vhack = { + persist.enable = true; + nginx.enable = true; + rocie = { + enable = true; + domain = "rocie.server"; + loginSecret = ./secrets/login.age; + }; + }; + }; + + client = {_, ...}: {}; + }; + + services = [ + {server = "rocie.service";} + ]; + + ports = [ + {server = 80;} + {server = 443;} + ]; + + testScript = {...}: + # Python + '' + client.wait_until_succeeds("curl --verbose https://rocie.server/api/can-be-provisioned > out.file") + client.copy_from_machine("out.file") + ''; +} diff --git a/tests/by-name/ru/rust-motd/test.nix b/tests/by-name/ru/rust-motd/test.nix new file mode 100644 index 0000000..b50abf5 --- /dev/null +++ b/tests/by-name/ru/rust-motd/test.nix @@ -0,0 +1,30 @@ +{vhack, ...}: +vhack.runTest { + name = "rust-motd"; + + nodes = { + server = {config, ...}: { + vhack = { + rust-motd.enable = true; + }; + }; + }; + + services = [ + { + server = { + name = "rust-motd.service"; + should_be_started = true; + }; + } + ]; + + testScript = {nodes, ...}: + # Python + '' + with subtest("Motd generated"): + server.succeed("cat /var/lib/rust-motd/motd | tee /dev/stderr | grep --invert-match --ignore-case Error") + + server.copy_from_machine("/var/lib/rust-motd/motd") + ''; +} diff --git a/tests/by-name/sh/sharkey-cpu/test.nix b/tests/by-name/sh/sharkey-cpu/test.nix new file mode 100644 index 0000000..89bc7cb --- /dev/null +++ b/tests/by-name/sh/sharkey-cpu/test.nix @@ -0,0 +1,66 @@ +{ + packageSets, + vhack, + ... +}: let + pkgs = packageSets.stable; +in + vhack.runTest { + name = "sharkey-cpu"; + ignore = true; + + nodes = { + server = {config, ...}: { + vhack = { + persist.enable = true; + nginx.enable = true; + sharkey = { + enable = true; + fqdn = "sharkey.server"; + }; + }; + systemd.services = { + # Avoid an error from this service. + "acme-sharkey.server".enable = false; + + # Test that sharkey's hardening still allows access to the CPUs. + sharkey.serviceConfig.ExecStart = let + nodejs = pkgs.lib.getExe pkgs.nodejs; + script = pkgs.writeTextFile { + name = "script.js"; + text = + # js + '' + import * as os from 'node:os'; + + var cpus = os.cpus() + + if (cpus.length != 0) { + console.log(cpus[0].model) + } else { + // Fail? + } + + while (true) { + } + ''; + }; + in + pkgs.lib.mkForce "${nodejs} ${script}"; + }; + }; + }; + + services = [ + {server = "sharkey.service";} + ]; + + testScript = {...}: + # Python + '' + from time import sleep + + # Give the service time to run. + sleep(3) + ''; + } diff --git a/tests/by-name/sh/sharkey/test.nix b/tests/by-name/sh/sharkey/test.nix new file mode 100644 index 0000000..03a8281 --- /dev/null +++ b/tests/by-name/sh/sharkey/test.nix @@ -0,0 +1,34 @@ +{vhack, ...}: +vhack.runTest { + name = "sharkey"; + ignore = true; + + serverDomains = [ + {server = "sharkey.server";} + ]; + + nodes = { + server = {config, ...}: { + vhack = { + persist.enable = true; + nginx.enable = true; + sharkey = { + enable = true; + fqdn = "sharkey.server"; + }; + }; + }; + + client = {...}: {}; + }; + + services = [ + {server = "sharkey.service";} + ]; + + testScript = {...}: + # Python + '' + client.wait_until_succeeds("curl --verbose https://sharkey.server | grep 'Thank you for using Sharkey!'") + ''; +} diff --git a/tests/by-name/sn/snm-email-dual-server/test.nix b/tests/by-name/sn/snm-email-dual-server/test.nix new file mode 100644 index 0000000..1860058 --- /dev/null +++ b/tests/by-name/sn/snm-email-dual-server/test.nix @@ -0,0 +1,139 @@ +{ + lib, + vhack, + packageSets, + ownName, + ... +}: let + pkgs = packageSets.stable; + + server1Domain = "mail.server1"; + server2Domain = "mail.server2"; + + common = import ../../../common/email/functions.nix { + inherit pkgs; + vhackPackages = packageSets.in_tree; + }; + + # That's a horrible hack. We should instead wait, until the delivery of the email is + # confirmed. + sleepTime = "40"; +in + vhack.runTest { + name = ownName; + + serverDomains = [ + {server1 = server1Domain;} + {server2 = server2Domain;} + ]; + + nodes = { + server1 = common.mkMailServer server1Domain "alice"; + server2 = common.mkMailServer server2Domain "bob"; + + alice = common.mkUser "alice" server1Domain; + bob = common.mkUser "bob" server2Domain; + }; + + dns = { + server1 = common.mkDnsZone server1Domain; + server2 = common.mkDnsZone server2Domain; + }; + + services = [ + {server1 = "postfix.service";} + {server1 = "dovecot.service";} + {server2 = "postfix.service";} + {server2 = "dovecot.service";} + + {alice = "multi-user.target";} + {bob = "multi-user.target";} + ]; + + ports = [ + {server1 = 993;} # imap + {server1 = 465;} # smtp + + {server2 = 993;} # imap + {server2 = 465;} # smtp + ]; + + testScript = {...}: + # Python + '' + from time import sleep + + with subtest("Dkim keys work"): + server1.succeed("sudo -u rspamd ${pkgs.writeShellScript "dkim-keys-check" '' + set -xe + + stat /run/agenix/mailDkim + + ${lib.getExe pkgs.openssl} pkey -text -noout -in /run/agenix/mailDkim | grep Private-Key + ${lib.getExe pkgs.openssl} pkey -text -noout -in /run/agenix/mailDkim + ''}") + + with subtest("Both start without mail"): + alice.succeed("sudo -u alice ${common.scripts.expectNoNewMail}") + bob.succeed("sudo -u bob ${common.scripts.expectNoNewMail}") + + + with subtest("Alice can send an empty email to bob"): + alice.succeed("sudo -u alice ${pkgs.writeShellScript "alice-send" '' + set -xe + + echo "" | msmtp --debug --account alice bob@${server2Domain} >&2 + ''}") + + # Give the mail server some time to send the email. + sleep(${sleepTime}) + + bob.succeed("sudo -u bob ${common.scripts.expectNewSpamMail}") + + with subtest("Alice can send an non-empty email to bob"): + alice.succeed("sudo -u alice ${pkgs.writeShellScript "alice-send" '' + set -xe + + cat << EOF | msmtp --debug --account alice bob@${server2Domain} >&2 + Subject: Hi bob, I'm Alice! + + Good day, Bob! + + This is an email. + It contains a subject and a body. + I also assert utf8 support by including my last name in this very message. + + XOXO + Alice van Dåligen. + + . + EOF + ''}") + + # Give the mail server some time to send the email. + sleep(${sleepTime}) + + bob.succeed("sudo -u bob ${common.scripts.expectNewSpamMail}") + + with subtest("Bob can send an email to alice"): + bob.succeed("sudo -u bob ${pkgs.writeShellScript "bob-send" '' + set -xe + + cat << EOF | msmtp --debug --account bob alice@${server1Domain} >&2 + Hi Alice! + + Thank you for your emails! (Although they seemed kinda weird tbh :?) + + XXX + Bob Älšter + + . + EOF + ''}") + + # Give the mail server some time to send the email. + sleep(${sleepTime}) + + alice.succeed("sudo -u alice ${common.scripts.expectNewSpamMail}") + ''; + } diff --git a/tests/by-name/sn/snm-email-single-server/test.nix b/tests/by-name/sn/snm-email-single-server/test.nix new file mode 100644 index 0000000..6f65b83 --- /dev/null +++ b/tests/by-name/sn/snm-email-single-server/test.nix @@ -0,0 +1,91 @@ +{ + vhack, + packageSets, + ownName, + ... +}: let + pkgs = packageSets.stable; + + domain = "mail.server.test"; + + common = import ../../../common/email/functions.nix { + inherit pkgs; + vhackPackages = packageSets.in_tree; + }; +in + vhack.runTest { + name = ownName; + + serverDomains = [ + {server = domain;} + ]; + + nodes = { + server = {config, ...}: { + systemd.tmpfiles.rules = [ + #- path mode user group - content + "f /passwords/alice 777 root root - alice-password" + "f /passwords/bob 777 root root - bob-password" + ]; + + vhack = { + mail = { + enable = true; + fqdn = domain; + domains = [ + domain + ]; + accounts = { + "alice@${domain}" = { + passwordFile = "/passwords/alice"; + }; + "bob@${domain}" = { + passwordFile = "/passwords/bob"; + }; + }; + }; + }; + }; + + alice = common.mkUser "alice" domain; + bob = common.mkUser "bob" domain; + }; + + services = [ + {server = "postfix.service";} + ]; + + ports = [ + {server = 993;} # imap + {server = 465;} # smtp + ]; + + testScript = {...}: + # Python + '' + with subtest("Both start without mail"): + alice.succeed("sudo -u alice ${common.scripts.expectNoNewMail}") + bob.succeed("sudo -u bob ${common.scripts.expectNoNewMail}") + + with subtest("Alice can send an email to bob"): + alice.succeed("sudo -u alice ${pkgs.writeShellScript "alice-send" '' + set -xe + + cat << EOF | msmtp --debug --account alice bob@${domain} >&2 + Hi Bob! + + This is an email. + It contains a subject and a body. + + ALICE + EOF + ''}") + + # TODO: Find a better way to wait until alice mail has finished going through the + # email queue <2026-11-26> + from time import sleep + sleep(2) + + bob.succeed("sudo -u bob ${common.scripts.expectNewMail}") + ''; + } diff --git a/tests/by-name/st/stalwart-email-dns/nodes/mail_server.nix b/tests/by-name/st/stalwart-email-dns/nodes/mail_server.nix new file mode 100644 index 0000000..279d289 --- /dev/null +++ b/tests/by-name/st/stalwart-email-dns/nodes/mail_server.nix @@ -0,0 +1,52 @@ +{ + extraModules, + pkgs, + vhackPackages, +}: { + mkMailServer = serverName: principal: { + config, + lib, + nodes, + ... + }: { + imports = + extraModules + ++ [ + ../../../../../modules + ../../../../common/acme/client.nix + ../../../../common/dns/client.nix + ]; + + environment.systemPackages = [ + pkgs.bind + pkgs.openssl + ]; + + age.identityPaths = ["${../../../../common/email/hostKey}"]; + + vhack = { + stalwart-mail = { + enable = true; + fqdn = "${serverName}.server.com"; + admin = "admin@${serverName}.server.com"; + security = { + dkimKeys = let + loadKey = name: { + dkimPublicKey = builtins.readFile (../../../../common/email/dkim + "/${name}/public"); + dkimPrivateKeyPath = ../../../../common/email/dkim + "/${name}/private.age"; + keyAlgorithm = "ed25519-sha256"; + }; + in { + "mail1.server.com" = loadKey "mail1.server.com"; + "mail2.server.com" = loadKey "mail2.server.com"; + "alice.com" = loadKey "alice.com"; + "bob.com" = loadKey "bob.com"; + }; + verificationMode = "strict"; + }; + openFirewall = true; + principals = [principal]; + }; + }; + }; +} diff --git a/tests/by-name/st/stalwart-email-dns/nodes/name_server.nix b/tests/by-name/st/stalwart-email-dns/nodes/name_server.nix new file mode 100644 index 0000000..d9b3643 --- /dev/null +++ b/tests/by-name/st/stalwart-email-dns/nodes/name_server.nix @@ -0,0 +1,292 @@ +{extraModules}: { + config, + lib, + nodes, + pkgs, + ... +}: let + keyAlgoToKeyType = keyAlgo: + if keyAlgo == "ed25519-sha256" + then "ed25519" + else if keyAlgo == "rsa-sha-256" || keyAlgo == "rsa-sha-1" + then "rsa" + else builtins.throw "Impossible"; + + mkZone = user: nodes: lib: cfg: { + SOA = { + nameServer = "ns.server.com"; + adminEmail = "${user}@${user}.com"; + serial = 2024012301; + }; + + MX = [ + { + preference = 10; + exchange = "${cfg.fqdn}."; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc8461.html#section-3.1 + # Also see the policy in the hmtl part. + MTA-STS = [ + { + id = "20250228Z"; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc7208.html + # https://en.wikipedia.org/wiki/Sender_Policy_Framework + TXT = [ + (builtins.concatStringsSep " " + [ + "v=spf1" # The version. + "+mx" # Allow mail from this domain MX record. + "-all" # Reject all other emails if the previous mechanism did not match. + ]) + ]; + + # https://www.rfc-editor.org/rfc/rfc6376.html#section-3.6.1 + # https://www.rfc-editor.org/rfc/rfc6376.html#section-7.5 + DKIM = [ + { + selector = "mail"; + k = keyAlgoToKeyType cfg.security.dkimKeys."${user}.com".keyAlgorithm; + p = cfg.security.dkimKeys."${user}.com".dkimPublicKey; + s = ["email"]; + t = ["s"]; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc7489.html#section-6.3 + DMARC = [ + { + adkim = "strict"; + aspf = "strict"; + fo = ["0" "1" "d" "s"]; + p = "reject"; + rua = cfg.admin; + ruf = [cfg.admin]; + } + ]; + + A = [ + nodes.${user}.networking.primaryIPAddress + ]; + AAAA = [ + nodes.${user}.networking.primaryIPv6Address + ]; + }; + mkServerZone = serverName: nodes: lib: let + cfg = nodes."${serverName}_server".vhack.stalwart-mail; + in { + SOA = { + nameServer = "ns.server.com"; + adminEmail = "admin@server.com"; + serial = 2024012301; + }; + MX = [ + { + preference = 10; + exchange = "${serverName}.server.com."; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc6376.html#section-3.6.1 + # https://www.rfc-editor.org/rfc/rfc6376.html#section-7.5 + DKIM = [ + { + selector = "mail"; + k = keyAlgoToKeyType cfg.security.dkimKeys."${serverName}.server.com".keyAlgorithm; + p = cfg.security.dkimKeys."${serverName}.server.com".dkimPublicKey; + s = ["email"]; + t = ["s"]; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc7489.html#section-6.3 + DMARC = [ + { + adkim = "strict"; + aspf = "strict"; + fo = ["0" "1" "d" "s"]; + p = "quarantine"; + rua = cfg.admin; + ruf = [cfg.admin]; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc7208.html + # NOTE(@bpeetz): This server might not be directly sending mail, but it is still required for + # the SMTP EHLO check. <2025-02-25> + TXT = [ + (builtins.concatStringsSep " " + [ + "v=spf1" # The version. + "+mx" # Allow mail from this domain MX record. + "-all" # Reject all other emails if the previous mechanism did not match. + ]) + ]; + + A = [ + nodes."${serverName}_server".networking.primaryIPAddress + ]; + AAAA = [ + nodes."${serverName}_server".networking.primaryIPv6Address + ]; + }; +in { + imports = + extraModules + ++ [ + ../../../../../modules + ../../../../common/acme/client.nix + ../../../../common/dns/server.nix + ]; + + services.nginx = { + logError = "stderr debug"; + virtualHosts = let + mkStsHost = mx: { + forceSSL = true; + enableACME = true; + root = pkgs.runCommandLocal "mkPolicy" {} '' + mkdir --parents $out/.well-known/ + + # https://www.rfc-editor.org/rfc/rfc8461.html#section-3.2 + cat << EOF > $out/.well-known/mta-sts.txt + version: STSv1 + mode: enforce + mx: ${mx} + max_age: 604800 + EOF + ''; + }; + in { + "mta-sts.alice.com" = mkStsHost "mail2.server.com"; + "mta-sts.bob.com" = mkStsHost "mail1.server.com"; + }; + }; + + vhack = { + nginx = { + enable = true; + }; + dns.zones = let + stsZone = { + SOA = { + nameServer = "ns"; + adminEmail = "admin@server.com"; + serial = 2025012301; + }; + + useOrigin = false; + + A = [ + nodes.name_server.networking.primaryIPAddress + ]; + AAAA = [ + nodes.name_server.networking.primaryIPv6Address + ]; + }; + in { + "arpa" = { + SOA = { + nameServer = "ns"; + adminEmail = "admin@server.com"; + serial = 2025012301; + }; + useOrigin = false; + + PTR = [ + { + name = "acme.nixos_test"; + ip.v4 = nodes.acme.networking.primaryIPAddress; + } + { + name = "acme.nixos_test"; + ip.v6 = nodes.acme.networking.primaryIPv6Address; + } + + { + name = "alice.com"; + ip.v4 = nodes.alice.networking.primaryIPAddress; + } + { + name = "alice.com"; + ip.v6 = nodes.alice.networking.primaryIPv6Address; + } + + { + name = "bob"; + ip.v4 = nodes.bob.networking.primaryIPAddress; + } + { + name = "bob"; + ip.v6 = nodes.bob.networking.primaryIPv6Address; + } + + { + name = "mail1.server.com"; + ip.v4 = nodes.mail1_server.networking.primaryIPAddress; + } + { + name = "mail1.server.com"; + ip.v6 = nodes.mail1_server.networking.primaryIPv6Address; + } + + { + name = "mail2.server.com"; + ip.v4 = nodes.mail2_server.networking.primaryIPAddress; + } + { + name = "mail2.server.com"; + ip.v6 = nodes.mail2_server.networking.primaryIPv6Address; + } + + { + name = "ns.server.com"; + ip.v4 = nodes.name_server.networking.primaryIPAddress; + } + { + name = "ns.server.com"; + ip.v6 = nodes.name_server.networking.primaryIPv6Address; + } + ]; + }; + + "alice.com" = mkZone "alice" nodes lib nodes.mail2_server.vhack.stalwart-mail; + "mta-sts.alice.com" = stsZone; + "bob.com" = mkZone "bob" nodes lib nodes.mail1_server.vhack.stalwart-mail; + "mta-sts.bob.com" = stsZone; + "mail1.server.com" = mkServerZone "mail1" nodes lib; + "mail2.server.com" = mkServerZone "mail2" nodes lib; + "ns.server.com" = { + SOA = { + nameServer = "ns"; + adminEmail = "admin@server.com"; + serial = 2025012301; + }; + useOrigin = false; + + A = [ + nodes.name_server.networking.primaryIPAddress + ]; + AAAA = [ + nodes.name_server.networking.primaryIPv6Address + ]; + }; + "server.com" = { + SOA = { + nameServer = "ns"; + adminEmail = "admin@server.com"; + serial = 2025012301; + }; + + useOrigin = false; + NS = [ + "ns.server.com." + ]; + }; + }; + }; +} diff --git a/tests/by-name/st/stalwart-email-dns/nodes/user.nix b/tests/by-name/st/stalwart-email-dns/nodes/user.nix new file mode 100644 index 0000000..fba02ce --- /dev/null +++ b/tests/by-name/st/stalwart-email-dns/nodes/user.nix @@ -0,0 +1,70 @@ +{ + pkgs, + vhackPackages, +}: { + mkUser = user: serverName: { + nodes, + lib, + ... + }: { + imports = [ + ../../../../common/acme/client.nix + ../../../../common/dns/client.nix + ]; + + environment.systemPackages = [ + vhackPackages.fetchmail-common-name + pkgs.msmtp + pkgs.procmail + + pkgs.bind + pkgs.openssl + ]; + + users.users."${user}" = {isNormalUser = true;}; + + systemd.tmpfiles.rules = [ + "d /home/${user}/mail 0700 ${user} users - -" + "L /home/${user}/.fetchmailrc - - - - /etc/homeSetup/.fetchmailrc" + "L /home/${user}/.procmailrc - - - - /etc/homeSetup/.procmailrc" + "L /home/${user}/.msmtprc - - - - /etc/homeSetup/.msmtprc" + ]; + + environment.etc = { + "homeSetup/.fetchmailrc" = { + text = '' + poll "${serverName}.server.com" protocol IMAP + username "${user}" + password "${user}-password" + ssl + mda procmail; + ''; + mode = "0600"; + inherit user; + }; + "homeSetup/.procmailrc" = { + text = '' + DEFAULT=$HOME/mail + ''; + mode = "0600"; + inherit user; + }; + "homeSetup/.msmtprc" = { + text = '' + account ${user} + host ${serverName}.server.com + domain ${user}.com + port 465 + from ${user}@${user}.com + user ${user} + password ${user}-password + auth on + tls on + tls_starttls off + ''; + mode = "0600"; + inherit user; + }; + }; + }; +} diff --git a/tests/by-name/st/stalwart-email-dns/test.disabled.nix b/tests/by-name/st/stalwart-email-dns/test.disabled.nix new file mode 100644 index 0000000..33955d8 --- /dev/null +++ b/tests/by-name/st/stalwart-email-dns/test.disabled.nix @@ -0,0 +1,170 @@ +{ + nixos-lib, + pkgsUnstable, + nixpkgs-unstable, + vhackPackages, + pkgs, + extraModules, + nixLib, + ... +}: let + mail_server = import ./nodes/mail_server.nix {inherit extraModules pkgs vhackPackages;}; + inherit (mail_server) mkMailServer; + user = import ./nodes/user.nix {inherit pkgs vhackPackages;}; + inherit (user) mkUser; +in + nixos-lib.runTest { + # Wait until we actually use stalwart again + meta.broken = true; + + hostPkgs = pkgs; # the Nixpkgs package set used outside the VMs + + name = "email-dns"; + + node = { + specialArgs = {inherit pkgsUnstable vhackPackages nixpkgs-unstable nixLib;}; + + # Use the nixpkgs as constructed by the `nixpkgs.*` options + pkgs = null; + }; + + nodes = { + acme = { + nodes, + lib, + ... + }: { + imports = [ + ../../../common/acme/server.nix + ../../../common/dns/client.nix + ]; + }; + + name_server = import ./nodes/name_server.nix {inherit extraModules;}; + + mail1_server = + mkMailServer "mail1" + { + class = "individual"; + name = "bob"; + secret = "{PLAIN}bob-password"; + email = ["bob@bob.com"]; + }; + + mail2_server = + mkMailServer "mail2" + { + class = "individual"; + name = "alice"; + secret = "{PLAIN}alice-password"; + email = ["alice@alice.com"]; + }; + + bob = mkUser "bob" "mail1"; + alice = mkUser "alice" "mail2"; + }; + + testScript = {...}: let + checkEmailEmpty = pkgs.writeShellScript "assert-empty-emails" '' + set -xe + + # fetchmail returns EXIT_CODE 1 when no new mail + fetchmail --verbose >&2 || [ "$?" -eq 1 ] || { + echo "Mail was not empty" >&2 + exit 1 + } + ''; + checkEmailNotEmpty = pkgs.writeShellScript "assert-empty-emails" '' + set -xe + + # fetchmail returns EXIT_CODE 1 when no new mail + fetchmail --verbose >&2 || [ "$?" -ne 1 ] || { + echo "No new mail" >&2 + exit 1 + } + ''; + checkSpamEmailNotEmpty = pkgs.writeShellScript "assert-empty-emails" '' + set -xe + + # fetchmail returns EXIT_CODE 1 when no new mail + fetchmail --folder JUNK --verbose >&2 || [ "$?" -ne 1 ] || { + echo "No new mail" >&2 + exit 1 + } + ''; + + acme = import ../../../common/acme {inherit pkgs;}; + in + acme.prepare ["mail1_server" "mail2_server" "alice" "bob"] + # Python + '' + from time import sleep + + mail1_server.wait_for_unit("stalwart-mail.service") + mail1_server.wait_for_open_port(993) # imap + mail1_server.wait_for_open_port(465) # smtp + mail2_server.wait_for_unit("stalwart-mail.service") + mail2_server.wait_for_open_port(993) # imap + mail2_server.wait_for_open_port(465) # smtp + + alice.wait_for_unit("multi-user.target") + bob.wait_for_unit("multi-user.target") + + name_server.wait_until_succeeds("stat /var/lib/acme/mta-sts.alice.com/cert.pem") + name_server.wait_until_succeeds("stat /var/lib/acme/mta-sts.bob.com/cert.pem") + + with subtest("Both mailserver successfully started all services"): + import json + def all_services_running(host): + (status, output) = host.systemctl("list-units --state=failed --plain --no-pager --output=json") + host_failed = json.loads(output) + assert len(host_failed) == 0, f"Expected zero failing services, but found: {json.dumps(host_failed, indent=4)}" + all_services_running(mail1_server) + all_services_running(mail2_server) + + with subtest("Both start without mail"): + alice.succeed("sudo -u alice ${checkEmailEmpty}") + bob.succeed("sudo -u bob ${checkEmailEmpty}") + + with subtest("Alice can send an empty email to bob"): + alice.succeed("sudo -u alice ${pkgs.writeShellScript "alice-send" '' + set -xe + + echo "" | msmtp --debug --account alice bob@bob.com >&2 + ''}") + + # Give `mail2_server` some time to send the email. + sleep(160) + + bob.succeed("sudo -u bob ${checkSpamEmailNotEmpty}") + + with subtest("Alice can send an non-empty email to bob"): + alice.succeed("sudo -u alice ${pkgs.writeShellScript "alice-send" '' + set -xe + + cat << EOF | msmtp --debug --account alice bob@bob.com >&2 + Subject: Hi bob, I'm Alice! + + Good day, Bob! + + This is an email. + It contains a subject and a body. + I also assert utf8 support by including my last name in this very message. + + XOXO + Alice van Dåligen. + + . + EOF + ''}") + + # Give `mail2_server` some time to send the email. + sleep(120) + + bob.succeed("sudo -u bob ${checkEmailNotEmpty}") + + mail1_server.copy_from_vm("/var/lib/", "server1") + mail2_server.copy_from_vm("/var/lib/", "server2") + bob.copy_from_vm("/home/bob/mail", "bob") + ''; + } diff --git a/tests/by-name/st/stalwart-email-http/nodes/mail_server.nix b/tests/by-name/st/stalwart-email-http/nodes/mail_server.nix new file mode 100644 index 0000000..e94c4e9 --- /dev/null +++ b/tests/by-name/st/stalwart-email-http/nodes/mail_server.nix @@ -0,0 +1,57 @@ +{ + extraModules, + pkgs, + vhackPackages, +}: { + mkMailServer = serverName: principal: { + config, + lib, + nodes, + ... + }: { + imports = + extraModules + ++ [ + ../../../../../modules + ../../../../common/acme/client.nix + ]; + + environment.systemPackages = [ + pkgs.bind + pkgs.openssl + ]; + + networking.nameservers = lib.mkForce [ + nodes.name_server.networking.primaryIPAddress + nodes.name_server.networking.primaryIPv6Address + ]; + + age.identityPaths = ["${../../../../common/email/hostKey}"]; + + vhack = { + stalwart-mail = { + enable = true; + fqdn = "${serverName}.server.com"; + admin = "admin@${serverName}.server.com"; + security = { + dkimKeys = let + loadKey = name: { + dkimPublicKey = builtins.readFile (../../../../common/email/dkim + "/${name}/public"); + dkimPrivateKeyPath = ../../../../common/email/dkim + "/${name}/private.age"; + keyAlgorithm = "ed25519-sha256"; + }; + in { + "mail.server.com" = loadKey "mail1.server.com"; + "bob.com" = loadKey "bob.com"; + }; + verificationMode = "strict"; + }; + openFirewall = true; + principals = + if principal == null + then null + else [principal]; + }; + }; + }; +} diff --git a/tests/by-name/st/stalwart-email-http/nodes/user.nix b/tests/by-name/st/stalwart-email-http/nodes/user.nix new file mode 100644 index 0000000..73b9ff7 --- /dev/null +++ b/tests/by-name/st/stalwart-email-http/nodes/user.nix @@ -0,0 +1,26 @@ +{ + pkgs, + vhackPackages, +}: { + mkUser = user: serverName: { + nodes, + lib, + ... + }: { + imports = [ + ../../../../common/acme/client.nix + ]; + + environment.systemPackages = [ + pkgs.bind + pkgs.openssl + ]; + + networking.nameservers = lib.mkForce [ + nodes.name_server.networking.primaryIPAddress + nodes.name_server.networking.primaryIPv6Address + ]; + + users.users."${user}" = {isNormalUser = true;}; + }; +} diff --git a/tests/by-name/st/stalwart-email-http/test.disabled.nix b/tests/by-name/st/stalwart-email-http/test.disabled.nix new file mode 100644 index 0000000..42fd22b --- /dev/null +++ b/tests/by-name/st/stalwart-email-http/test.disabled.nix @@ -0,0 +1,103 @@ +{ + nixos-lib, + pkgsUnstable, + nixpkgs-unstable, + vhackPackages, + pkgs, + extraModules, + nixLib, + ... +}: let + mail_server = import ./nodes/mail_server.nix {inherit extraModules pkgs vhackPackages;}; + inherit (mail_server) mkMailServer; + user = import ./nodes/user.nix {inherit pkgs vhackPackages;}; + inherit (user) mkUser; +in + nixos-lib.runTest { + # Wait until we actually use stalwart again + meta.broken = true; + + hostPkgs = pkgs; # the Nixpkgs package set used outside the VMs + + name = "email-http"; + + node = { + specialArgs = {inherit pkgsUnstable vhackPackages nixpkgs-unstable nixLib;}; + + # Use the nixpkgs as constructed by the `nixpkgs.*` options + pkgs = null; + }; + + nodes = { + acme = { + nodes, + lib, + ... + }: { + imports = [ + ../../../common/acme/server.nix + ../../../common/dns/client.nix + ]; + }; + + name_server = {nodes, ...}: { + imports = + extraModules + ++ [ + ../../../common/acme/client.nix + ../../../common/dns/server.nix + ]; + + vhack.dns.zones = { + "mail.server.com" = { + SOA = { + nameServer = "ns"; + adminEmail = "admin@server.com"; + serial = 2025012301; + }; + useOrigin = false; + + A = [ + nodes.mail_server.networking.primaryIPAddress + ]; + AAAA = [ + nodes.mail_server.networking.primaryIPv6Address + ]; + }; + }; + }; + + mail_server = mkMailServer "mail" null; + + bob = mkUser "bob" "mail"; + }; + + # TODO(@bpeetz): This test should also test the http JMAP features of stalwart-mail. <2025-04-12> + testScript = _: let + acme = import ../../../common/acme {inherit pkgs;}; + in + acme.prepare ["mail_server" "bob"] + # Python + '' + mail_server.wait_for_unit("stalwart-mail.service") + mail_server.wait_for_open_port(993) # imap + mail_server.wait_for_open_port(465) # smtp + + bob.wait_for_unit("multi-user.target") + + with subtest("The mailserver successfully started all services"): + import json + def all_services_running(host): + (status, output) = host.systemctl("list-units --state=failed --plain --no-pager --output=json") + host_failed = json.loads(output) + assert len(host_failed) == 0, f"Expected zero failing services, but found: {json.dumps(host_failed, indent=4)}" + all_services_running(mail_server) + + with subtest("Bob can use the self-service interface"): + bob.succeed("${pkgs.writeShellScript "check-self-service" '' + curl mail.server.com --location --output /home/bob/output.html; + ''}") + + bob.copy_from_vm("/home/bob", "") + ''; + } diff --git a/tests/by-name/st/stalwart-email-ip/test.disabled.nix b/tests/by-name/st/stalwart-email-ip/test.disabled.nix new file mode 100644 index 0000000..c0b2d7e --- /dev/null +++ b/tests/by-name/st/stalwart-email-ip/test.disabled.nix @@ -0,0 +1,177 @@ +{ + nixos-lib, + pkgsUnstable, + nixpkgs-unstable, + vhackPackages, + pkgs, + extraModules, + nixLib, + ... +}: let + domain = "mail.server.test"; + + scripts = { + checkEmailEmpty = pkgs.writeShellScript "assert-empty-emails" '' + set -xe + + # fetchmail returns EXIT_CODE 1 when no new mail + fetchmail --nosslcertck --verbose >&2 || [ "$?" -eq 1 ] || { + echo "Expected exit code 1." >&2 + exit 1 + } + ''; + }; + + mkUser = user: {nodes, ...}: let + domainIp = nodes.server.networking.primaryIPAddress; + in { + environment.systemPackages = with pkgs; [ + fetchmail + msmtp + procmail + ]; + + users.users."${user}" = {isNormalUser = true;}; + + systemd.tmpfiles.rules = [ + "d /home/${user}/mail 0700 ${user} users - -" + "L /home/${user}/.fetchmailrc - - - - /etc/homeSetup/.fetchmailrc" + "L /home/${user}/.procmailrc - - - - /etc/homeSetup/.procmailrc" + "L /home/${user}/.msmtprc - - - - /etc/homeSetup/.msmtprc" + ]; + + environment.etc = { + "homeSetup/.fetchmailrc" = { + text = '' + poll "${domainIp}" protocol IMAP + username "${user}" + password "${user}-password" + ssl + mda procmail; + ''; + mode = "0600"; + inherit user; + }; + "homeSetup/.procmailrc" = { + text = '' + DEFAULT=$HOME/mail + ''; + mode = "0600"; + inherit user; + }; + "homeSetup/.msmtprc" = { + text = '' + account ${user} + host ${domainIp} + port 465 + from ${user}@${domain} + user ${user} + password ${user}-password + auth on + tls on + tls_starttls off + ''; + mode = "0600"; + inherit user; + }; + }; + }; +in + nixos-lib.runTest { + # Wait until we actually use stalwart again + meta.broken = true; + + hostPkgs = pkgs; # the Nixpkgs package set used outside the VMs + + name = "email"; + + node = { + specialArgs = {inherit pkgsUnstable vhackPackages nixpkgs-unstable nixLib;}; + + # Use the nixpkgs as constructed by the `nixpkgs.*` options + pkgs = null; + }; + + nodes = { + server = {config, ...}: { + imports = + extraModules + ++ [ + ../../../../modules + ]; + + vhack = { + nginx = { + enable = true; + selfsign = true; + }; + + stalwart-mail = { + enable = true; + fqdn = domain; + admin = "mailto:admin@${domain}"; + security = null; + openFirewall = true; + principals = [ + { + class = "individual"; + name = "alice"; + secret = "{PLAIN}alice-password"; + email = ["alice@${domain}"]; + } + { + class = "individual"; + name = "bob"; + secret = "{PLAIN}bob-password"; + email = ["bob@${domain}"]; + } + ]; + }; + }; + }; + + alice = mkUser "alice"; + bob = mkUser "bob"; + }; + + testScript = {...}: + /* + python + */ + '' + start_all() + + server.wait_for_unit("stalwart-mail.service") + server.wait_for_open_port(993) # imap + server.wait_for_open_port(465) # smtp + + with subtest("Both start without mail"): + alice.succeed("sudo -u alice ${scripts.checkEmailEmpty}") + bob.succeed("sudo -u bob ${scripts.checkEmailEmpty}") + + with subtest("Alice can send an email to bob"): + alice.succeed("sudo -u alice ${pkgs.writeShellScript "alice-send" '' + set -xe + + cat << EOF | msmtp --debug --account alice --tls-certcheck=off bob@${domain} >&2 + Hi Bob! + + This is an email. + It contains a subject and a body. + + ALICE + EOF + ''}") + bob.succeed("sudo -u bob ${pkgs.writeShellScript "bob-receive" '' + set -xe + + fetchmail --nosslcertck --verbose >&2 || { + echo New Mail did not arrive + exit 1 + } + ''}") + + server.copy_from_vm("/var/lib/", "server") + bob.copy_from_vm("/home/bob/mail", "bob") + ''; + } diff --git a/tests/by-name/ta/taskchampion-sync/test.nix b/tests/by-name/ta/taskchampion-sync/test.nix new file mode 100644 index 0000000..a8b42ee --- /dev/null +++ b/tests/by-name/ta/taskchampion-sync/test.nix @@ -0,0 +1,94 @@ +{ + packageSets, + vhack, + ... +}: let + pkgs = packageSets.stable; +in + vhack.runTest { + name = "taskchampion-sync"; + + serverDomains = [ + {server = "taskchampion.server";} + ]; + + nodes = let + taskwarriorPackage = pkgs.taskwarrior3.overrideAttrs (final: prev: { + cmakeFlags = (prev.cmakeFlags or []) ++ ["-DENABLE_TLS_NATIVE_ROOTS=true"]; + }); + in { + server = {config, ...}: { + vhack = { + persist.enable = true; + nginx.enable = true; + taskchampion-sync = { + enable = true; + fqdn = "taskchampion.server"; + }; + }; + }; + + task_client1 = {config, ...}: { + environment.systemPackages = [ + taskwarriorPackage + ]; + }; + task_client2 = {config, ...}: { + environment.systemPackages = [ + taskwarriorPackage + ]; + }; + }; + + services = [ + {server = "taskchampion-sync-server.service";} + ]; + + ports = [ + {server = 443;} + ]; + + testScript = {nodes, ...}: let + # Generated with uuidgen + uuid = "bf01376e-04a4-435a-9263-608567531af3"; + password = "nixos-test"; + + mkSyncConfig = path: + pkgs.writeShellScript "setup-config-file" '' + set -xe + + mkdir --parents "$(dirname "${path}")" + echo 'sync.server.url=https://taskchampion.server' >> "${path}" + echo 'sync.server.client_id=${uuid}' >> "${path}" + echo 'sync.encryption_secret=${password}' >> "${path}" + ''; + in + # Python + '' + with subtest("Setup task syncing"): + for task in [task_client1, task_client2]: + # See man task-sync(5) + task.succeed("mkdir ~/.task") + task.succeed("${mkSyncConfig "$HOME/.taskrc"}") + + with subtest("Can create tasks"): + task_client1.succeed("task add 'First task -- task_client1'") + task_client2.succeed("task add 'First task -- task_client2'") + + # Wait for the server to acquire the acme certificate + task_client1.wait_until_succeeds("curl https://taskchampion.server") + + with subtest("Can sync tasks"): + for task in [task_client1, task_client2]: + task.succeed("task sync") + task_client1.succeed("task sync") + + + with subtest("Have correct tasks"): + count1 = task_client1.succeed("task count") + count2 = task_client2.succeed("task count") + + assert int(count1) == 2, f"We don't have exactly 2 tasks, but {count1}" + assert count1 == count2, f"The clients don't have the same amount of tasks, client1: {count1}, client2: {count2}" + ''; + } diff --git a/tests/common/acme/certs/generate b/tests/common/acme/certs/generate new file mode 100755 index 0000000..ffce74b --- /dev/null +++ b/tests/common/acme/certs/generate @@ -0,0 +1,66 @@ +#! /usr/bin/env nix-shell +#! nix-shell -p gnutls -p dash -i dash --impure +# shellcheck shell=dash + +# For development and testing. +# Create a CA key and cert, and use that to generate a server key and cert. +# Creates: +# ca.key.pem +# ca.cert.pem +# server.key.pem +# server.cert.pem + +export SEC_PARAM=ultra +export EXPIRATION_DAYS=123456 +export ORGANIZATION="Vhack.eu Test Keys" +export COUNTRY=EU +export SAN="acme.nixos_test" +export KEY_TYPE="ed25519" + +BASEDIR="$(dirname "$0")" +GENERATION_LOCATION="$BASEDIR/output" +cd "$BASEDIR" || { + echo "(BUG?) No basedir ('$BASEDIR')" 1>&2 + exit 1 +} + +ca=false +clients=false + +usage() { + echo "Usage: $0 --ca|--clients" + exit 2 +} + +if [ "$#" -eq 0 ]; then + usage +fi + +for arg in "$@"; do + case "$arg" in + "--ca") + ca=true + ;; + "--clients") + clients=true + ;; + *) + usage + ;; + esac +done + +[ -d "$GENERATION_LOCATION" ] || mkdir --parents "$GENERATION_LOCATION" +cd "$GENERATION_LOCATION" || echo "(BUG?) No generation location fould!" 1>&2 + +[ "$ca" = true ] && ../generate.ca + +# Creates: +# <client_name>.key.pem +# <client_name>.cert.pem +# +[ "$clients" = true ] && ../generate.client "acme.nixos_test" + +echo "(INFO) Look for the keys at: $GENERATION_LOCATION" + +# vim: ft=sh diff --git a/tests/common/acme/certs/generate.ca b/tests/common/acme/certs/generate.ca new file mode 100755 index 0000000..92832c5 --- /dev/null +++ b/tests/common/acme/certs/generate.ca @@ -0,0 +1,38 @@ +#! /usr/bin/env sh + +# Take the correct binary to create the certificates +CERTTOOL=$(command -v gnutls-certtool 2>/dev/null || command -v certtool 2>/dev/null) +if [ -z "$CERTTOOL" ]; then + echo "ERROR: No certtool found" >&2 + exit 1 +fi + +# Create a CA key. +$CERTTOOL \ + --generate-privkey \ + --sec-param "$SEC_PARAM" \ + --key-type "$KEY_TYPE" \ + --outfile ca.key.pem + +chmod 600 ca.key.pem + +# Sign a CA cert. +cat <<EOF >ca.template +country = $COUNTRY +dns_name = "$SAN" +expiration_days = $EXPIRATION_DAYS +organization = $ORGANIZATION +ca +EOF +#state = $STATE +#locality = $LOCALITY + +$CERTTOOL \ + --generate-self-signed \ + --load-privkey ca.key.pem \ + --template ca.template \ + --outfile ca.cert.pem + +chmod 600 ca.cert.pem + +# vim: ft=sh diff --git a/system/services/taskserver/certs/generate.client b/tests/common/acme/certs/generate.client index 4f0e503..5930298 100755 --- a/system/services/taskserver/certs/generate.client +++ b/tests/common/acme/certs/generate.client @@ -1,54 +1,44 @@ -#!/bin/sh +#! /usr/bin/env sh # Take the correct binary to create the certificates CERTTOOL=$(command -v gnutls-certtool 2>/dev/null || command -v certtool 2>/dev/null) -if [ -z "$CERTTOOL" ] -then - echo "ERROR: No certtool found" >&2 - exit 1 +if [ -z "$CERTTOOL" ]; then + echo "ERROR: No certtool found" >&2 + exit 1 fi -. ./vars - NAME=client -if [ $# -gt 0 ] -then - NAME=$1 +if [ $# -gt 0 ]; then + NAME="$1" fi -if ! [ -f "$NAME".key.pem ] -then - # Create a client key. - $CERTTOOL \ +# Create a client key. +$CERTTOOL \ --generate-privkey \ - --sec-param $SEC_PARAM \ + --sec-param "$SEC_PARAM" \ + --key-type "$KEY_TYPE" \ --outfile "$NAME".key.pem -fi chmod 600 "$NAME".key.pem -if ! [ -f "$NAME".template ] -then - # Sign a client cert with the key. - cat <<EOF >"$NAME".template -organization = $ORGANIZATION -cn = $CN +# Sign a client cert with the key. +cat <<EOF >"$NAME".template +dns_name = "$NAME" +dns_name = "$SAN" expiration_days = $EXPIRATION_DAYS -tls_www_client +organization = $ORGANIZATION encryption_key signing_key EOF -fi -if ! [ -f "$NAME".cert.pem ] -then - $CERTTOOL \ +$CERTTOOL \ --generate-certificate \ --load-privkey "$NAME".key.pem \ --load-ca-certificate ca.cert.pem \ --load-ca-privkey ca.key.pem \ --template "$NAME".template \ --outfile "$NAME".cert.pem -fi chmod 600 "$NAME".cert.pem + +# vim: ft=sh diff --git a/tests/common/acme/certs/output/acme.nixos_test.cert.pem b/tests/common/acme/certs/output/acme.nixos_test.cert.pem new file mode 100644 index 0000000..58b4de1 --- /dev/null +++ b/tests/common/acme/certs/output/acme.nixos_test.cert.pem @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE----- +MIIBmjCCAUygAwIBAgIUFdLqU4Nnr7S1XID2wC9T77hCOFwwBQYDK2VwMCoxCzAJ +BgNVBAYTAkVVMRswGQYDVQQKExJWaGFjay5ldSBUZXN0IEtleXMwIBcNMjYxMTI1 +MjEyNzIxWhgPMjM2NDExMjkyMTI3MjFaMB0xGzAZBgNVBAoTElZoYWNrLmV1IFRl +c3QgS2V5czAqMAUGAytlcAMhAMkG/QPjjHnBb+hbKplpVFB6H+UgW/ZvBvlBT1aE +0AvDo4GOMIGLMAwGA1UdEwEB/wQCMAAwKwYDVR0RBCQwIoIPYWNtZS5uaXhvc190 +ZXN0gg9hY21lLm5peG9zX3Rlc3QwDgYDVR0PAQH/BAQDAgeAMB0GA1UdDgQWBBRo +0ehOg4DRs1umtKC2Ao1flvI0HjAfBgNVHSMEGDAWgBQixZzNSQAtj5IS+2AEQBEa +PJoG3jAFBgMrZXADQQAL7KGrXQvFi5Qf68VQmTYush5rKCaplI9Dyx6q2bjY/CdL +0Ru36eyHML25kHdH1O/uATOUzcQ2ktQr/32rYeEF +-----END CERTIFICATE----- diff --git a/tests/common/acme/certs/output/acme.nixos_test.key.pem b/tests/common/acme/certs/output/acme.nixos_test.key.pem new file mode 100644 index 0000000..6917ca3 --- /dev/null +++ b/tests/common/acme/certs/output/acme.nixos_test.key.pem @@ -0,0 +1,25 @@ +Public Key Info: + Public Key Algorithm: EdDSA (Ed25519) + Key Security Level: High (256 bits) + +curve: Ed25519 +private key: + 32:d5:dd:08:b1:9f:8e:6d:6a:dc:7d:95:56:ea:93:2e + 8a:58:95:24:ea:83:81:1a:f1:a0:91:67:98:d2:db:58 + + +x: + c9:06:fd:03:e3:8c:79:c1:6f:e8:5b:2a:99:69:54:50 + 7a:1f:e5:20:5b:f6:6f:06:f9:41:4f:56:84:d0:0b:c3 + + + +Public Key PIN: + pin-sha256:eavyvA0AGilDRJLrGi6ZQbJsvmglZJbNNtu43TccUUU= +Public Key ID: + sha256:79abf2bc0d001a29434492eb1a2e9941b26cbe68256496cd36dbb8dd371c5145 + sha1:68d1e84e8380d1b35ba6b4a0b6028d5f96f2341e + +-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIDLV3Qixn45tatx9lVbqky6KWJUk6oOBGvGgkWeY0ttY +-----END PRIVATE KEY----- diff --git a/tests/common/acme/certs/output/acme.nixos_test.template b/tests/common/acme/certs/output/acme.nixos_test.template new file mode 100644 index 0000000..4a8ffc2 --- /dev/null +++ b/tests/common/acme/certs/output/acme.nixos_test.template @@ -0,0 +1,6 @@ +dns_name = "acme.nixos_test" +dns_name = "acme.nixos_test" +expiration_days = 123456 +organization = Vhack.eu Test Keys +encryption_key +signing_key diff --git a/tests/common/acme/certs/output/ca.cert.pem b/tests/common/acme/certs/output/ca.cert.pem new file mode 100644 index 0000000..80bcfba --- /dev/null +++ b/tests/common/acme/certs/output/ca.cert.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBZjCCARigAwIBAgIUJOXiI/fNb+f0jg9A5C8R422F1fEwBQYDK2VwMCoxCzAJ +BgNVBAYTAkVVMRswGQYDVQQKExJWaGFjay5ldSBUZXN0IEtleXMwIBcNMjYxMTI1 +MjEyNzIxWhgPMjM2NDExMjkyMTI3MjFaMCoxCzAJBgNVBAYTAkVVMRswGQYDVQQK +ExJWaGFjay5ldSBUZXN0IEtleXMwKjAFBgMrZXADIQBB0LTe8yXxLY1AGtwTYnR8 +FKRi443xDAnMzvlgHkPEM6NOMEwwDwYDVR0TAQH/BAUwAwEB/zAaBgNVHREEEzAR +gg9hY21lLm5peG9zX3Rlc3QwHQYDVR0OBBYEFCLFnM1JAC2PkhL7YARAERo8mgbe +MAUGAytlcANBAJ8BFuFmb3uCLqi4R0fIXfPIZ11dGpfGZH53mo/rHZjag2LZp2s3 +vFOposan7fyE1AR8SWcAM29jDUODEEbt/gc= +-----END CERTIFICATE----- diff --git a/tests/common/acme/certs/output/ca.key.pem b/tests/common/acme/certs/output/ca.key.pem new file mode 100644 index 0000000..63f4ce3 --- /dev/null +++ b/tests/common/acme/certs/output/ca.key.pem @@ -0,0 +1,25 @@ +Public Key Info: + Public Key Algorithm: EdDSA (Ed25519) + Key Security Level: High (256 bits) + +curve: Ed25519 +private key: + d4:e3:c9:e9:66:c5:b9:4c:cd:ff:d0:ae:3a:ae:de:69 + 62:8b:17:3e:92:57:fd:87:06:03:f1:c1:38:65:a2:fd + + +x: + 41:d0:b4:de:f3:25:f1:2d:8d:40:1a:dc:13:62:74:7c + 14:a4:62:e3:8d:f1:0c:09:cc:ce:f9:60:1e:43:c4:33 + + + +Public Key PIN: + pin-sha256:KRMUGfl9oe0XIaRXC0iXU8vAYUe1txWgHhIScds/CrA= +Public Key ID: + sha256:29131419f97da1ed1721a4570b489753cbc06147b5b715a01e121271db3f0ab0 + sha1:22c59ccd49002d8f9212fb600440111a3c9a06de + +-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEINTjyelmxblMzf/Qrjqu3mliixc+klf9hwYD8cE4ZaL9 +-----END PRIVATE KEY----- diff --git a/tests/common/acme/certs/output/ca.template b/tests/common/acme/certs/output/ca.template new file mode 100644 index 0000000..80c74c0 --- /dev/null +++ b/tests/common/acme/certs/output/ca.template @@ -0,0 +1,5 @@ +country = EU +dns_name = "acme.nixos_test" +expiration_days = 123456 +organization = Vhack.eu Test Keys +ca diff --git a/tests/common/acme/certs/snakeoil-certs.nix b/tests/common/acme/certs/snakeoil-certs.nix new file mode 100644 index 0000000..1b4328c --- /dev/null +++ b/tests/common/acme/certs/snakeoil-certs.nix @@ -0,0 +1,13 @@ +let + domain = "acme.nixos_test"; +in { + inherit domain; + ca = { + cert = ./output/ca.cert.pem; + key = ./output/ca.key.pem; + }; + "${domain}" = { + cert = ./output/. + "/${domain}.cert.pem"; + key = ./output/. + "/${domain}.key.pem"; + }; +} diff --git a/tests/common/acme/client.nix b/tests/common/acme/client.nix new file mode 100644 index 0000000..2b870e8 --- /dev/null +++ b/tests/common/acme/client.nix @@ -0,0 +1,21 @@ +{ + nodes, + lib, + ... +}: let + inherit (nodes.acme.test-support.acme) caCert; + inherit (nodes.acme.test-support.acme) caDomain; +in { + security = { + acme = { + acceptTerms = true; + defaults = { + server = "https://${caDomain}/dir"; + }; + }; + + pki = { + certificateFiles = lib.mkForce [caCert]; + }; + }; +} diff --git a/tests/common/acme/default.nix b/tests/common/acme/default.nix new file mode 100644 index 0000000..dffe40c --- /dev/null +++ b/tests/common/acme/default.nix @@ -0,0 +1,44 @@ +{pkgs}: let + add_pebble_ca_certs = pkgs.writeShellScript "fetch-and-set-ca" '' + set -xe + + # Fetch the randomly generated ca certificate + curl https://acme.nixos_test:15000/roots/0 > /tmp/ca.crt + curl https://acme.nixos_test:15000/intermediates/0 >> /tmp/ca.crt + + # Append it to the various system stores + # The file paths are from <nixpgks>/modules/security/ca.nix + for cert_path in "ssl/certs/ca-certificates.crt" "ssl/certs/ca-bundle.crt" "pki/tls/certs/ca-bundle.crt"; do + cert_path="/etc/$cert_path" + + mv "$cert_path" "$cert_path.old" + cat "$cert_path.old" > "$cert_path" + cat /tmp/ca.crt >> "$cert_path" + done + + export NIX_SSL_CERT_FILE=/tmp/ca.crt + export SSL_CERT_FILE=/tmp/ca.crt + + # TODO + # # P11-Kit trust source. + # environment.etc."ssl/trust-source".source = "$${cacertPackage.p11kit}/etc/ssl/trust-source"; + ''; +in { + prepare = clients: extra: + # The parens are needed for the syntax highlighting to work. + ( # python + '' + # Start dependencies for the other services + start_all() + + acme.wait_for_unit("pebble.service") + name_server.wait_for_unit("nsd.service") + + with subtest("Add pebble ca key to all services"): + for node in [name_server, ${builtins.concatStringsSep "," clients}]: + node.wait_until_succeeds("curl https://acme.nixos_test:15000/roots/0") + node.succeed("${add_pebble_ca_certs}") + '' + ) + + extra; +} diff --git a/tests/common/acme/server.nix b/tests/common/acme/server.nix new file mode 100644 index 0000000..997c944 --- /dev/null +++ b/tests/common/acme/server.nix @@ -0,0 +1,91 @@ +# Add this node as acme server. +# This also needs a DNS server. +{ + config, + pkgs, + lib, + ... +}: let + testCerts = import ./certs/snakeoil-certs.nix; + inherit (testCerts) domain; + + pebbleConf.pebble = { + listenAddress = "0.0.0.0:443"; + managementListenAddress = "0.0.0.0:15000"; + + # The cert and key are used only for the Web Front End (WFE) + certificate = testCerts.${domain}.cert; + privateKey = testCerts.${domain}.key; + + httpPort = 80; + tlsPort = 443; + ocspResponderURL = "http://${domain}:4002"; + strict = true; + }; + + pebbleConfFile = pkgs.writeText "pebble.conf" (builtins.toJSON pebbleConf); +in { + options.test-support.acme = { + caDomain = lib.mkOption { + type = lib.types.str; + default = domain; + readOnly = true; + description = '' + A domain name to use with the `nodes` attribute to + identify the CA server in the `client` config. + ''; + }; + caCert = lib.mkOption { + type = lib.types.path; + readOnly = true; + default = testCerts.ca.cert; + description = '' + A certificate file to use with the `nodes` attribute to + inject the test CA certificate used in the ACME server into + {option}`security.pki.certificateFiles`. + ''; + }; + }; + + config = { + networking = { + # This has priority 140, because modules/testing/test-instrumentation.nix + # already overrides this with priority 150. + nameservers = lib.mkOverride 140 ["127.0.0.1"]; + firewall.allowedTCPPorts = [ + 80 + 443 + 15000 + 4002 + ]; + + extraHosts = '' + 127.0.0.1 ${domain} + ${config.networking.primaryIPAddress} ${domain} + ''; + }; + + systemd.services = { + pebble = { + enable = true; + description = "Pebble ACME server"; + wantedBy = ["network.target"]; + environment = { + # We're not testing lego, we're just testing our configuration. + # No need to sleep. + PEBBLE_VA_NOSLEEP = "1"; + }; + + serviceConfig = { + RuntimeDirectory = "pebble"; + WorkingDirectory = "/run/pebble"; + + # Required to bind on privileged ports. + AmbientCapabilities = ["CAP_NET_BIND_SERVICE"]; + + ExecStart = "${pkgs.pebble}/bin/pebble -config ${pebbleConfFile}"; + }; + }; + }; + }; +} diff --git a/tests/common/dns/client.nix b/tests/common/dns/client.nix new file mode 100644 index 0000000..384f1c9 --- /dev/null +++ b/tests/common/dns/client.nix @@ -0,0 +1,16 @@ +{ + nodes, + lib, + ... +}: { + # In the test environment, we cannot use the root dns servers to perform recursive dns + # resolving, as there is no internet access. + # Instead of doing the dance with root dns servers and what-not, we just force them + # to directly connect to our authoritative dns server for the zones we have. + networking.nameservers = lib.mkForce nodes.name_server.vhack.nsd.interfaces; + + # `unbound` might be active, but it's utterly pointless in a test environment (there is + # no network access). So we disable it, which means that the nameservers, configured + # above, actually mean something. + vhack.unbound.enable = lib.mkForce false; +} diff --git a/tests/common/dns/server.nix b/tests/common/dns/server.nix new file mode 100644 index 0000000..a3a603f --- /dev/null +++ b/tests/common/dns/server.nix @@ -0,0 +1,37 @@ +{ + nodes, + config, + ... +}: { + vhack = { + # Enable unbound, so we can resolve our own zones. + unbound.enable = true; + + nsd = { + enable = true; + openFirewall = true; + interfaces = [ + config.networking.primaryIPAddress + config.networking.primaryIPv6Address + ]; + + zones = { + "acme.nixos_test" = { + SOA = { + nameServer = "ns"; + adminEmail = "admin@server.com"; + serial = 2025012301; + }; + useOrigin = false; + + A = [ + nodes.acme.networking.primaryIPAddress + ]; + AAAA = [ + nodes.acme.networking.primaryIPv6Address + ]; + }; + }; + }; + }; +} diff --git a/tests/common/email/dkim/alice.com/private.age b/tests/common/email/dkim/alice.com/private.age new file mode 100644 index 0000000..cb590c6 --- /dev/null +++ b/tests/common/email/dkim/alice.com/private.age @@ -0,0 +1,11 @@ +-----BEGIN AGE ENCRYPTED FILE----- +YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHNzaC1lZDI1NTE5IFJzZ1dwUSA3bVJS +NjBTaitjUEhxMVZmejI1L3Fmd0xGK3ZFVlM2eVBaellDYWs3ZW5nClZOckc5cFFZ +dVlXYmxWZXpQU3lPTnlwTC9KUGNZak9VVS9aNzVEaFkrUG8KLT4gUy1ncmVhc2UK +Y21CMkZlQVdUUHVIclRpMk5yNmRTb3lwUVQzTWM2a0YwSjhUQU1kbTRqK1lrVUtk +ZkVVCi0tLSByRDVCeTJIK2JQWittWjlUWklSOWJaenluL1FLdXN2ZEM4bVlnU2U1 +RFk0CiAxOLq5ePeM8MemSES9Q86mBix3hooazHZZ7xCIQKnLvZmiHWCKUYw83PWl +QpmWI7S3wgdguOncKirQccJbNtVLYb/noYEBA1y7lOzO1FELPcFgevtB3kt5EAOA +6OaPsFKSsz71t++K011dgFUcnYmOtrqiQeKKEkZ0gey4+jNwf4buDygdiPOL/fQS +uJiIUwsLPqZI/FQ= +-----END AGE ENCRYPTED FILE----- diff --git a/tests/common/email/dkim/alice.com/public b/tests/common/email/dkim/alice.com/public new file mode 100644 index 0000000..be30723 --- /dev/null +++ b/tests/common/email/dkim/alice.com/public @@ -0,0 +1 @@ +LviKY6SBD2mtLJlUTon9AkWPYzB2D+Ivk0XnJOalAZM=
\ No newline at end of file diff --git a/tests/common/email/dkim/bob.com/private.age b/tests/common/email/dkim/bob.com/private.age new file mode 100644 index 0000000..70eddca --- /dev/null +++ b/tests/common/email/dkim/bob.com/private.age @@ -0,0 +1,12 @@ +-----BEGIN AGE ENCRYPTED FILE----- +YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHNzaC1lZDI1NTE5IFJzZ1dwUSAvSmk4 +YlQ3SElud2c3TWgxaUZCaC9mYytlbmNVdlVRcS9VTjlneFBBQ2hrCnE3b1dNdytR +Z0l5dVlMYUhVT0ZIMkFBYkNRKzZ6U1pBYStJTUJsNUEvN28KLT4gcX5kMWtnXi1n +cmVhc2UgczdieGAKNjNwRmVMYmN2cE5LaGFEOS9QZHFtaVhtZXI4dTFpazZhdUN4 +bUZ0cjQ4Y09nOVRjM2IzTGgweS9NbHkxMXlMSwpjdWhQekk0a0VnMTNFTXdjTmdl +bHluNDZWT0R5L25zbXlTL3l3NnRuTWhtNWs0dVByMWQ2TlEKLS0tIEZMK2dqRktZ +Y0hlN2l0ZVB4c3Exd3NsanRuTitrVklaaS9ZTU5ZWVF0cGsKuTNM9zBVFmOHkEqx +jMZaJQd/XqA4WzOi/iFi4WmDUDb8XcVsS0s/37fyZfeMW3YjoCzDb/treKMXyTDC +8l5N/xMG20UGC/Z16W24c/MXMFzpDLuFrjHiUtpQvBzwi6JUDMlKC8t0YWNcqQRr +2vu7qij0XgasxrGDg86hoc72YmYPmpHnE86O1il0PWy9sDRlkn6Ah/DUNg== +-----END AGE ENCRYPTED FILE----- diff --git a/tests/common/email/dkim/bob.com/public b/tests/common/email/dkim/bob.com/public new file mode 100644 index 0000000..915188c --- /dev/null +++ b/tests/common/email/dkim/bob.com/public @@ -0,0 +1 @@ +6USjzSE5zuUNrMdgsjAHFnq0BRKmyZh2IoXFHBCv3To=
\ No newline at end of file diff --git a/tests/common/email/dkim/gen_key.sh b/tests/common/email/dkim/gen_key.sh new file mode 100755 index 0000000..48b4434 --- /dev/null +++ b/tests/common/email/dkim/gen_key.sh @@ -0,0 +1,35 @@ +#! /usr/bin/env nix-shell +#! nix-shell -p rage -p openssl -p dash -i dash --impure + +# shellcheck shell=dash + +cd "$(dirname "$0")" || { + echo "No basedir?!" + exit 1 +} + +key_name="$1" +[ -z "$key_name" ] && { + echo "Usage: $0 KEY_NAME" + exit 2 +} + +[ -d "$key_name" ] || mkdir "$key_name" +cd "$key_name" || { + echo "Just created." + exit 1 +} + +openssl genpkey -algorithm ed25519 -out "private" +openssl pkey -in "private" -pubout -out "public.tmp" + +openssl asn1parse -in "public.tmp" -offset 12 -noout -out /dev/stdout | base64 --wrap 0 >"public" +rm "public.tmp" + +rage --encrypt \ + --armor \ + --recipient "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILxdvBk/PC9fC7B5vqe9TvygZKY6LgDQ2mXRdVrthBM/" \ + "private" >"private.age" +rm "private" + +# vim: ft=sh diff --git a/tests/common/email/dkim/mail.server1/private.age b/tests/common/email/dkim/mail.server1/private.age new file mode 100644 index 0000000..a97c70b --- /dev/null +++ b/tests/common/email/dkim/mail.server1/private.age @@ -0,0 +1,13 @@ +-----BEGIN AGE ENCRYPTED FILE----- +YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHNzaC1lZDI1NTE5IFJzZ1dwUSBndElV +WFFTcEZpTGwrTUg5WHk1MElLSU5ZZWp1NU5ocit4VGtnM09KZFNBCjNvaWVPR3Zt +RG14N2E3b0RwK21IUzBZZmg1UzFwakMwTVVOdDgrTTd4U1UKLT4geD9OYm0tZ3Jl +YXNlIDwgcjkKQUJtaDlVbzk3Slk3S1ozNS9STGwrdzhvWTlodWgxNVd1WVRadTV5 +VmFVUmRmSTV3ckIzYmpQYUFsMUxkdGNzUgo1UXozYzBCK3UxU1BPSnlvVVVxQjI2 +QVdWY0tBbUg1R3p5NmNaZ2RiVGNlL3pWN3FHZU5QOEN2VVdraDBzM1R2CgotLS0g +TElGejJDYUk4WlhxajdXekI4S0tUMVlrNmdxelpjUnBUa1VCU2krSFloawpUfMj8 +iqVP45yV8fON6fDUur6q/UYqTaaHhCW07LTsBZQpReG8LA+PiOhHw1TmPSJlc/JH +yEkwLachwvLGCGEO2yoFUFhYwoNhl3vrBsuDLXpqfNuoPrg3wcFXBdrg9zBjZ5Pc +C/rdzpysjW/52gKRCdGgFj2WyTW2wO2yVmmUk1RWhMabmdd+XLkKhynaMtWsBF0j +NQ3F +-----END AGE ENCRYPTED FILE----- diff --git a/tests/common/email/dkim/mail.server1/public b/tests/common/email/dkim/mail.server1/public new file mode 100644 index 0000000..6c9e653 --- /dev/null +++ b/tests/common/email/dkim/mail.server1/public @@ -0,0 +1 @@ +3/bsVrnWag3eMCuj78VpsHDQSONi97fIzY+WPKvAYWM=
\ No newline at end of file diff --git a/tests/common/email/dkim/mail.server2/private.age b/tests/common/email/dkim/mail.server2/private.age new file mode 100644 index 0000000..fbd88fc --- /dev/null +++ b/tests/common/email/dkim/mail.server2/private.age @@ -0,0 +1,11 @@ +-----BEGIN AGE ENCRYPTED FILE----- +YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHNzaC1lZDI1NTE5IFJzZ1dwUSBTcktS +L0ovODhxd2tyWFdINWRtbXNNYksyNzl6RUxRcTU2T251eVNhQlg4CjVzTVpnc0FC +eHBNaUtEQnJVRXVpTjg2c3gxcC90VXJ3cUJVaHZJY1pnb00KLT4gKDEkKS1ncmVh +c2UgYnYqQSBAVSU+CnVRbkRhdUhRS0Z6NGIybll1WVdmSmxzS0lxYlAwSXp0TnA4 +anRDSmQKLS0tIGxxSXRaM0lKeXRoeHFxWW9qN3Y1OE55b1FBVGJTZzB2RmFmZVk5 +eW94aW8KleHhm6fKalehWR0IfHYiC+0bsm0SeYjnJeA60hePdwikmr0QQv5D2xCX +Nf2QRuai/BpsiJpnvKUiP1uwkm5x6a2Zgwa7t8BwJ7SHqD4oJ+VgCsWMffLs55uC +A1pKLRmAI26cNt7oibVxNSCCuxZRWeCn+xAsQ393jVCUuDW2FkgyDsKFYHvKRpnC +BNfwDWWHJ+pifPPrqg== +-----END AGE ENCRYPTED FILE----- diff --git a/tests/common/email/dkim/mail.server2/public b/tests/common/email/dkim/mail.server2/public new file mode 100644 index 0000000..40b6ff7 --- /dev/null +++ b/tests/common/email/dkim/mail.server2/public @@ -0,0 +1 @@ +QmbJbp/b671OCOQa0Qx1XGl7c1jzFuASuzBr1f5ATpE=
\ No newline at end of file diff --git a/tests/common/email/functions.nix b/tests/common/email/functions.nix new file mode 100644 index 0000000..0628a2f --- /dev/null +++ b/tests/common/email/functions.nix @@ -0,0 +1,218 @@ +{ + pkgs, + vhackPackages, +}: { + scripts = { + expectNoNewMail = pkgs.writeShellScript "assert-empty-emails" '' + set -xe + + # fetchmail returns EXIT_CODE 1 when no new mail + fetchmail --verbose >&2 || [ "$?" -eq 1 ] || { + echo "Mail was not empty" >&2 + exit 1 + } + ''; + expectNewMail = pkgs.writeShellScript "assert-new-emails" '' + set -xe + + # fetchmail returns EXIT_CODE 1 when no new mail + fetchmail --verbose >&2 || [ "$?" -ne 1 ] || { + echo "No new mail" >&2 + exit 1 + } + ''; + expectNewSpamMail = pkgs.writeShellScript "assert-new-spam-emails" '' + set -xe + + # fetchmail returns EXIT_CODE 1 when no new mail + fetchmail --folder JUNK --verbose >&2 || [ "$?" -ne 1 ] || { + echo "No new spam mail" >&2 + exit 1 + } + ''; + }; + + mkMailServer = serverName: userName: { + config, + lib, + nodes, + ... + }: { + age.identityPaths = ["${../../common/email/hostKey}"]; + + systemd.tmpfiles.rules = [ + #- path mode user group - content + "f /passwords/${userName} 777 root root - ${userName}-password" + ]; + + age.secrets = { + "mailDkim" = { + file = ../../common/email/dkim + "/${serverName}/private.age"; + mode = "600"; + owner = "rspamd"; + group = "rspamd"; + }; + }; + + # Disable rspamd. rspamd can't do the dns lookups in the sandbox for + # determining if something is spam or not. Therefore it just rejects every mail with + # 'Try again later.'. + # services.rspamd.enable = lib.mkForce false; + # users.users.rspamd.group = "rspamd"; + # users.groups.rspamd = {}; + # + # services.postfix.settings.main = { + # smtpd_milters = lib.mkForce []; + # non_smtpd_milters = lib.mkForce []; + # }; + # mailserver.dkim.enable = false; + services = { + rspamd = { + locals = { + "asn.conf".text = lib.mkForce '' + enabled = false; + ''; + "rbl.conf".text = lib.mkForce '' + enabled = false; + ''; + "greylist.conf".text = lib.mkForce '' + enabled = false; + ''; + }; + }; + }; + + vhack = { + mail = { + enable = true; + fqdn = serverName; + domains = [ + serverName + ]; + + security.dkimKeys."${serverName}" = { + dkimPrivateKeyPath = config.age.secrets."mailDkim".path; + dkimPublicKey = + builtins.readFile (../../common/email/dkim + "/${serverName}/public"); + keyAlgorithm = "rsa-sha-256"; + }; + + accounts = { + "${userName}@${serverName}" = { + passwordFile = "/passwords/${userName}"; + }; + }; + }; + }; + }; + + mkDnsZone = serverName: {config, ...}: let + cfg = config.vhack.mail; + + keyAlgoToKeyType = keyAlgo: + if keyAlgo == "ed25519-sha256" + then "ed25519" + else if keyAlgo == "rsa-sha-256" || keyAlgo == "rsa-sha-1" + then "rsa" + else builtins.throw "Impossible"; + in { + "${serverName}" = { + MX = [ + { + preference = 10; + exchange = "${serverName}."; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc6376.html#section-3.6.1 + # https://www.rfc-editor.org/rfc/rfc6376.html#section-7.5 + DKIM = [ + { + selector = "mail"; + k = keyAlgoToKeyType cfg.security.dkimKeys."${serverName}".keyAlgorithm; + p = cfg.security.dkimKeys."${serverName}".dkimPublicKey; + s = ["email"]; + t = ["s"]; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc7489.html#section-6.3 + DMARC = [ + { + adkim = "strict"; + aspf = "strict"; + fo = ["0" "1" "d" "s"]; + p = "quarantine"; + rua = "admin@vhack.eu"; + ruf = ["admin@vhack.eu"]; + } + ]; + + # https://www.rfc-editor.org/rfc/rfc7208.html + # NOTE(@bpeetz): This server might not be directly sending mail, but it is still required for + # the SMTP EHLO check. <2025-02-25> + TXT = [ + (builtins.concatStringsSep " " + [ + "v=spf1" # The version. + "+mx" # Allow mail from this domain MX record. + "-all" # Reject all other emails if the previous mechanism did not match. + ]) + ]; + }; + }; + + mkUser = user: mailServer: {nodes, ...}: { + environment.systemPackages = [ + vhackPackages.fetchmail-common-name + pkgs.msmtp + pkgs.procmail + ]; + + users.users."${user}" = {isNormalUser = true;}; + + systemd.tmpfiles.rules = [ + "d /home/${user}/mail 0700 ${user} users - -" + "L /home/${user}/.fetchmailrc - - - - /etc/homeSetup/.fetchmailrc" + "L /home/${user}/.procmailrc - - - - /etc/homeSetup/.procmailrc" + "L /home/${user}/.msmtprc - - - - /etc/homeSetup/.msmtprc" + ]; + + environment.etc = { + "homeSetup/.fetchmailrc" = { + text = '' + poll "${mailServer}" protocol IMAP + username "${user}@${mailServer}" + password "${user}-password" + ssl + mda procmail; + ''; + mode = "0600"; + inherit user; + }; + "homeSetup/.procmailrc" = { + text = '' + DEFAULT=$HOME/mail + ''; + mode = "0600"; + inherit user; + }; + "homeSetup/.msmtprc" = { + text = '' + account ${user} + host ${mailServer} + domain ${mailServer} + port 465 + from ${user}@${mailServer} + user ${user}@${mailServer} + password ${user}-password + auth on + tls on + tls_starttls off + ''; + mode = "0600"; + inherit user; + }; + }; + }; +} diff --git a/tests/common/email/hostKey b/tests/common/email/hostKey new file mode 100644 index 0000000..79c9d6c --- /dev/null +++ b/tests/common/email/hostKey @@ -0,0 +1,7 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACC8XbwZPzwvXwuweb6nvU78oGSmOi4A0Npl0XVa7YQTPwAAAJjFZPqHxWT6 +hwAAAAtzc2gtZWQyNTUxOQAAACC8XbwZPzwvXwuweb6nvU78oGSmOi4A0Npl0XVa7YQTPw +AAAEA9D5AP+Uqhrg8rPx2DjgucjfnJknkk7lkeKHMV04ZZv7xdvBk/PC9fC7B5vqe9Tvyg +ZKY6LgDQ2mXRdVrthBM/AAAAFSAnUHVibGljIHRlc3Rpbmcga2V5Jw== +-----END OPENSSH PRIVATE KEY----- diff --git a/tests/default.nix b/tests/default.nix index d9b354a..0c4038a 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -1,13 +1,354 @@ { - specialArgs, - nixLib, - pkgs, + packageSets, + module_args, + special_args, + extra_lib, + sources, }: let - tests = nixLib.mkByName { + splitAttr = attr: let + pairs = builtins.attrNames attr; + firstName = builtins.elemAt pairs 0; + name = + if (builtins.length pairs) == 1 + then firstName + else builtins.throw "The name value pair (`${firstName}` and some more) has more than one name value pair."; + in { + inherit name; + value = attr.${name}; + }; + + nodeImports = [ + ./common/acme/client.nix + ./common/dns/client.nix + + ../modules + { + _module.args = module_args; + } + ]; + + vhack.runTest = { + name, + # Node definition, like in a normal nixos vm test. + nodes ? {}, + # Extra DNS configuration with the node's config as input. + # Example: + # ``` + # { + # server1 = {config, ...}: { + # "domain.example.org" = { + # TXT = [ "test" ]; + # }; + # }; + # } + # ``` + # That will add the TXT record to the `domain.example.org` domain, the `config` will + # be from the `server1` node. + dns ? {}, + # Server domains that all clients and the server can resolve via dns. + # The format follows the common one, e.g.: + # `{nodeName = "domain.example.com";}` + # means, that `domain.example.com` resolves to the node with name `nodeName`. + serverDomains ? [], + # Services to wait for. + # The format follows the common one, e.g.: + # `{nodeName = "example.service";}` + # means, that the test will not start, until `example.service` on the node with name + # `nodeName` has started. + services ? [], + # Open ports to wait for. + # The format follows the common one, e.g.: + # `{nodeName = 993;}` + # means, that the test will not start, until port `993` on the node with name + # `nodeName` is opened. + ports ? [], + # If `true`, will ignore this test. + ignore ? null, + # Should this test use the stable nixpkgs? + stable ? true, + testScript ? {_, ...}: "", + }: let + # Apparently the default's (e.g. `serivces ? []`), are not applied for the `@args` + # syntax. + args = {inherit dns ignore name nodes ports serverDomains services testScript;}; + pkgs = + if stable + then packageSets.stable + else packageSets.unstable; + in + pkgs.testers.runNixOSTest { + inherit (args) name; + + meta.broken = pkgs.lib.mkIf (args.ignore != null) true; + + node = { + specialArgs = special_args; + + # Use the nixpkgs as constructed by the `nixpkgs.*` options + pkgs = packageSets.unstable.lib.mkForce null; + }; + + nodes = pkgs.lib.mkMerge [ + { + acme = { + imports = [ + ./common/acme/server.nix + ./common/dns/client.nix + + ../modules + { + _module.args = module_args; + } + ]; + }; + name_server = {nodes, ...}: { + imports = [ + ./common/acme/client.nix + ./common/dns/server.nix + + ../modules + { + _module.args = module_args; + } + ]; + + vhack.nsd.zones = let + mkDomain = attr: let + split = splitAttr attr; + in { + name = "${split.value}"; + value = { + SOA = { + nameServer = "ns"; + adminEmail = "admin@server.com"; + serial = 2025012301; + }; + useOrigin = false; + + A = [ + nodes.${split.name}.networking.primaryIPAddress + ]; + AAAA = [ + nodes.${split.name}.networking.primaryIPv6Address + ]; + }; + }; + in + builtins.listToAttrs (builtins.map mkDomain args.serverDomains); + }; + } + + (pkgs.lib.mapAttrs' (nodeName: dnsOverride: { + name = "name_server"; + value = {nodes, ...}: { + vhack.nsd.zones = dnsOverride {config = nodes."${nodeName}";}; + }; + }) + args.dns) + + args.nodes + (builtins.mapAttrs (_: _: { + imports = nodeImports; + }) + args.nodes) + ]; + + testScript = {nodes, ...} @ testScriptInput: let + acme = import ./common/acme {inherit pkgs;}; + + waitForServices = builtins.concatStringsSep "\n" ( + builtins.map (attr: let + split = splitAttr attr; + name = + if builtins.isAttrs split.value + then split.value.name + else split.value; + should_be_started = + if builtins.isAttrs split.value + then + if split.value.should_be_started + then "True" + else "False" + else "False"; + in " maybe_wait(${split.name},\"${name}\", ${should_be_started})") + args.services + ); + waitForPorts = builtins.concatStringsSep "\n" ( + builtins.map ( + attr: let + split = splitAttr attr; + in " ${split.name}.wait_for_open_port(${builtins.toString split.value})" + ) + args.ports + ); + + acmeOnline = builtins.concatStringsSep "\n" (builtins.map (attr: let + split = splitAttr attr; + in " status.append(acme_online(${split.name}, \"${split.value}\", renewRan.get(\"acme-order-renew-${split.value}.service\", False)))") + args.serverDomains); + + allRunning = + builtins.concatStringsSep "\n" (builtins.map (name: " all_services_running(${name})") + (builtins.attrNames args.nodes)); + + optional = condition: value: + if condition + then value + else ""; + in + acme.prepare (builtins.attrNames args.nodes) + # The acme code runs `start_all` before it hands execution back to us. + # So we don't need to run it. + ( + optional (args.services != [] || args.serverDomains != []) + # Python + '' + def unit_exists(host, unitName: str) -> bool: + (status, _) = host.execute(f"test -f '/etc/systemd/system/{unitName}'") + return status == 0 + + wasAlive: bool + deadCounter: int + def run_and_wait(host, unit: str): + global wasAlive + global deadCounter + + wasAlive = False + deadCounter = 0 + + def wait_state(_last_try: bool) -> bool: + global wasAlive + global deadCounter + + state = host.get_unit_property(unit, "SubState") + host.log(f"(waiting) {unit} -> {state}") + + match state: + case "failed": + assert False, f'Unit "{unit}" reached state "{state}"' + case "start" | "active" | "running": + wasAlive = True + case "dead": + if wasAlive: + return True + else: + if deadCounter >= 5: + return True + + deadCounter = deadCounter + 1 + return False + + return False + + with host.nested(f"Waiting for unit {unit}"): + retry(wait_state) + '' + + optional (args.serverDomains != []) + # Python + '' + def acme_online(host, domain, renewRan): + from typing import assert_never + + unitMain = f"acme-{domain}.service" + unitRenew = f"acme-order-renew-{domain}.service" + + infoMain = host.get_unit_property(unitMain, "SubState") + infoRenew = host.get_unit_property(unitRenew, "SubState") + + match (infoMain, infoRenew): + case ("exited", "dead") | ("dead", "dead") if not renewRan: + # The unit might not exist, because we use the DNS values for + # generating this code (there is no needed mapping between DNS -> acme + # host). So we check, if it is an actual unit. + if unit_exists(host, unitMain): + host.start_job(f"acme-{domain}") + return ("Wait", unitRenew, host) + else: + return ("Done", None, None) + + case ("exited", "dead") | ("exited", "dead") if renewRan: + # The unit is done, so it should be good? + # Wait until nginx is up and running again (so nginx has time to reload + # after getting the new certificates.) + host.wait_for_unit("nginx") + host.require_unit_state(unitMain, "active") + host.succeed(f"${pkgs.lib.getExe pkgs.openssl} s_client -connect {domain}:443 -verify_return_error </dev/null") + return ("Done", None, None) + + case (_, "running") | (_, "start"): + # It's currently running, let's wait + return ("Wait", unitRenew, host) + + case other: + assert False, f"Wrong unit sub-states for ({unitMain},{unitRenew}): {other}" + assert_never() # i.e. unreachable + + with subtest("Ensure, that all acme certificates have been fetched"): + renewRan = {} + while True: + status = [] + ${acmeOnline} + done = True + for (state, unit, host) in status: + if state == "Wait": + run_and_wait(host, unit) + renewRan[unit] = True + if state != "Done": + done = False + if done: + break + '' + + optional (args.services != []) + # Python + '' + def maybe_wait(host, unit: str, should_start: bool): + if unit_exists(host, unit): + if should_start: + host.start_job(unit.removesuffix(".service")) + run_and_wait(host, unit) + else: + host.wait_for_unit(unit) + else: + assert False, f"Unit '{unit}' does not exist, test misconfigured" + + with subtest("Waiting for units"): + ${waitForServices} + '' + + optional (args.ports != []) + # Python + '' + with subtest("Waiting for ports"): + ${waitForPorts} + '' + + + # Python + '' + def all_services_running(host): + import json + (status, output) = host.systemctl("list-units --state=failed --plain --no-pager --output=json") + host_failed = json.loads(output) + assert len(host_failed) == 0, f"Expected zero failing services, but found: {json.dumps(host_failed, indent=4)}" + + with subtest("All services running"): + ${allRunning} + + ${(args.testScript testScriptInput)} + + with subtest("All services running"): + ${allRunning} + '' + ); + }; + + tests = extra_lib.mkByName { baseDirectory = ./by-name; fileName = "test.nix"; finalizeFunction = name: value: - import value (nixLib.warnMerge specialArgs {inherit pkgs;} "the test args set"); + import value { + inherit packageSets vhack sources; + inherit (packageSets.unstable) lib; + ownName = name; + }; }; in tests |
