From 5828af9fc19e18dc85e49fcc1a251a7eb25d909c Mon Sep 17 00:00:00 2001 From: Max Audron Date: Fri, 11 Aug 2023 16:51:35 +0200 Subject: init --- modules/bgp/default.nix | 19 + modules/cri-o/default.nix | 159 + modules/crypto/default.nix | 90 + modules/default.nix | 50 + modules/hetzner/default.nix | 24 + modules/image/default.nix | 12 + modules/k3s/default.nix | 128 + modules/kubernetes/default.nix | 160 + modules/matrix/conduit.nix | 142 + modules/matrix/default.nix | 73 + modules/matrix/mautrix-slack.nix | 194 + modules/matrix/mx-puppet-slack.nix | 132 + modules/matrix/options.nix | 38 + .../matrix/patches/heisenbridge_channel_name.patch | 13 + .../matrix/patches/heisenbridge_private_name.patch | 13 + .../patches/heisenbridge_user_presence.patch | 103 + modules/matrix/pkgs/generate.sh | 20 + modules/matrix/pkgs/mautrix-slack.nix | 26 + modules/matrix/pkgs/mx-puppet-slack.nix | 49 + modules/matrix/pkgs/node-composition.nix | 17 + modules/matrix/pkgs/node-env.nix | 689 ++++ modules/matrix/pkgs/node-packages.nix | 4275 ++++++++++++++++++++ modules/matrix/pkgs/slack_presence.patch | 21 + modules/nix-settings.nix | 38 + modules/users/default.nix | 20 + modules/vultr/default.nix | 45 + modules/wireguard/default.nix | 67 + modules/wireguard/options.nix | 71 + modules/wireguard/roaming.nix | 64 + modules/zfs/default.nix | 111 + 30 files changed, 6863 insertions(+) create mode 100644 modules/bgp/default.nix create mode 100644 modules/cri-o/default.nix create mode 100644 modules/crypto/default.nix create mode 100644 modules/default.nix create mode 100644 modules/hetzner/default.nix create mode 100644 modules/image/default.nix create mode 100644 modules/k3s/default.nix create mode 100644 modules/kubernetes/default.nix create mode 100644 modules/matrix/conduit.nix create mode 100644 modules/matrix/default.nix create mode 100644 modules/matrix/mautrix-slack.nix create mode 100644 modules/matrix/mx-puppet-slack.nix create mode 100644 modules/matrix/options.nix create mode 100644 modules/matrix/patches/heisenbridge_channel_name.patch create mode 100644 modules/matrix/patches/heisenbridge_private_name.patch create mode 100644 modules/matrix/patches/heisenbridge_user_presence.patch create mode 100755 modules/matrix/pkgs/generate.sh create mode 100644 modules/matrix/pkgs/mautrix-slack.nix create mode 100644 modules/matrix/pkgs/mx-puppet-slack.nix create mode 100644 modules/matrix/pkgs/node-composition.nix create mode 100644 modules/matrix/pkgs/node-env.nix create mode 100644 modules/matrix/pkgs/node-packages.nix create mode 100644 modules/matrix/pkgs/slack_presence.patch create mode 100644 modules/nix-settings.nix create mode 100644 modules/users/default.nix create mode 100644 modules/vultr/default.nix create mode 100644 modules/wireguard/default.nix create mode 100644 modules/wireguard/options.nix create mode 100644 modules/wireguard/roaming.nix create mode 100644 modules/zfs/default.nix (limited to 'modules') diff --git a/modules/bgp/default.nix b/modules/bgp/default.nix new file mode 100644 index 0000000..79187da --- /dev/null +++ b/modules/bgp/default.nix @@ -0,0 +1,19 @@ +{ config, lib, pkgs, ... }: + +{ + networking.interfaces.eth0.ipv4.addresses = [ + { + address = "217.163.29.14"; + prefixLength = 32; + } + { + address = "209.250.238.254"; + prefixLength = 32; + } + ]; + + networking.interfaces.eth0.ipv6.addresses = [{ + address = "2a0f:9400:8020::"; + prefixLength = 48; + }]; +} diff --git a/modules/cri-o/default.nix b/modules/cri-o/default.nix new file mode 100644 index 0000000..0a1860a --- /dev/null +++ b/modules/cri-o/default.nix @@ -0,0 +1,159 @@ +{ config, lib, pkgs, utils, ... }: + +with lib; +let + cfg = config.virtualisation.cri-o; + + crioPackage = (pkgs.cri-o.override { inherit (cfg) extraPackages; }); + + format = pkgs.formats.toml { }; + + cfgFile = format.generate "00-default.conf" cfg.settings; +in +{ + imports = [ + (mkRenamedOptionModule [ "virtualisation" "cri-o" "registries" ] [ "virtualisation" "containers" "registries" "search" ]) + ]; + + meta = { + maintainers = teams.podman.members; + }; + + options.virtualisation.cri-o = { + enable = mkEnableOption "Container Runtime Interface for OCI (CRI-O)"; + + storageDriver = mkOption { + type = types.enum [ "btrfs" "overlay" "vfs" "zfs" ]; + default = "overlay"; + description = "Storage driver to be used"; + }; + + logLevel = mkOption { + type = types.enum [ "trace" "debug" "info" "warn" "error" "fatal" ]; + default = "info"; + description = "Log level to be used"; + }; + + pauseImage = mkOption { + type = types.nullOr types.str; + default = null; + description = "Override the default pause image for pod sandboxes"; + example = "k8s.gcr.io/pause:3.2"; + }; + + pauseCommand = mkOption { + type = types.nullOr types.str; + default = null; + description = "Override the default pause command"; + example = "/pause"; + }; + + runtime = mkOption { + type = types.nullOr types.str; + default = null; + description = "Override the default runtime"; + example = "crun"; + }; + + extraPackages = mkOption { + type = with types; listOf package; + default = [ ]; + example = literalExpression '' + [ + pkgs.gvisor + ] + ''; + description = '' + Extra packages to be installed in the CRI-O wrapper. + ''; + }; + + package = mkOption { + type = types.package; + default = crioPackage; + internal = true; + description = '' + The final CRI-O package (including extra packages). + ''; + }; + + networkDir = mkOption { + type = types.nullOr types.path; + default = null; + description = "Override the network_dir option."; + internal = true; + }; + + settings = mkOption { + type = format.type; + default = { }; + description = '' + Configuration for cri-o, see + . + ''; + }; + }; + + config = mkIf cfg.enable { + environment.systemPackages = [ cfg.package pkgs.cri-tools ]; + + environment.etc."crictl.yaml".source = utils.copyFile "${pkgs.cri-o-unwrapped.src}/crictl.yaml"; + + virtualisation.cri-o.settings.crio = { + storage_driver = cfg.storageDriver; + + image = { + pause_image = mkIf (cfg.pauseImage != null) cfg.pauseImage; + pause_command = mkIf (cfg.pauseCommand != null) cfg.pauseCommand; + }; + + network = { + plugin_dirs = [ "${pkgs.cni-plugins}/bin" ]; + network_dir = mkIf (cfg.networkDir != null) cfg.networkDir; + }; + + runtime = { + cgroup_manager = "systemd"; + log_level = cfg.logLevel; + manage_ns_lifecycle = true; + pinns_path = "${cfg.package}/bin/pinns"; + hooks_dir = + optional (config.virtualisation.containers.ociSeccompBpfHook.enable) + config.boot.kernelPackages.oci-seccomp-bpf-hook; + + default_runtime = mkIf (cfg.runtime != null) cfg.runtime; + runtimes = mkIf (cfg.runtime != null) { + "${cfg.runtime}" = { }; + }; + }; + }; + + environment.etc."cni/net.d/10-crio-bridge.conf".source = utils.copyFile "${pkgs.cri-o-unwrapped.src}/contrib/cni/10-crio-bridge.conf"; + environment.etc."cni/net.d/99-loopback.conf".source = utils.copyFile "${pkgs.cri-o-unwrapped.src}/contrib/cni/99-loopback.conf"; + environment.etc."crio/crio.conf.d/00-default.conf".source = cfgFile; + + # Enable common /etc/containers configuration + virtualisation.containers.enable = true; + + systemd.services.crio = { + description = "Container Runtime Interface for OCI (CRI-O)"; + documentation = [ "https://github.com/cri-o/cri-o" ]; + wantedBy = [ "multi-user.target" ]; + after = [ "network.target" ]; + path = [ cfg.package ]; + serviceConfig = { + Type = "notify"; + ExecStart = "${cfg.package}/bin/crio"; + ExecReload = "/bin/kill -s HUP $MAINPID"; + TasksMax = "infinity"; + LimitNOFILE = "1048576"; + LimitNPROC = "1048576"; + LimitCORE = "infinity"; + OOMScoreAdjust = "-999"; + TimeoutStartSec = "0"; + Restart = "on-abnormal"; + }; + restartTriggers = [ cfgFile ]; + }; + }; +} diff --git a/modules/crypto/default.nix b/modules/crypto/default.nix new file mode 100644 index 0000000..578fc0c --- /dev/null +++ b/modules/crypto/default.nix @@ -0,0 +1,90 @@ +{ pkgs, config, lib, ... }: + +with lib; + +let + cfg = config.secrets; + + secret = types.submodule { + options = { + source = mkOption { + type = types.path; + description = "local secret path"; + }; + + dest = mkOption { + type = types.str; + description = "where to write the decrypted secret to"; + }; + + owner = mkOption { + default = "root"; + type = types.str; + description = "who should own the secret"; + }; + + group = mkOption { + default = "root"; + type = types.str; + description = "what group should own the secret"; + }; + + permissions = mkOption { + default = "0400"; + type = types.str; + description = "Permissions expressed as octal."; + }; + }; + }; + + # metadata = lib.importTOML ../../ops/metadata/hosts.toml; + + mkSecretOnDisk = name: + { source, ... }: + pkgs.stdenv.mkDerivation { + name = "${name}-secret"; + phases = "installPhase"; + buildInputs = [ pkgs.rage ]; + installPhase = '' + rage -a -r '${config.pubKey}' -o "$out" '${source}' + ''; + }; + + mkService = name: + { source, dest, owner, group, permissions, ... }: { + description = "decrypt secret for ${name}"; + wantedBy = [ "multi-user.target" ]; + + serviceConfig.Type = "oneshot"; + + script = with pkgs; '' + rm -rf ${dest} + mkdir -p ${dirOf dest} + "${rage}"/bin/rage -d -i /etc/ssh/ssh_host_ed25519_key -o '${dest}' '${ + mkSecretOnDisk name { inherit source; } + }' + chown '${owner}':'${group}' '${dest}' + chmod '${permissions}' '${dest}' + ''; + }; +in { + options = { + pubKey = mkOption { + type = types.str; + description = "host public key used for encrypting secrets"; + }; + + secrets = mkOption { + type = types.attrsOf secret; + description = "secret configuration"; + default = { }; + }; + }; + + config.systemd.services = let + units = mapAttrs' (name: info: { + name = "${name}-key"; + value = (mkService name info); + }) cfg; + in units; +} diff --git a/modules/default.nix b/modules/default.nix new file mode 100644 index 0000000..7f71fab --- /dev/null +++ b/modules/default.nix @@ -0,0 +1,50 @@ +{ config, nixpkgs, pkgs, lib, ... }: + +{ + imports = [ + ./users + ./crypto + ./wireguard + ./nix-settings.nix + ]; + + # Time and Locale + time.timeZone = "UTC"; + i18n.defaultLocale = "en_US.UTF-8"; + console = { + font = "Lat2-Terminus16"; + keyMap = "us"; + }; + + # Default Packages Set + environment.systemPackages = with pkgs; [ vim htop wget nftables wireguard-tools ]; + + # Wireguard + wireguard = { + enable = lib.mkDefault false; + v4 = { network = lib.mkDefault "10.10.0.0"; }; + v6 = { + ula = lib.mkDefault "fd15:3d8c:d429:beef"; + gua = lib.mkDefault "2a0f:9400:8020:beef"; + }; + }; + + # Security + networking.firewall.enable = false; + security.sudo.wheelNeedsPassword = false; + services.openssh = { + enable = true; + passwordAuthentication = false; + permitRootLogin = "no"; + }; + + # CPU + powerManagement.cpuFreqGovernor = lib.mkDefault "ondemand"; + hardware.cpu.amd.updateMicrocode = + lib.mkDefault config.hardware.enableRedistributableFirmware; + hardware.cpu.intel.updateMicrocode = + lib.mkDefault config.hardware.enableRedistributableFirmware; + + # System state version + system.stateVersion = lib.mkDefault "23.05"; +} diff --git a/modules/hetzner/default.nix b/modules/hetzner/default.nix new file mode 100644 index 0000000..692ee20 --- /dev/null +++ b/modules/hetzner/default.nix @@ -0,0 +1,24 @@ +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = [ (modulesPath + "/profiles/qemu-guest.nix") ]; + + boot.initrd.availableKernelModules = [ "ata_piix" "uhci_hcd" "xen_blkfront" "vmw_pvscsi" ]; + boot.initrd.kernelModules = [ "nvme" ]; + boot.loader.grub.device = "/dev/sda"; + + fileSystems."/" = { device = "/dev/sda1"; fsType = "ext4"; }; + + networking = { + domain = "vapor.systems"; + usePredictableInterfaceNames = false; + enableIPv6 = true; + tempAddresses = "disabled"; + interfaces.eth0.useDHCP = true; + nameservers = [ "1.1.1.1" "8.8.8.8" ]; + + dhcpcd.extraConfig = '' + nohook resolv.conf + ''; + }; +} diff --git a/modules/image/default.nix b/modules/image/default.nix new file mode 100644 index 0000000..5903db3 --- /dev/null +++ b/modules/image/default.nix @@ -0,0 +1,12 @@ +{ config, lib, pkgs, ... }: + +{ + config = { + system.build.image = import { + name = "vapor-systems-image"; + format = "raw"; + diskSize = "auto"; + inherit config lib pkgs; + }; + }; +} diff --git a/modules/k3s/default.nix b/modules/k3s/default.nix new file mode 100644 index 0000000..e2aa335 --- /dev/null +++ b/modules/k3s/default.nix @@ -0,0 +1,128 @@ +{ config, lib, pkgs, ... }: + +with lib; +let + cfg = config.services.k3s; +in +{ + # interface + options.services.k3s = { + enable = mkEnableOption "k3s"; + + package = mkOption { + type = types.package; + default = pkgs.k3s; + defaultText = literalExpression "pkgs.k3s"; + description = "Package that should be used for k3s"; + }; + + role = mkOption { + description = '' + Whether k3s should run as a server or agent. + Note that the server, by default, also runs as an agent. + ''; + default = "server"; + type = types.enum [ "server" "agent" ]; + }; + + serverAddr = mkOption { + type = types.str; + description = "The k3s server to connect to. This option only makes sense for an agent."; + example = "https://10.0.0.10:6443"; + default = ""; + }; + + token = mkOption { + type = types.str; + description = '' + The k3s token to use when connecting to the server. This option only makes sense for an agent. + WARNING: This option will expose store your token unencrypted world-readable in the nix store. + If this is undesired use the tokenFile option instead. + ''; + default = ""; + }; + + tokenFile = mkOption { + type = types.nullOr types.path; + description = "File path containing k3s token to use when connecting to the server. This option only makes sense for an agent."; + default = null; + }; + + docker = mkOption { + type = types.bool; + default = false; + description = "Use docker to run containers rather than the built-in containerd."; + }; + + extraFlags = mkOption { + description = "Extra flags to pass to the k3s command."; + type = types.str; + default = ""; + example = "--no-deploy traefik --cluster-cidr 10.24.0.0/16"; + }; + + disableAgent = mkOption { + type = types.bool; + default = false; + description = "Only run the server. This option only makes sense for a server."; + }; + + configPath = mkOption { + type = types.nullOr types.path; + default = null; + description = "File path containing the k3s YAML config. This is useful when the config is generated (for example on boot)."; + }; + }; + + # implementation + + config = mkIf cfg.enable { + assertions = [ + { + assertion = cfg.role == "agent" -> (cfg.configPath != null || cfg.serverAddr != ""); + message = "serverAddr or configPath (with 'server' key) should be set if role is 'agent'"; + } + { + assertion = cfg.role == "agent" -> cfg.configPath != null || cfg.tokenFile != null || cfg.token != ""; + message = "token or tokenFile or configPath (with 'token' or 'token-file' keys) should be set if role is 'agent'"; + } + ]; + + virtualisation.docker = mkIf cfg.docker { + enable = mkDefault true; + }; + + environment.systemPackages = [ config.services.k3s.package ]; + + systemd.services.k3s = { + description = "k3s service"; + after = [ "network.service" "firewall.service" ] ++ (optional cfg.docker "docker.service"); + wants = [ "network.service" "firewall.service" ]; + wantedBy = [ "multi-user.target" ]; + path = optional config.boot.zfs.enabled config.boot.zfs.package; + serviceConfig = { + # See: https://github.com/rancher/k3s/blob/dddbd16305284ae4bd14c0aade892412310d7edc/install.sh#L197 + Type = if cfg.role == "agent" then "exec" else "notify"; + KillMode = "process"; + Delegate = "yes"; + Restart = "always"; + RestartSec = "5s"; + LimitNOFILE = 1048576; + LimitNPROC = "infinity"; + LimitCORE = "infinity"; + TasksMax = "infinity"; + ExecStart = concatStringsSep " \\\n " ( + [ + "${cfg.package}/bin/k3s ${cfg.role}" + ] ++ (optional cfg.docker "--docker") + ++ (optional cfg.disableAgent "--disable-agent") + ++ (optional (cfg.serverAddr != "") "--server ${cfg.serverAddr}") + ++ (optional (cfg.token != "") "--token ${cfg.token}") + ++ (optional (cfg.tokenFile != null) "--token-file ${cfg.tokenFile}") + ++ (optional (cfg.configPath != null) "--config ${cfg.configPath}") + ++ [ cfg.extraFlags ] + ); + }; + }; + }; +} diff --git a/modules/kubernetes/default.nix b/modules/kubernetes/default.nix new file mode 100644 index 0000000..0e6e522 --- /dev/null +++ b/modules/kubernetes/default.nix @@ -0,0 +1,160 @@ +{ config, lib, pkgs, nixpkgs, ... }: + +with lib; +let + cfg = config.kubernetes; + + clusterDomain = "kube.vapor.systems"; + + externalIP = { + v4 = if cfg.externalIP.v4 != "" then + cfg.externalIP.v4 + else + (lib.elemAt config.networking.interfaces.eth0.ipv4.addresses 0).address; + v6 = if cfg.externalIP.v6 != "" then + cfg.externalIP.v6 + else + (lib.elemAt config.networking.interfaces.eth0.ipv6.addresses 0).address; + }; + internalIP = { + v4 = config.wireguard.v4.address; + v6 = "${config.wireguard.v6.ula}::${config.wireguard.v6.address}"; + }; +in { + disabledModules = + [ "virtualisation/cri-o.nix" "services/cluster/k3s/default.nix" ]; + imports = [ ../cri-o ../k3s ]; + + options = { + kubernetes = { + role = mkOption { + type = types.enum [ "server" "agent" ]; + description = "Act as control plane or worker node"; + }; + + labels = mkOption { + type = types.attrs; + description = "Address the k8s api is advertised on"; + default = { }; + }; + taints = mkOption { + type = types.attrs; + description = "Address the k8s api is advertised on"; + default = { }; + }; + + advertiseAddress = mkOption { + type = types.str; + description = "Address the k8s api is advertised on"; + }; + + externalIP = { + v4 = mkOption { + type = types.str; + description = "External Node IP Address"; + default = ""; + }; + v6 = mkOption { + type = types.str; + description = "External Node IP Address"; + default = ""; + }; + }; + }; + }; + + config = { + nixpkgs.overlays = [ + (self: super: { + cri-o = super.callPackage ../../pkgs/cri-o { }; + k3s = super.callPackage ../../pkgs/k3s { }; + }) + ]; + + networking.extraHosts = '' + 10.10.0.1 ${clusterDomain} + fd15:3d8c:d429:beef::1 ${clusterDomain} + ''; + + environment.etc = { + "k3s/config.yaml" = { + text = generators.toJSON { } ({ + # cluster-init = true; + token = "YPoyiPeBpQpB7oK8"; + + container-runtime-endpoint = "/run/crio/crio.sock"; + + node-ip = "${internalIP.v4},${internalIP.v6}"; + node-external-ip = "${internalIP.v4},${internalIP.v6}"; + + node-label = + attrValues (mapAttrs (n: v: "${n}=${toString v}") cfg.labels); + node-taint = + attrValues (mapAttrs (n: v: "${n}=${toString v}") cfg.taints); + + kubelet-arg = "cgroup-driver=systemd"; + + no-flannel = true; + } // (if cfg.role == "server" then { + advertise-address = "${internalIP.v4}"; + + kube-controller-manager-arg = "node-cidr-mask-size-ipv6=72"; + + cluster-cidr = "10.102.0.0/16,fd15:3d8c:d429:0102::/64"; + service-cidr = "10.101.0.0/16,fd15:3d8c:d429:0101::/108"; + cluster-dns = "10.101.0.10"; + cluster-domain = clusterDomain; + + disable = [ "servicelb" "traefik" "local-storage" ]; + disable-kube-proxy = true; + disable-network-policy = true; + + flannel-backend = "none"; + } else + { })); + }; + }; + + services.k3s = { + enable = true; + role = cfg.role; + serverAddr = "https://10.10.0.1:6443"; + configPath = "/etc/k3s/config.yaml"; + }; + + virtualisation.cri-o = { + enable = true; + settings = { + crio = { + network.plugin_dir = "/opt/cni/bin"; + default_runtime = "crun"; + runtime = { + allowed_devices = [ "/dev/fuse" ]; + default_sysctls = [ + "net.ipv4.ping_group_range=0 2147483647" + ]; + workloads = { + gitlab = { + activation_annotation = "io.kubernetes.cri-o.workload/gitlab"; + allowed_annotations = [ + "io.kubernetes.cri-o.userns-mode" + "io.kubernetes.cri-o.Devices" + "io.kubernetes.cri-o.ShmSize" + ]; + }; + }; + runtimes.crun = { + runtime_type = "oci"; + runtime_root = "/run/crun"; + allowed_annotations = [ + "io.kubernetes.cri-o.userns-mode" + "io.kubernetes.cri-o.Devices" + "io.kubernetes.cri-o.ShmSize" + ]; + }; + }; + }; + }; + }; + }; +} diff --git a/modules/matrix/conduit.nix b/modules/matrix/conduit.nix new file mode 100644 index 0000000..10612b9 --- /dev/null +++ b/modules/matrix/conduit.nix @@ -0,0 +1,142 @@ +{ config, lib, pkgs, ... }: + + +let + cfg = config.services.matrix; + + # Build a dervation that stores the content of `${server_name}/.well-known/matrix/server` + well_known_server = pkgs.writeText "well-known-matrix-server" '' + { + "m.server": "${cfg.matrix_hostname}" + } + ''; + + # Build a dervation that stores the content of `${server_name}/.well-known/matrix/client` + well_known_client = pkgs.writeText "well-known-matrix-client" '' + { + "m.homeserver": { + "base_url": "https://${cfg.matrix_hostname}" + } + } + ''; +in +{ + # Configure Conduit itself + services.matrix-conduit = { + enable = true; + + # This causes NixOS to use the flake defined in this repository instead of + # the build of Conduit built into nixpkgs. + package = pkgs.unstable.matrix-conduit; + + settings.global = { + inherit (cfg) server_name; + + allow_registration = true; + allow_federation = true; + trusted_servers = [ "matrix.org" ]; + enable_lightning_bolt = false; + }; + }; + + security.acme = { + acceptTerms = true; + defaults = { + email = cfg.admin_email; + }; + }; + + # ACME data must be readable by the NGINX user + users.users.nginx.extraGroups = [ + "acme" + ]; + + # Configure NGINX as a reverse proxy + services.nginx = { + enable = true; + recommendedProxySettings = true; + + virtualHosts = { + "${cfg.matrix_hostname}" = { + forceSSL = true; + enableACME = true; + + listen = [ + { + addr = "0.0.0.0"; + port = 443; + ssl = true; + } + { + addr = "0.0.0.0"; + port = 8448; + ssl = true; + } + { + addr = "[::0]"; + port = 443; + ssl = true; + } + { + addr = "[::0]"; + port = 8448; + ssl = true; + } + ]; + + locations."/_matrix/" = { + proxyPass = "http://backend_conduit$request_uri"; + proxyWebsockets = true; + extraConfig = '' + proxy_set_header Host $host; + proxy_buffering off; + ''; + }; + + extraConfig = '' + merge_slashes off; + ''; + }; + + "${cfg.server_name}" = { + forceSSL = true; + enableACME = true; + + locations."=/.well-known/matrix/server" = { + # Use the contents of the derivation built previously + alias = "${well_known_server}"; + + extraConfig = '' + # Set the header since by default NGINX thinks it's just bytes + default_type application/json; + ''; + }; + + locations."=/.well-known/matrix/client" = { + # Use the contents of the derivation built previously + alias = "${well_known_client}"; + + extraConfig = '' + # Set the header since by default NGINX thinks it's just bytes + default_type application/json; + + # https://matrix.org/docs/spec/client_server/r0.4.0#web-browser-clients + add_header Access-Control-Allow-Origin "*"; + ''; + }; + }; + }; + + upstreams = { + "backend_conduit" = { + servers = { + "localhost:${toString config.services.matrix-conduit.settings.global.port}" = { }; + }; + }; + }; + }; + + # Open firewall ports for HTTP, HTTPS, and Matrix federation + networking.firewall.allowedTCPPorts = [ 80 443 8448 ]; + networking.firewall.allowedUDPPorts = [ 80 443 8448 ]; +} diff --git a/modules/matrix/default.nix b/modules/matrix/default.nix new file mode 100644 index 0000000..7964f9b --- /dev/null +++ b/modules/matrix/default.nix @@ -0,0 +1,73 @@ +{ config, lib, pkgs, secrets, ... }: + + +let cfg = config.services.matrix; +in +{ + imports = [ + ./options.nix + ./conduit.nix + ./mautrix-slack.nix + ]; + + services.matrix = { + server_name = "vapor.systems"; + admin_email = "info@cocaine.farm"; + }; + + services.heisenbridge = { + enable = true; + owner = "@audron:vapor.systems"; + homeserver = "https://${cfg.matrix_hostname}"; + # extraArgs = [ "--generate-compat" ]; + # + package = pkgs.heisenbridge.overrideAttrs (prev: rec { + version = "1.14.2"; + + src = pkgs.fetchFromGitHub { + owner = "hifi"; + repo = prev.pname; + rev = "refs/tags/v${version}"; + sha256 = "sha256-qp0LVcmWf5lZ52h0V58S6FoIM8RLOd6Y3FRb85j7KRg="; + }; + + patches = [ + ./patches/heisenbridge_channel_name.patch + ./patches/heisenbridge_private_name.patch + ./patches/heisenbridge_user_presence.patch + ]; + }); + + identd.enable = true; + }; + + + services.mautrix-slack = { + enable = true; + environmentFile = "/var/lib/mautrix-slack/secrets.env"; + settings = { + homeserver = { + address = "https://${cfg.matrix_hostname}"; + domain = cfg.server_name; + }; + + appservice = + let s = builtins.fromJSON (builtins.readFile "${secrets}/matrix/mautrix-slack.json"); + in + { + as_token = s.as_token; + hs_token = s.hs_token; + }; + + bridge = { + permissions = { + "*" = "relay"; + "vapor.systems" = "user"; + "@audron:vapor.systems" = "admin"; + }; + }; + }; + + configurePostgresql = true; + }; +} diff --git a/modules/matrix/mautrix-slack.nix b/modules/matrix/mautrix-slack.nix new file mode 100644 index 0000000..d0324a1 --- /dev/null +++ b/modules/matrix/mautrix-slack.nix @@ -0,0 +1,194 @@ +{ config, pkgs, lib, ... }: + +with lib; + +let + cfg = config.services.mautrix-slack; + dataDir = "/var/lib/mautrix-slack"; + registrationFile = "${dataDir}/slack-registration.yaml"; + settingsFormat = pkgs.formats.json { }; + settingsFile = settingsFormat.generate "mautrix-slack-config.json" cfg.settings; +in +{ + options = { + services.mautrix-slack = { + enable = mkEnableOption (lib.mdDoc "Mautrix-Slack, a Matrix-Slack hybrid puppeting/relaybot bridge"); + + package = mkOption { + type = types.package; + default = pkgs.callPackage ./pkgs/mautrix-slack.nix { }; + defaultText = "pkgs.mautrix-slack"; + example = "pkgs.mautrix-slack.override { … = …; }"; + description = lib.mdDoc '' + Package of the application to run, exposed for overriding purposes. + ''; + }; + + settings = mkOption rec { + apply = recursiveUpdate default; + type = settingsFormat.type; + default = { + homeserver = { + software = "standard"; + }; + + appservice = rec { + address = "http://${hostname}:${toString port}"; + hostname = "localhost"; + port = 29319; + + database = { + type = "postgres"; + uri = "postgres:///mautrix-slack?host=/run/postgresql&sslmode=disable"; + }; + + id = "slack"; + bot = { + username = "slackbot"; + }; + + # backfill = { + # enable = false; + # conversations_count = 200; + # unread_hours_threshold = 720; + # immediate_messages = 10; + # incremental = { + # messages_per_batch = 100; + # post_batch_delay = 20; + # max_messages = { + # channel = -1; + # group_dm = -1; + # dm = -1; + # }; + # }; + # }; + + # encryption = { + # allow = false; + # default = false; + # appservice = false; + # require = false; + # allow_key_sharing = false; + # verification_levels = { + # receive = "unverified"; + # send = "unverified"; + # share = "cross-signed-tofu"; + # }; + # rotation = { + # enable_custom = false; + # milliseconds = 604800000; + # messages = 100; + # }; + # }; + + # provisioning = { + # prefix = "/_matrix/provision"; + # shared_secret = "generate"; + # }; + }; + + logging = { + directory = "/var/log/mautrix"; + file_name_format = "slack-{{.Date}}-{{.Index}}.log"; + file_date_format = "2006-01-02"; + file_mode = 384; + timestamp_format = "Jan _2, 2006 15:04:05"; + print_level = "debug"; + print_json = false; + file_json = false; + }; + }; + }; + + environmentFile = mkOption { + type = types.nullOr types.path; + default = null; + description = lib.mdDoc '' + File containing environment variables to be passed to the mautrix-slack service. + Any config variable can be overridden by setting `MAUTRIX_SLACK_SOME_KEY` to override the `some.key` variable. + ''; + }; + + configurePostgresql = mkOption { + type = types.bool; + default = true; + description = lib.mdDoc '' + Enable PostgreSQL and create a user and database for mautrix-slack. The default `settings` reference this database, if you disable this option you must provide a database URL. + ''; + }; + }; + }; + + config = mkIf cfg.enable { + users.groups.mautrix-slack = { }; + + users.users.mautrix-slack = { + group = "mautrix-slack"; + isSystemUser = true; + }; + + services.postgresql = mkIf cfg.configurePostgresql { + enable = true; + ensureDatabases = [ "mautrix-slack" ]; + ensureUsers = [{ + name = "mautrix-slack"; + ensurePermissions = { + "DATABASE \"mautrix-slack\"" = "ALL PRIVILEGES"; + }; + }]; + }; + + systemd.services.mautrix-slack = rec { + wantedBy = [ "multi-user.target" ]; + wants = [ + "network-online.target" + ] ++ optional config.services.matrix-synapse.enable "matrix-synapse.service" + ++ optional cfg.configurePostgresql "postgresql.service"; + after = wants; + + preStart = '' + # generate the appservice's registration file if absent + if [ ! -f '${registrationFile}' ]; then + ${cfg.package}/bin/mautrix-slack -g -c ${settingsFile} \ + -r ${registrationFile} + fi + ''; + + serviceConfig = { + Type = "simple"; + Restart = "always"; + + User = "mautrix-slack"; + + NoNewPrivileges = true; + MemoryDenyWriteExecute = true; + PrivateDevices = true; + PrivateTmp = true; + ProtectHome = true; + ProtectSystem = "strict"; + ProtectControlGroups = true; + RestrictSUIDSGID = true; + RestrictRealtime = true; + LockPersonality = true; + ProtectKernelLogs = true; + ProtectKernelTunables = true; + ProtectHostname = true; + ProtectKernelModules = true; + PrivateUsers = true; + ProtectClock = true; + SystemCallArchitectures = "native"; + SystemCallErrorNumber = "EPERM"; + SystemCallFilter = "@system-service"; + + StateDirectory = baseNameOf dataDir; + LogsDirectory = "mautrix"; + LogsDirectoryMode = "0750"; + EnvironmentFile = cfg.environmentFile; + + ExecStart = '' + ${cfg.package}/bin/mautrix-slack --no-update --config=${settingsFile} --registration=${registrationFile} + ''; + }; + }; + }; +} diff --git a/modules/matrix/mx-puppet-slack.nix b/modules/matrix/mx-puppet-slack.nix new file mode 100644 index 0000000..5737319 --- /dev/null +++ b/modules/matrix/mx-puppet-slack.nix @@ -0,0 +1,132 @@ +{ config, pkgs, lib, ... }: + +with lib; + +let + dataDir = "/var/lib/mx-puppet-slack"; + registrationFile = "${dataDir}/slack-registration.yaml"; + cfg = config.services.mx-puppet-slack; + settingsFormat = pkgs.formats.json {}; + settingsFile = settingsFormat.generate "mx-puppet-slack-config.json" cfg.settings; + +in { + options = { + services.mx-puppet-slack = { + enable = mkEnableOption (lib.mdDoc '' + mx-puppet-slack is a slack puppeting bridge for matrix. + It handles bridging private and group DMs + ''); + + package = mkOption { + type = types.package; + default = pkgs.callPackage ./pkgs/mx-puppet-slack.nix {}; + defaultText = "pkgs.mx-puppet-slack"; + example = "pkgs.mx-puppet-slack.override { … = …; }"; + description = lib.mdDoc '' + Package of the application to run, exposed for overriding purposes. + ''; + }; + + settings = mkOption rec { + apply = recursiveUpdate default; + inherit (settingsFormat) type; + default = { + bridge = { + port = 8432; + }; + presence = { + enabled = true; + interval = 500; + }; + provisioning.whitelist = [ ]; + + # variables are preceded by a colon. + namePatterns = { + user = ":name"; + room = ":name[:team? - :team,]"; + group = ":name"; + }; + + #defaults to sqlite but can be configured to use postgresql with + #connstring + database.filename = "${dataDir}/database.db"; + logging = { + console = "info"; + lineDateFormat = "MMM-D HH:mm:ss.SSS"; + }; + }; + example = literalExpression '' + { + bridge = { + bindAddress = "localhost"; + domain = "example.com"; + homeserverUrl = "https://example.com"; + }; + provisioning.whitelist = [ "@admin:example.com" ]; + relay.whitelist = [ "@.*:example.com" ]; + } + ''; + description = lib.mdDoc '' + {file}`config.yaml` configuration as a Nix attribute set. + Configuration options should match those described in + [ + sample.config.yaml](https://github.com/matrix-slack/mx-puppet-slack/blob/master/sample.config.yaml). + ''; + }; + serviceDependencies = mkOption { + type = with types; listOf str; + default = optional config.services.matrix-synapse.enable "matrix-synapse.service"; + defaultText = literalExpression '' + optional config.services.matrix-synapse.enable "matrix-synapse.service" + ''; + description = lib.mdDoc '' + List of Systemd services to require and wait for when starting the application service. + ''; + }; + }; + }; + + config = mkIf cfg.enable { + systemd.services.mx-puppet-slack = { + description = "Matrix to Slack puppeting bridge"; + + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ] ++ cfg.serviceDependencies; + after = [ "network-online.target" ] ++ cfg.serviceDependencies; + + preStart = '' + # generate the appservice's registration file if absent + if [ ! -f '${registrationFile}' ]; then + ${cfg.package}/bin/mx-puppet-slack -r -c ${settingsFile} \ + -f ${registrationFile} + fi + ''; + + serviceConfig = { + Type = "simple"; + Restart = "always"; + + ProtectSystem = "strict"; + ProtectHome = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + + DynamicUser = true; + PrivateTmp = true; + WorkingDirectory = cfg.package; + StateDirectory = baseNameOf dataDir; + + UMask = "0027"; + + ExecStart = '' + ${cfg.package}/bin/mx-puppet-slack \ + -c ${settingsFile} \ + -f ${registrationFile} + ''; + }; + }; + }; + + meta.maintainers = with maintainers; [ govanify ]; +} diff --git a/modules/matrix/options.nix b/modules/matrix/options.nix new file mode 100644 index 0000000..61a9201 --- /dev/null +++ b/modules/matrix/options.nix @@ -0,0 +1,38 @@ +{ config, lib, pkgs, ... }: + +with lib; +{ + options = { + services.matrix = { + server_name = mkOption { + type = types.str; + example = "example.com"; + description = lib.mdDoc '' + The hostname that will appear in your user and room IDs + ''; + }; + + matrix_hostname = mkOption { + type = types.str; + default = "matrix.${config.services.matrix.server_name}"; + example = "matrix.example.com"; + description = lib.mdDoc '' + The hostname that Conduit actually runs on + + This can be the same as `server_name` if you want. This is only necessary + when Conduit is running on a different machine than the one hosting your + root domain. This configuration also assumes this is all running on a single + machine, some tweaks will need to be made if this is not the case. + ''; + }; + + admin_email = mkOption { + type = types.str; + example = "admin@example.com"; + description = lib.mdDoc '' + An admin email for TLS certificate notifications + ''; + }; + }; + }; +} diff --git a/modules/matrix/patches/heisenbridge_channel_name.patch b/modules/matrix/patches/heisenbridge_channel_name.patch new file mode 100644 index 0000000..130f96b --- /dev/null +++ b/modules/matrix/patches/heisenbridge_channel_name.patch @@ -0,0 +1,13 @@ +diff --git i/heisenbridge/channel_room.py w/heisenbridge/channel_room.py +index 119dad0..f1a17f6 100644 +--- i/heisenbridge/channel_room.py ++++ w/heisenbridge/channel_room.py +@@ -207,7 +207,7 @@ class ChannelRoom(PrivateRoom): + self.hidden_room_id = self.serv.hidden_room.id + + self.id = await self.network.serv.create_room( +- f"{visible_name} ({self.network.name})", ++ f"{visible_name}", + "", + [self.network.user_id], + self.hidden_room_id, diff --git a/modules/matrix/patches/heisenbridge_private_name.patch b/modules/matrix/patches/heisenbridge_private_name.patch new file mode 100644 index 0000000..6cff153 --- /dev/null +++ b/modules/matrix/patches/heisenbridge_private_name.patch @@ -0,0 +1,13 @@ +diff --git i/heisenbridge/private_room.py w/heisenbridge/private_room.py +index d8118e8..6d33a3e 100644 +--- i/heisenbridge/private_room.py ++++ w/heisenbridge/private_room.py +@@ -466,7 +466,7 @@ class PrivateRoom(Room): + if self.id is None: + irc_user_id = await self.network.serv.ensure_irc_user_id(self.network.name, displayname, update_cache=False) + self.id = await self.network.serv.create_room( +- "{} ({})".format(displayname, self.network.name), ++ "{}".format(displayname), + "Private chat with {} on {}".format(displayname, self.network.name), + [self.network.user_id, irc_user_id], + ) diff --git a/modules/matrix/patches/heisenbridge_user_presence.patch b/modules/matrix/patches/heisenbridge_user_presence.patch new file mode 100644 index 0000000..a5fc96d --- /dev/null +++ b/modules/matrix/patches/heisenbridge_user_presence.patch @@ -0,0 +1,103 @@ +diff --git i/heisenbridge/__main__.py w/heisenbridge/__main__.py +index d59febd..4898955 100644 +--- i/heisenbridge/__main__.py ++++ w/heisenbridge/__main__.py +@@ -28,6 +28,7 @@ from mautrix.errors import MUserInUse + from mautrix.types import EventType + from mautrix.types import JoinRule + from mautrix.types import Membership ++from mautrix.types import PresenceState + from mautrix.util.bridge_state import BridgeState + from mautrix.util.bridge_state import BridgeStateEvent + from mautrix.util.config import yaml +@@ -192,6 +193,19 @@ class BridgeAppService(AppService): + + return ret + ++ def set_user_state(self, user_id, away, status=None): ++ if user_id not in self._users: ++ return ++ ++ presence = PresenceState.ONLINE ++ if away: ++ presence = PresenceState.UNAVAILABLE ++ ++ async def later(): ++ await self.az.intent.user(user_id).set_presence(presence=presence, status=status) ++ ++ asyncio.ensure_future(later()) ++ + async def cache_user(self, user_id, displayname): + # start by caching that the user_id exists without a displayname + if user_id not in self._users: +diff --git i/heisenbridge/channel_room.py w/heisenbridge/channel_room.py +index 119dad0..3e0651d 100644 +--- i/heisenbridge/channel_room.py ++++ w/heisenbridge/channel_room.py +@@ -478,6 +478,9 @@ class ChannelRoom(PrivateRoom): + + asyncio.ensure_future(autocmd(self)) + ++ # Run a WHO on the channel to get initial away status ++ self.network.conn.who(target=event.target) ++ + return + + # ensure, append, invite and join +diff --git i/heisenbridge/network_room.py w/heisenbridge/network_room.py +index 3c20654..2758462 100644 +--- i/heisenbridge/network_room.py ++++ w/heisenbridge/network_room.py +@@ -139,7 +139,7 @@ class NetworkRoom(Room): + self.tls_cert = None + self.rejoin_invite = True + self.rejoin_kick = False +- self.caps = ["message-tags", "chghost", "znc.in/self-message"] ++ self.caps = ["message-tags", "chghost", "znc.in/self-message", "away-notify"] + self.forward = False + self.backoff = 0 + self.backoff_task = None +@@ -1378,6 +1378,7 @@ class NetworkRoom(Room): + self.conn.add_global_handler("338", self.on_whoisrealhost) # is actually using host + self.conn.add_global_handler("away", self.on_away) + self.conn.add_global_handler("endofwhois", self.on_endofwhois) ++ self.conn.add_global_handler("whoreply", self.on_whoreply) + + # tags + self.conn.add_global_handler("tagmsg", self.on_pass_or_ignore) +@@ -1936,9 +1937,34 @@ class NetworkRoom(Room): + data = self.whois_data[event.arguments[0].lower()] + data["realhost"] = event.arguments[1] + ++ def on_whoreply(self, conn, event) -> None: ++ data = self.whois_data[event.arguments[4].lower()] ++ data["nick"] = event.arguments[4] ++ data["user"] = event.arguments[1] ++ data["host"] = event.arguments[2] ++ if "G" in event.arguments[5]: ++ data["away"] = True ++ elif "H" in event.arguments[5]: ++ data["away"] = False ++ # data["realname"] = event.arguments[4] ++ ++ nick, mode = self.serv.strip_nick(data["nick"]) ++ irc_user_id = self.serv.irc_user_id(self.name, data["nick"]) ++ self.serv.set_user_state(irc_user_id, data["away"]) ++ + def on_away(self, conn, event) -> None: ++ nick, mode = self.serv.strip_nick(event.arguments[0]) ++ irc_user_id = self.serv.irc_user_id(self.name, event.arguments[0]) ++ + if event.arguments[0].lower() in self.whois_data: +- self.whois_data[event.arguments[0].lower()]["away"] = event.arguments[1] ++ if len(event.arguments) > 1: ++ self.whois_data[event.arguments[0].lower()]["away"] = True ++ self.whois_data[event.arguments[0].lower()]["awaymsg"] = event.arguments[1] ++ self.serv.set_user_state(irc_user_id, True, event.arguments[1]) ++ else: ++ self.whois_data[event.arguments[0].lower()]["away"] = False ++ self.whois_data[event.arguments[0].lower()]["awaymsg"] = "" ++ self.serv.set_user_state(irc_user_id, False) + else: + self.send_notice(f"{event.arguments[0]} is away: {event.arguments[1]}") + diff --git a/modules/matrix/pkgs/generate.sh b/modules/matrix/pkgs/generate.sh new file mode 100755 index 0000000..1192e12 --- /dev/null +++ b/modules/matrix/pkgs/generate.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env nix-shell +#! nix-shell -i bash -p nodePackages.node2nix + +tag="v0.1.2" +u="https://gitlab.com/mx-puppet/slack/mx-puppet-slack/-/raw/$tag" +# Download package.json and patch in @slackjs/opus optional dependency +curl $u/package.json | + sed 's|"typescript":.*|"typescript": "^4.8.3",|' >package.json + +node2nix \ + --nodejs-14 \ + --input package.json \ + --strip-optional-dependencies \ + --output node-packages.nix \ + --composition node-composition.nix \ + --registry https://registry.npmjs.org \ + --registry https://gitlab.com/api/v4/packages/npm \ + --registry-scope '@mx-puppet' + +rm -f package.json diff --git a/modules/matrix/pkgs/mautrix-slack.nix b/modules/matrix/pkgs/mautrix-slack.nix new file mode 100644 index 0000000..4310e7b --- /dev/null +++ b/modules/matrix/pkgs/mautrix-slack.nix @@ -0,0 +1,26 @@ +{ lib, buildGoModule, fetchFromGitHub, olm }: + +buildGoModule rec { + pname = "mautrix-slack"; + version = "20230316"; + + src = fetchFromGitHub { + owner = "mautrix"; + repo = "slack"; + rev = "main"; + sha256 = "sha256-kA2IzYkvWoh/LxykuSzOLif76ZDbj7hKRjdIGDHY1W0="; + }; + + buildInputs = [ olm ]; + + vendorSha256 = "sha256-kYaeVXxrfA8WuL10+2DC6c2cYJ2li4/3ulKxcy/KviQ="; + + doCheck = false; + + meta = with lib; { + homepage = "https://github.com/mautrix/slack"; + description = "Matrix <-> Slack hybrid puppeting/relaybot bridge"; + license = licenses.agpl3Plus; + maintainers = with maintainers; [ ]; + }; +} diff --git a/modules/matrix/pkgs/mx-puppet-slack.nix b/modules/matrix/pkgs/mx-puppet-slack.nix new file mode 100644 index 0000000..110cdca --- /dev/null +++ b/modules/matrix/pkgs/mx-puppet-slack.nix @@ -0,0 +1,49 @@ +{ stdenv, fetchFromGitLab, pkgs, lib, nodejs-14_x, pkg-config +, libjpeg, pixman, cairo, pango, which, postgresql }: + +let + nodejs = nodejs-14_x; + + version = "0.1.2"; + + src = fetchFromGitLab { + owner = "cocainefarm"; + repo = "mx-puppet-slack"; + rev = "e4b51ed"; + hash = "sha256-y2q3m5E6FuYSwn691SfFlwoFqkVolXl4esgiuVYHNOA="; + }; + + myNodePackages = import ./node-composition.nix { + inherit pkgs nodejs; + inherit (stdenv.hostPlatform) system; + }; + +in myNodePackages.package.override { + inherit version src; + + nativeBuildInputs = [ nodejs.pkgs.node-pre-gyp nodejs.pkgs.node-gyp-build pkg-config which ]; + buildInputs = [ libjpeg pixman cairo pango postgresql ]; + + postRebuild = '' + # Build typescript stuff + npm run build + ''; + + postInstall = '' + # Make an executable to run the server + mkdir -p $out/bin + cat < $out/bin/mx-puppet-slack + #!/bin/sh + exec ${nodejs}/bin/node $out/lib/node_modules/@mx-puppet/mx-puppet-slack/build/index.js "\$@" + EOF + chmod +x $out/bin/mx-puppet-slack + ''; + + meta = with lib; { + description = "A slack puppeting bridge for matrix"; + license = licenses.asl20; + homepage = "https://gitlab.com/mx-puppet/slack/mx-puppet-slack"; + maintainers = with maintainers; [ ]; + platforms = platforms.unix; + }; +} diff --git a/modules/matrix/pkgs/node-composition.nix b/modules/matrix/pkgs/node-composition.nix new file mode 100644 index 0000000..08f947e --- /dev/null +++ b/modules/matrix/pkgs/node-composition.nix @@ -0,0 +1,17 @@ +# This file has been generated by node2nix 1.11.1. Do not edit! + +{pkgs ? import { + inherit system; + }, system ? builtins.currentSystem, nodejs ? pkgs."nodejs-14_x"}: + +let + nodeEnv = import ./node-env.nix { + inherit (pkgs) stdenv lib python2 runCommand writeTextFile writeShellScript; + inherit pkgs nodejs; + libtool = if pkgs.stdenv.isDarwin then pkgs.darwin.cctools else null; + }; +in +import ./node-packages.nix { + inherit (pkgs) fetchurl nix-gitignore stdenv lib fetchgit; + inherit nodeEnv; +} diff --git a/modules/matrix/pkgs/node-env.nix b/modules/matrix/pkgs/node-env.nix new file mode 100644 index 0000000..bc1e366 --- /dev/null +++ b/modules/matrix/pkgs/node-env.nix @@ -0,0 +1,689 @@ +# This file originates from node2nix + +{lib, stdenv, nodejs, python2, pkgs, libtool, runCommand, writeTextFile, writeShellScript}: + +let + # Workaround to cope with utillinux in Nixpkgs 20.09 and util-linux in Nixpkgs master + utillinux = if pkgs ? utillinux then pkgs.utillinux else pkgs.util-linux; + + python = if nodejs ? python then nodejs.python else python2; + + # Create a tar wrapper that filters all the 'Ignoring unknown extended header keyword' noise + tarWrapper = runCommand "tarWrapper" {} '' + mkdir -p $out/bin + + cat > $out/bin/tar <> $out/nix-support/hydra-build-products + ''; + }; + + # Common shell logic + installPackage = writeShellScript "install-package" '' + installPackage() { + local packageName=$1 src=$2 + + local strippedName + + local DIR=$PWD + cd $TMPDIR + + unpackFile $src + + # Make the base dir in which the target dependency resides first + mkdir -p "$(dirname "$DIR/$packageName")" + + if [ -f "$src" ] + then + # Figure out what directory has been unpacked + packageDir="$(find . -maxdepth 1 -type d | tail -1)" + + # Restore write permissions to make building work + find "$packageDir" -type d -exec chmod u+x {} \; + chmod -R u+w "$packageDir" + + # Move the extracted tarball into the output folder + mv "$packageDir" "$DIR/$packageName" + elif [ -d "$src" ] + then + # Get a stripped name (without hash) of the source directory. + # On old nixpkgs it's already set internally. + if [ -z "$strippedName" ] + then + strippedName="$(stripHash $src)" + fi + + # Restore write permissions to make building work + chmod -R u+w "$strippedName" + + # Move the extracted directory into the output folder + mv "$strippedName" "$DIR/$packageName" + fi + + # Change to the package directory to install dependencies + cd "$DIR/$packageName" + } + ''; + + # Bundle the dependencies of the package + # + # Only include dependencies if they don't exist. They may also be bundled in the package. + includeDependencies = {dependencies}: + lib.optionalString (dependencies != []) ( + '' + mkdir -p node_modules + cd node_modules + '' + + (lib.concatMapStrings (dependency: + '' + if [ ! -e "${dependency.packageName}" ]; then + ${composePackage dependency} + fi + '' + ) dependencies) + + '' + cd .. + '' + ); + + # Recursively composes the dependencies of a package + composePackage = { name, packageName, src, dependencies ? [], ... }@args: + builtins.addErrorContext "while evaluating node package '${packageName}'" '' + installPackage "${packageName}" "${src}" + ${includeDependencies { inherit dependencies; }} + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + ''; + + pinpointDependencies = {dependencies, production}: + let + pinpointDependenciesFromPackageJSON = writeTextFile { + name = "pinpointDependencies.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + function resolveDependencyVersion(location, name) { + if(location == process.env['NIX_STORE']) { + return null; + } else { + var dependencyPackageJSON = path.join(location, "node_modules", name, "package.json"); + + if(fs.existsSync(dependencyPackageJSON)) { + var dependencyPackageObj = JSON.parse(fs.readFileSync(dependencyPackageJSON)); + + if(dependencyPackageObj.name == name) { + return dependencyPackageObj.version; + } + } else { + return resolveDependencyVersion(path.resolve(location, ".."), name); + } + } + } + + function replaceDependencies(dependencies) { + if(typeof dependencies == "object" && dependencies !== null) { + for(var dependency in dependencies) { + var resolvedVersion = resolveDependencyVersion(process.cwd(), dependency); + + if(resolvedVersion === null) { + process.stderr.write("WARNING: cannot pinpoint dependency: "+dependency+", context: "+process.cwd()+"\n"); + } else { + dependencies[dependency] = resolvedVersion; + } + } + } + } + + /* Read the package.json configuration */ + var packageObj = JSON.parse(fs.readFileSync('./package.json')); + + /* Pinpoint all dependencies */ + replaceDependencies(packageObj.dependencies); + if(process.argv[2] == "development") { + replaceDependencies(packageObj.devDependencies); + } + else { + packageObj.devDependencies = {}; + } + replaceDependencies(packageObj.optionalDependencies); + replaceDependencies(packageObj.peerDependencies); + + /* Write the fixed package.json file */ + fs.writeFileSync("package.json", JSON.stringify(packageObj, null, 2)); + ''; + }; + in + '' + node ${pinpointDependenciesFromPackageJSON} ${if production then "production" else "development"} + + ${lib.optionalString (dependencies != []) + '' + if [ -d node_modules ] + then + cd node_modules + ${lib.concatMapStrings (dependency: pinpointDependenciesOfPackage dependency) dependencies} + cd .. + fi + ''} + ''; + + # Recursively traverses all dependencies of a package and pinpoints all + # dependencies in the package.json file to the versions that are actually + # being used. + + pinpointDependenciesOfPackage = { packageName, dependencies ? [], production ? true, ... }@args: + '' + if [ -d "${packageName}" ] + then + cd "${packageName}" + ${pinpointDependencies { inherit dependencies production; }} + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + fi + ''; + + # Extract the Node.js source code which is used to compile packages with + # native bindings + nodeSources = runCommand "node-sources" {} '' + tar --no-same-owner --no-same-permissions -xf ${nodejs.src} + mv node-* $out + ''; + + # Script that adds _integrity fields to all package.json files to prevent NPM from consulting the cache (that is empty) + addIntegrityFieldsScript = writeTextFile { + name = "addintegrityfields.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + function augmentDependencies(baseDir, dependencies) { + for(var dependencyName in dependencies) { + var dependency = dependencies[dependencyName]; + + // Open package.json and augment metadata fields + var packageJSONDir = path.join(baseDir, "node_modules", dependencyName); + var packageJSONPath = path.join(packageJSONDir, "package.json"); + + if(fs.existsSync(packageJSONPath)) { // Only augment packages that exist. Sometimes we may have production installs in which development dependencies can be ignored + console.log("Adding metadata fields to: "+packageJSONPath); + var packageObj = JSON.parse(fs.readFileSync(packageJSONPath)); + + if(dependency.integrity) { + packageObj["_integrity"] = dependency.integrity; + } else { + packageObj["_integrity"] = "sha1-000000000000000000000000000="; // When no _integrity string has been provided (e.g. by Git dependencies), add a dummy one. It does not seem to harm and it bypasses downloads. + } + + if(dependency.resolved) { + packageObj["_resolved"] = dependency.resolved; // Adopt the resolved property if one has been provided + } else { + packageObj["_resolved"] = dependency.version; // Set the resolved version to the version identifier. This prevents NPM from cloning Git repositories. + } + + if(dependency.from !== undefined) { // Adopt from property if one has been provided + packageObj["_from"] = dependency.from; + } + + fs.writeFileSync(packageJSONPath, JSON.stringify(packageObj, null, 2)); + } + + // Augment transitive dependencies + if(dependency.dependencies !== undefined) { + augmentDependencies(packageJSONDir, dependency.dependencies); + } + } + } + + if(fs.existsSync("./package-lock.json")) { + var packageLock = JSON.parse(fs.readFileSync("./package-lock.json")); + + if(![1, 2].includes(packageLock.lockfileVersion)) { + process.stderr.write("Sorry, I only understand lock file versions 1 and 2!\n"); + process.exit(1); + } + + if(packageLock.dependencies !== undefined) { + augmentDependencies(".", packageLock.dependencies); + } + } + ''; + }; + + # Reconstructs a package-lock file from the node_modules/ folder structure and package.json files with dummy sha1 hashes + reconstructPackageLock = writeTextFile { + name = "reconstructpackagelock.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + var packageObj = JSON.parse(fs.readFileSync("package.json")); + + var lockObj = { + name: packageObj.name, + version: packageObj.version, + lockfileVersion: 2, + requires: true, + packages: { + "": { + name: packageObj.name, + version: packageObj.version, + license: packageObj.license, + bin: packageObj.bin, + dependencies: packageObj.dependencies, + engines: packageObj.engines, + optionalDependencies: packageObj.optionalDependencies + } + }, + dependencies: {} + }; + + function augmentPackageJSON(filePath, packages, dependencies) { + var packageJSON = path.join(filePath, "package.json"); + if(fs.existsSync(packageJSON)) { + var packageObj = JSON.parse(fs.readFileSync(packageJSON)); + packages[filePath] = { + version: packageObj.version, + integrity: "sha1-000000000000000000000000000=", + dependencies: packageObj.dependencies, + engines: packageObj.engines, + optionalDependencies: packageObj.optionalDependencies + }; + dependencies[packageObj.name] = { + version: packageObj.version, + integrity: "sha1-000000000000000000000000000=", + dependencies: {} + }; + processDependencies(path.join(filePath, "node_modules"), packages, dependencies[packageObj.name].dependencies); + } + } + + function processDependencies(dir, packages, dependencies) { + if(fs.existsSync(dir)) { + var files = fs.readdirSync(dir); + + files.forEach(function(entry) { + var filePath = path.join(dir, entry); + var stats = fs.statSync(filePath); + + if(stats.isDirectory()) { + if(entry.substr(0, 1) == "@") { + // When we encounter a namespace folder, augment all packages belonging to the scope + var pkgFiles = fs.readdirSync(filePath); + + pkgFiles.forEach(function(entry) { + if(stats.isDirectory()) { + var pkgFilePath = path.join(filePath, entry); + augmentPackageJSON(pkgFilePath, packages, dependencies); + } + }); + } else { + augmentPackageJSON(filePath, packages, dependencies); + } + } + }); + } + } + + processDependencies("node_modules", lockObj.packages, lockObj.dependencies); + + fs.writeFileSync("package-lock.json", JSON.stringify(lockObj, null, 2)); + ''; + }; + + # Script that links bins defined in package.json to the node_modules bin directory + # NPM does not do this for top-level packages itself anymore as of v7 + linkBinsScript = writeTextFile { + name = "linkbins.js"; + text = '' + var fs = require('fs'); + var path = require('path'); + + var packageObj = JSON.parse(fs.readFileSync("package.json")); + + var nodeModules = Array(packageObj.name.split("/").length).fill("..").join(path.sep); + + if(packageObj.bin !== undefined) { + fs.mkdirSync(path.join(nodeModules, ".bin")) + + if(typeof packageObj.bin == "object") { + Object.keys(packageObj.bin).forEach(function(exe) { + if(fs.existsSync(packageObj.bin[exe])) { + console.log("linking bin '" + exe + "'"); + fs.symlinkSync( + path.join("..", packageObj.name, packageObj.bin[exe]), + path.join(nodeModules, ".bin", exe) + ); + } + else { + console.log("skipping non-existent bin '" + exe + "'"); + } + }) + } + else { + if(fs.existsSync(packageObj.bin)) { + console.log("linking bin '" + packageObj.bin + "'"); + fs.symlinkSync( + path.join("..", packageObj.name, packageObj.bin), + path.join(nodeModules, ".bin", packageObj.name.split("/").pop()) + ); + } + else { + console.log("skipping non-existent bin '" + packageObj.bin + "'"); + } + } + } + else if(packageObj.directories !== undefined && packageObj.directories.bin !== undefined) { + fs.mkdirSync(path.join(nodeModules, ".bin")) + + fs.readdirSync(packageObj.directories.bin).forEach(function(exe) { + if(fs.existsSync(path.join(packageObj.directories.bin, exe))) { + console.log("linking bin '" + exe + "'"); + fs.symlinkSync( + path.join("..", packageObj.name, packageObj.directories.bin, exe), + path.join(nodeModules, ".bin", exe) + ); + } + else { + console.log("skipping non-existent bin '" + exe + "'"); + } + }) + } + ''; + }; + + prepareAndInvokeNPM = {packageName, bypassCache, reconstructLock, npmFlags, production}: + let + forceOfflineFlag = if bypassCache then "--offline" else "--registry http://www.example.com"; + in + '' + # Pinpoint the versions of all dependencies to the ones that are actually being used + echo "pinpointing versions of dependencies..." + source $pinpointDependenciesScriptPath + + # Patch the shebangs of the bundled modules to prevent them from + # calling executables outside the Nix store as much as possible + patchShebangs . + + # Deploy the Node.js package by running npm install. Since the + # dependencies have been provided already by ourselves, it should not + # attempt to install them again, which is good, because we want to make + # it Nix's responsibility. If it needs to install any dependencies + # anyway (e.g. because the dependency parameters are + # incomplete/incorrect), it fails. + # + # The other responsibilities of NPM are kept -- version checks, build + # steps, postprocessing etc. + + export HOME=$TMPDIR + cd "${packageName}" + runHook preRebuild + + ${lib.optionalString bypassCache '' + ${lib.optionalString reconstructLock '' + if [ -f package-lock.json ] + then + echo "WARNING: Reconstruct lock option enabled, but a lock file already exists!" + echo "This will most likely result in version mismatches! We will remove the lock file and regenerate it!" + rm package-lock.json + else + echo "No package-lock.json file found, reconstructing..." + fi + + node ${reconstructPackageLock} + ''} + + node ${addIntegrityFieldsScript} + ''} + + npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${lib.optionalString production "--production"} rebuild + + runHook postRebuild + + if [ "''${dontNpmInstall-}" != "1" ] + then + # NPM tries to download packages even when they already exist if npm-shrinkwrap is used. + rm -f npm-shrinkwrap.json + + npm ${forceOfflineFlag} --nodedir=${nodeSources} --no-bin-links --ignore-scripts ${npmFlags} ${lib.optionalString production "--production"} install + fi + + # Link executables defined in package.json + node ${linkBinsScript} + ''; + + # Builds and composes an NPM package including all its dependencies + buildNodePackage = + { name + , packageName + , version ? null + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , preRebuild ? "" + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , meta ? {} + , ... }@args: + + let + extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "preRebuild" "unpackPhase" "buildPhase" "meta" ]; + in + stdenv.mkDerivation ({ + name = "${name}${if version == null then "" else "-${version}"}"; + buildInputs = [ tarWrapper python nodejs ] + ++ lib.optional (stdenv.isLinux) utillinux + ++ lib.optional (stdenv.isDarwin) libtool + ++ buildInputs; + + inherit nodejs; + + inherit dontStrip; # Stripping may fail a build for some package deployments + inherit dontNpmInstall preRebuild unpackPhase buildPhase; + + compositionScript = composePackage args; + pinpointDependenciesScript = pinpointDependenciesOfPackage args; + + passAsFile = [ "compositionScript" "pinpointDependenciesScript" ]; + + installPhase = '' + source ${installPackage} + + # Create and enter a root node_modules/ folder + mkdir -p $out/lib/node_modules + cd $out/lib/node_modules + + # Compose the package and all its dependencies + source $compositionScriptPath + + ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }} + + # Create symlink to the deployed executable folder, if applicable + if [ -d "$out/lib/node_modules/.bin" ] + then + ln -s $out/lib/node_modules/.bin $out/bin + + # Fixup all executables + ls $out/bin/* | while read i + do + file="$(readlink -f "$i")" + chmod u+rwx "$file" + if isScript "$file" + then + sed -i 's/\r$//' "$file" # convert crlf to lf + fi + done + fi + + # Create symlinks to the deployed manual page folders, if applicable + if [ -d "$out/lib/node_modules/${packageName}/man" ] + then + mkdir -p $out/share + for dir in "$out/lib/node_modules/${packageName}/man/"* + do + mkdir -p $out/share/man/$(basename "$dir") + for page in "$dir"/* + do + ln -s $page $out/share/man/$(basename "$dir") + done + done + fi + + # Run post install hook, if provided + runHook postInstall + ''; + + meta = { + # default to Node.js' platforms + platforms = nodejs.meta.platforms; + } // meta; + } // extraArgs); + + # Builds a node environment (a node_modules folder and a set of binaries) + buildNodeDependencies = + { name + , packageName + , version ? null + , src + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , ... }@args: + + let + extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" ]; + in + stdenv.mkDerivation ({ + name = "node-dependencies-${name}${if version == null then "" else "-${version}"}"; + + buildInputs = [ tarWrapper python nodejs ] + ++ lib.optional (stdenv.isLinux) utillinux + ++ lib.optional (stdenv.isDarwin) libtool + ++ buildInputs; + + inherit dontStrip; # Stripping may fail a build for some package deployments + inherit dontNpmInstall unpackPhase buildPhase; + + includeScript = includeDependencies { inherit dependencies; }; + pinpointDependenciesScript = pinpointDependenciesOfPackage args; + + passAsFile = [ "includeScript" "pinpointDependenciesScript" ]; + + installPhase = '' + source ${installPackage} + + mkdir -p $out/${packageName} + cd $out/${packageName} + + source $includeScriptPath + + # Create fake package.json to make the npm commands work properly + cp ${src}/package.json . + chmod 644 package.json + ${lib.optionalString bypassCache '' + if [ -f ${src}/package-lock.json ] + then + cp ${src}/package-lock.json . + chmod 644 package-lock.json + fi + ''} + + # Go to the parent folder to make sure that all packages are pinpointed + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + + ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }} + + # Expose the executables that were installed + cd .. + ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} + + mv ${packageName} lib + ln -s $out/lib/node_modules/.bin $out/bin + ''; + } // extraArgs); + + # Builds a development shell + buildNodeShell = + { name + , packageName + , version ? null + , src + , dependencies ? [] + , buildInputs ? [] + , production ? true + , npmFlags ? "" + , dontNpmInstall ? false + , bypassCache ? false + , reconstructLock ? false + , dontStrip ? true + , unpackPhase ? "true" + , buildPhase ? "true" + , ... }@args: + + let + nodeDependencies = buildNodeDependencies args; + extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "unpackPhase" "buildPhase" ]; + in + stdenv.mkDerivation ({ + name = "node-shell-${name}${if version == null then "" else "-${version}"}"; + + buildInputs = [ python nodejs ] ++ lib.optional (stdenv.isLinux) utillinux ++ buildInputs; + buildCommand = '' + mkdir -p $out/bin + cat > $out/bin/shell < { + log.verbose("Received new reaction"); diff --git a/modules/nix-settings.nix b/modules/nix-settings.nix new file mode 100644 index 0000000..5219a67 --- /dev/null +++ b/modules/nix-settings.nix @@ -0,0 +1,38 @@ +{ config, lib, pkgs, ... }: + +{ + environment.etc = { + "nix/channels/nixpkgs".source = nixpkgs.outPath; + }; + + nix = { + extraOptions = '' + keep-outputs = true + keep-derivations = true + experimental-features = nix-command flakes + ''; + + registry = { + nixpkgs.flake = nixpkgs; + }; + + nixPath = [ + "nixpkgs=/etc/nix/channels/nixpkgs" + ]; + + settings = { + trusted-users = [ "@wheel" ]; + auto-optimise-store = true; + + substituters = [ + "https://cache.nixos.org/" + "https://nix-community.cachix.org" + ]; + + trusted-public-keys = [ + "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" + "nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=" + ]; + }; + }; +} diff --git a/modules/users/default.nix b/modules/users/default.nix new file mode 100644 index 0000000..13f1fc8 --- /dev/null +++ b/modules/users/default.nix @@ -0,0 +1,20 @@ +{ config, lib, pkgs, ... }: + +{ + users.users = { + audron = { + isNormalUser = true; + extraGroups = [ "wheel" "docker" ]; + openssh.authorizedKeys.keys = [ + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO2eIUtbt7RM75ThjKfUjm24QkzkzCSj7hs+GLaaxMeH cardno:15 505 339" + ]; + }; + d3fus = { + isNormalUser = true; + extraGroups = [ "wheel" "docker" ]; + openssh.authorizedKeys.keys = [ + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDa+AtVF5PuUOi30it7EuI79mfYvAWyqkoJQ/RS3LpXBGLqXt2VrpTmYnfonDhn2/nBlwnV5p/65l8g0lIZJ8TQOdMCxOMSsIPlC24q4xY2ov1ljboznmtmdxlPWRMoWqMKCp6kjCkVfEQ5pznnbOH+unvX5nLc4eG3QVfpKeaiz3JV6EZen1+jr/iLQP3KpdUylbnEO2ziHayUgZTdP6u5i6OvrcWS7lRA7yWIQyor92Rl6P/eby2jKVl9KMG0R5wCkUOAtgGRAT2XINmw0OZTj39hxxRToCXpilwjXkRUjPeD2SLmLOjhufJg1upbiGekqe5aOltg+3VoLtsIet6Im0RzjHuPHF4QAfBOv6ZfxREVbm5ODFkKP+2HdlIbYZhD5Rp16dgJTDGVPNiSRo7de2j/8RKG3gHAw1sPWhhTGONrL0t+7a0L3ijAn6NxjyyxA15JocVImPu/WtwcIfRsqxdtOYiaUXC8j+R6HK/q9PPDJyKGHYk6mU7V2KQ53ZR20Kl5YH9uLVHX0sSRXVWU0fZGDIGFpmy8uxccOS2zZYkSpQWmpWZdR0mg1zwOd6/rpTZ5mEJI/PYwi9Xuhfev3S3PD2StbFLzyFTVqzUdZ59nAmgh+jco8ylfzZTcMaTkYpznm9v59EnNmCBqTCde7MWTU4swhWal41EHMODJJQ== cardno:14 237 808" + ]; + }; + }; +} diff --git a/modules/vultr/default.nix b/modules/vultr/default.nix new file mode 100644 index 0000000..765c03d --- /dev/null +++ b/modules/vultr/default.nix @@ -0,0 +1,45 @@ +{ config, lib, pkgs, modulesPath, ... }: + +{ + imports = + [ (modulesPath + "/profiles/qemu-guest.nix") + ]; + + users.users."root".initialHashedPassword = "$6$R6JH.y368Bn6V$q710R4zQDK8vH7.L8JRAmFZwQW2H.3A00DPtKXFJb0nem87JlgYmD6UJbJ4vhP.f9UmvmqAgur8qMWEsBsErI/"; + users.users."root".hashedPassword = config.users.users."root".initialHashedPassword; + + boot.initrd.availableKernelModules = [ "ahci" "xhci_pci" "virtio_pci" "sr_mod" "virtio_blk" ]; + boot.initrd.kernelModules = [ ]; + boot.kernelModules = [ ]; + boot.extraModulePackages = [ ]; + + boot.loader.grub.devices = [ "/dev/vda" ]; + + fileSystems = { + "/" = { + device = "/dev/vda1"; + autoResize = true; + fsType = "ext4"; + }; + }; + + # kubernetes = { + # role = "agent"; + # taints = { + # role = "ns:NoSchedule"; + # }; + # }; + + networking = { + domain = "ns.vapor.systems"; + usePredictableInterfaceNames = false; + enableIPv6 = true; + tempAddresses = "disabled"; + interfaces.eth0.useDHCP = true; + nameservers = [ "1.1.1.1" "8.8.8.8" ]; + + dhcpcd.extraConfig = '' + nohook resolv.conf + ''; + }; +} diff --git a/modules/wireguard/default.nix b/modules/wireguard/default.nix new file mode 100644 index 0000000..c9fc063 --- /dev/null +++ b/modules/wireguard/default.nix @@ -0,0 +1,67 @@ +{ config, lib, pkgs, nodes, builtins, ... }: + +with lib; { + imports = [ ./options.nix ./roaming.nix ]; + + config = mkIf config.wireguard.enable (let + cfg = config.wireguard; + + peers = let + attrPeers = mapAttrs (n: node: + let peer = node.config.wireguard; + in { + endpoint = + "${node.config.deployment.targetHost}:${toString peer.port}"; + publicKey = peer.publicKey; + persistentKeepalive = 25; + allowedIPs = [ + "${peer.v4.address}/32" + "${peer.v6.ula}::${peer.v6.address}/128" + "${peer.v6.gua}::${peer.v6.address}/128" + ] ++ peer.allowedIPs; + }) (filterAttrs (n: node: node.config.wireguard.enable) nodes); + peers = attrValues attrPeers; + in peers; + in { + secrets = mkIf config.wireguard.enable { + wireguard = { + source = ../../secrets + + ("/" + "${config.networking.hostName}.privkey"); + dest = "/root/wireguard/privkey"; + }; + }; + + networking.wireguard.interfaces = mkIf config.wireguard.enable { + wg0 = with { ifname = "wg0"; }; { + ips = [ + "${cfg.v4.address}/${toString cfg.v4.prefixLength}" + "${cfg.v6.ula}::${cfg.v6.address}/128" + "${cfg.v6.gua}::${cfg.v6.address}/128" + ]; + listenPort = cfg.port; + postSetup = '' + ${pkgs.nftables}/bin/nft add table ${ifname} + ${pkgs.nftables}/bin/nft 'add chain ${ifname} prerouting { type nat hook prerouting priority 0 ; }' + ${pkgs.nftables}/bin/nft 'add chain ${ifname} postrouting { type nat hook postrouting priority 100 ; }' + ${pkgs.nftables}/bin/nft add rule ${ifname} postrouting ip saddr ${cfg.v4.network}/${ + toString cfg.v4.prefixLength + } oif ${cfg.natInterface} masquerade + + ${pkgs.iproute2}/bin/ip link set ${ifname} multicast on + ''; + postShutdown = '' + ${pkgs.nftables}/bin/nft flush table ${ifname} + ${pkgs.nftables}/bin/nft delete table ${ifname} + ''; + privateKeyFile = "/root/wireguard/privkey"; + peers = peers; + }; + }; + + boot.kernel.sysctl = { + "net.ipv4.ip_forward" = lib.mkDefault true; + "net.ipv6.conf.all.forwarding" = true; + "net.netfilter.nf_conntrack_tcp_be_liberal" = true; + }; + }); +} diff --git a/modules/wireguard/options.nix b/modules/wireguard/options.nix new file mode 100644 index 0000000..903716e --- /dev/null +++ b/modules/wireguard/options.nix @@ -0,0 +1,71 @@ +{ config, lib, pkgs, nodes, builtins, ... }: + +with lib; { + options = { + wireguard = { + enable = mkOption { + type = types.bool; + description = "Enable wireguard"; + }; + roaming = mkOption { + type = types.bool; + description = "Deploy roaming peers to this host"; + default = false; + }; + port = mkOption { + type = types.int; + description = "Port of the wireguard interface (51820)"; + default = 51820; + }; + publicKey = mkOption { + type = types.str; + description = "Public key of the wireguard interface"; + }; + natInterface = mkOption { + type = types.str; + description = "Interface to use for outgoing NAT connections"; + default = "eth0"; + }; + v4 = { + address = mkOption { + type = types.str; + description = "IP of the wireguard interface (10.10.0.1)"; + }; + network = mkOption { + type = types.str; + description = "The Network CIDR of the wireguard network (10.10.0.0)"; + }; + prefixLength = mkOption { + type = types.int; + description = "Prefix Length of the wireguard interface IP (24)"; + default = 24; + }; + }; + v6 = { + address = mkOption { + type = types.str; + description = "IP of the wireguard interface ()"; + }; + prefixLength = mkOption { + type = types.int; + description = "Prefix Length of the wireguard interface IP (24)"; + default = 64; + }; + ula = mkOption { + type = types.str; + description = "Unique Local Alloctation for IPv6 net"; + }; + gua = mkOption { + type = types.str; + description = + "Global Unique Allocation for IPv6 net, used as base for hosts"; + }; + }; + allowedIPs = mkOption { + type = types.listOf types.str; + description = "Extra allowedIPs"; + default = [ ]; + }; + }; + }; +} diff --git a/modules/wireguard/roaming.nix b/modules/wireguard/roaming.nix new file mode 100644 index 0000000..a89ce5d --- /dev/null +++ b/modules/wireguard/roaming.nix @@ -0,0 +1,64 @@ +{ config, pkgs, lib, ... }: + +{ + config = lib.mkIf config.wireguard.enable { + networking.wireguard.interfaces.wg0.peers = lib.mkIf config.wireguard.roaming [ + { # audron computer + publicKey = "okZQ5cMSu4+M3IKp1yIBuknmAKEzJLKe8tpVeY46phU="; + allowedIPs = [ + "10.10.0.10/32" + "2a0f:9400:8020:beef::10/128" + "fd15:3d8c:d429:beef::10/128" + ]; + } + { # audron homeassistant + publicKey = "afIZuhegBlyTmmzjikqtJ6lqYF2clfxtE4ZzQ9oijCg="; + allowedIPs = [ + "10.10.0.14/32" + "2a0f:9400:8020:beef::14/128" + "fd15:3d8c:d429:beef::14/128" + ]; + } + { # audron phone + publicKey = "LDzzGWlBmy9FQ/+bNAaLM2TmS8OR291uVTntwmb/gmM="; + allowedIPs = [ + "10.10.0.15/32" + "2a0f:9400:8020:beef::15/128" + "fd15:3d8c:d429:beef::15/128" + ]; + } + { # d3fus computer + publicKey = "CoMGgzL31yb0ozA17OuF0IDpkV2dnJ7j74itaQb0k1U="; + allowedIPs = [ + "10.10.0.20/32" + "2a0f:9400:8020:beef::20/128" + "fd15:3d8c:d429:beef::20/128" + ]; + } + { # d3fus streamer + publicKey = "byHXbaIVKARj3RBqyRuEUAsU5qeh/bmp/OLn6Y9qJV8="; + allowedIPs = [ + "10.10.0.21/32" + "2a0f:9400:8020:beef::21/128" + "fd15:3d8c:d429:beef::21/128" + ]; + } + { # d3fus phone + publicKey = "OEi+MTdy8oMWhkyC5NKHl6ztk92o4gYkgCTt5EMN5i4="; + allowedIPs = [ + "10.10.0.22/32" + "2a0f:9400:8020:beef::22/128" + "fd15:3d8c:d429:beef::22/128" + ]; + } + { # d3fus mac + publicKey = "dWWragU6AwsJeX6EhtybtT1VmjPdaSDKqmU/yxZQuxo="; + allowedIPs = [ + "10.10.0.23/32" + "2a0f:9400:8020:beef::23/128" + "fd15:3d8c:d429:beef::23/128" + ]; + } + ]; + }; +} diff --git a/modules/zfs/default.nix b/modules/zfs/default.nix new file mode 100644 index 0000000..4e863fc --- /dev/null +++ b/modules/zfs/default.nix @@ -0,0 +1,111 @@ +{ config, lib, pkgs, ... }: + +{ + boot = { + initrd.kernelModules = [ "zfs" ]; + kernelModules = [ "zfs" ]; + supportedFilesystems = [ "zfs" ]; + zfs.devNodes = "/dev/"; + loader.grub.zfsSupport = true; + }; + + + services.zfs = { + trim.enable = true; + autoScrub.enable = true; + autoScrub.pools = [ "rpool" ]; + }; + + virtualisation.containers.storage.settings.storage = { + driver = "zfs"; + graphroot = "/var/lib/containers/storage"; + runroot = "/run/containers/storage"; + options.zfs.fsname = "rpool/data/containers"; + options.zfs.mountopt = "nodev"; + }; + + virtualisation.cri-o = { + storageDriver = "zfs"; + extraPackages = [ pkgs.zfs ]; + }; + + fileSystems = { + "/" = { + device = "rpool/root"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/nix" = { + device = "rpool/root/nix"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/etc" = { + device = "rpool/root/etc"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/home" = { + device = "rpool/root/home"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/srv" = { + device = "rpool/root/srv"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/var" = { + device = "rpool/root/var"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/var/lib" = { + device = "rpool/root/var/lib"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/var/lib/rancher" = { + device = "rpool/root/var/lib/rancher"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/var/lib/docker" = { + device = "rpool/root/var/lib/docker"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/var/lib/containers" = { + device = "rpool/root/var/lib/containers"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/var/lib/etcd" = { + device = "rpool/root/var/lib/etcd"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/var/log" = { + device = "rpool/root/var/log"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + + "/var/spool" = { + device = "rpool/root/var/spool"; + fsType = "zfs"; + options = [ "zfsutil" ]; + }; + }; +} -- cgit v1.2.3