From ad4306149f72d6ff0b7e5bfd501cb063979a3706 Mon Sep 17 00:00:00 2001 From: krokosik Date: Sun, 29 Nov 2026 13:04:48 +0100 Subject: [PATCH 1/4] chore(nix): sync package and module with nixpkgs submission --- nix/module.nix | 10 +++------- nix/package.nix | 15 +++++++++------ nix/test.nix | 6 ++++-- 3 files changed, 16 insertions(+), 15 deletions(-) diff --git a/nix/module.nix b/nix/module.nix index 7e904fcd..97d5aa69 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -179,7 +179,8 @@ let in { meta = { - # nixpkgs: `maintainers = [ lib.maintainers.krokosik ];` once the maintainer entry exists. + # The maintainer entry is added in NixOS/nixpkgs#595003. In nixpkgs this is simply + # `maintainers = [ lib.maintainers.krokosik ];`. maintainers = lib.optional (lib.maintainers ? krokosik) lib.maintainers.krokosik; doc = ./split-pro.md; }; @@ -187,12 +188,7 @@ in options.services.split-pro = recursiveUpdate tableOptions { enable = lib.mkEnableOption "SplitPro, an open source alternative to Splitwise"; - package = mkOption { - type = types.package; - default = pkgs.split-pro; - defaultText = literalExpression "pkgs.split-pro"; - description = "The SplitPro package to use."; - }; + package = lib.mkPackageOption pkgs "split-pro" { }; openFirewall = mkOption { type = types.bool; diff --git a/nix/package.nix b/nix/package.nix index 30e95c27..e5c516c1 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -11,6 +11,7 @@ openssl, nixosTests ? { }, callPackage, + nix-update-script, }: let nodejs = nodejs_22; @@ -19,23 +20,22 @@ in stdenv.mkDerivation (finalAttrs: { pname = "split-pro"; # Keep this in sync with package.json; the flake's `version` check fails if they differ. - # In nixpkgs, nix-update bumps it. - # TODO(nixpkgs): fill in the real src and pnpm hashes for the first release that includes nix/. - # The flake replaces src, version and pnpmDeps with this checkout. + # The hashes below are for the release tagged `v${version}`. The flake replaces src, version + # and pnpmDeps with this checkout. In nixpkgs, nix-update bumps all three. version = "2.2.0"; src = fetchFromGitHub { owner = "oss-apps"; repo = "split-pro"; tag = "v${finalAttrs.version}"; - hash = lib.fakeHash; + hash = "sha256-ELsoEDzjUiov8+tMMLc9xF42xrAGkdCYbstcY2ZSMZ4="; }; pnpmDeps = fetchPnpmDeps { inherit (finalAttrs) pname version src; inherit pnpm; fetcherVersion = 5; - hash = lib.fakeHash; + hash = "sha256-QgIDb06iQvDNz/Znk9yH3W5tPwfu7X5w18Q60m+u4SM="; }; nativeBuildInputs = [ @@ -114,13 +114,16 @@ stdenv.mkDerivation (finalAttrs: { envCoverage = callPackage ./env-coverage.nix { split-pro = finalAttrs.finalPackage; }; } // lib.optionalAttrs (nixosTests ? split-pro) { nixos = nixosTests.split-pro; }; + updateScript = nix-update-script { }; }; meta = { - # nixpkgs: `maintainers = [ lib.maintainers.krokosik ];` once the maintainer entry exists. + # The maintainer entry is added in NixOS/nixpkgs#595003. In nixpkgs this is simply + # `maintainers = [ lib.maintainers.krokosik ];`, and the nixos test above is unconditional. maintainers = lib.optional (lib.maintainers ? krokosik) lib.maintainers.krokosik; description = "Open source alternative to Splitwise"; homepage = "https://github.com/oss-apps/split-pro"; + changelog = "https://github.com/oss-apps/split-pro/releases/tag/v${finalAttrs.version}"; license = lib.licenses.mit; mainProgram = "split-pro"; platforms = lib.platforms.linux; diff --git a/nix/test.nix b/nix/test.nix index c428003e..204aaaff 100644 --- a/nix/test.nix +++ b/nix/test.nix @@ -1,10 +1,12 @@ -# Imported by `runNixOSTest`. Expects `defaults` to import the module. -{ pkgs, ... }: +# Imported by `runNixOSTest`. Expects `defaults` to import the module. In nixpkgs the module +# is in the module list already, so the copy there drops that expectation. +{ lib, pkgs, ... }: let dbPassword = "hunter2-with/special@chars"; in { name = "split-pro"; + meta.maintainers = lib.optional (lib.maintainers ? krokosik) lib.maintainers.krokosik; nodes = { # Zero-config: local database, generated NEXTAUTH_SECRET, managed nginx in front. From c5f09204633eb0583b00d62b419bfb99de789c1b Mon Sep 17 00:00:00 2001 From: krokosik Date: Sun, 29 Nov 2026 13:07:25 +0100 Subject: [PATCH 2/4] fix(nix): drop module docs from the flake module --- flake.nix | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/flake.nix b/flake.nix index 9c86be56..bda4564a 100644 --- a/flake.nix +++ b/flake.nix @@ -36,6 +36,22 @@ date = self.lastModifiedDate or "19700101"; version = "${baseVersion}-unstable-${builtins.substring 0 4 date}-${builtins.substring 4 2 date}-${builtins.substring 6 2 date}"; pnpmDepsHash = "sha256-QgIDb06iQvDNz/Znk9yH3W5tPwfu7X5w18Q60m+u4SM="; + + # nixpkgs keeps meta.doc, because its redirects.json lists the doc's anchors. Out of tree, + # the doc would be built into the system manual, whose redirect check rejects the unknown + # anchors and fails the whole system build. + module = import ./nix/module.nix; + moduleWithoutDoc = lib.setFunctionArgs ( + args: + let + m = module args; + in + m + // { + _file = ./nix/module.nix; + meta = builtins.removeAttrs m.meta [ "doc" ]; + } + ) (lib.functionArgs module); in { packages = forAllSystems ( @@ -59,7 +75,7 @@ split-pro = { lib, pkgs, ... }: { - imports = [ ./nix/module.nix ]; + imports = [ moduleWithoutDoc ]; services.split-pro.package = lib.mkDefault self.packages.${pkgs.stdenv.hostPlatform.system}.split-pro; From 629e529cbc94fc69aab55557457508688ef526fe Mon Sep 17 00:00:00 2001 From: krokosik Date: Sun, 29 Nov 2026 13:13:12 +0100 Subject: [PATCH 3/4] feat(nix): build DATABASE_URL from database.host and passwordFile --- nix/module.nix | 102 +++++++++++++++++++++++++++++++++++++++++++---- nix/split-pro.md | 26 ++++++++++-- nix/test.nix | 20 +++++++--- 3 files changed, 131 insertions(+), 17 deletions(-) diff --git a/nix/module.nix b/nix/module.nix index 97d5aa69..25fae21c 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -110,6 +110,32 @@ let # file after the port, so the URL has to carry the port too. localDatabaseUrl = "postgresql://${db.user}@localhost:${toString pg.settings.port}/${db.name}?host=${lib.strings.escapeURL db.socketDir}"; + # True when the start script builds DATABASE_URL from database.host and friends. + buildDatabaseUrl = !db.createLocally && db.host != null; + + # Builds DATABASE_URL at start, so that the password never enters the Nix store or argv. The + # password comes from the DATABASE_PASSWORD credential. Like `$(< file)` for the other secrets, + # trailing newlines are dropped. A host starting with `/` is a socket directory. + databaseUrlScript = '' + const fs = require("fs"); + const e = process.env; + const enc = encodeURIComponent; + const file = e.CREDENTIALS_DIRECTORY && e.CREDENTIALS_DIRECTORY + "/DATABASE_PASSWORD"; + const password = file && fs.existsSync(file) ? fs.readFileSync(file, "utf8").replace(/\n+$/, "") : ""; + const auth = enc(e.SPLIT_PRO_DB_USER) + (password ? ":" + enc(password) : ""); + let host = e.SPLIT_PRO_DB_HOST; + let query = ""; + if (host.startsWith("/")) { + query = "?host=" + enc(host); + host = "localhost"; + } else if (host.includes(":")) { + host = "[" + host + "]"; + } + process.stdout.write( + "postgresql://" + auth + "@" + host + ":" + e.SPLIT_PRO_DB_PORT + "/" + enc(e.SPLIT_PRO_DB_NAME) + query, + ); + ''; + # Address that the managed nginx proxies to. If the app listens on a wildcard address, nginx # connects over loopback. IPv6 addresses need brackets in the URL. proxyHost = @@ -167,6 +193,21 @@ let fi ''} + ${optionalString buildDatabaseUrl '' + # environmentFiles and `environment` override the typed options, as for every other + # variable, so a DATABASE_URL from them wins. + if [ -z "''${DATABASE_URL:-}" ]; then + DATABASE_URL=$( + SPLIT_PRO_DB_HOST=${lib.escapeShellArg db.host} \ + SPLIT_PRO_DB_PORT=${toString db.port} \ + SPLIT_PRO_DB_USER=${lib.escapeShellArg db.user} \ + SPLIT_PRO_DB_NAME=${lib.escapeShellArg db.name} \ + ${node} -e ${lib.escapeShellArg databaseUrlScript} + ) + export DATABASE_URL + fi + ''} + # nginx, the firewall and the systemd sandbox rely on these values, so environment files # can't override them. ${lib.concatStringsSep "\n" ( @@ -261,8 +302,40 @@ in default = true; description = '' Create a local PostgreSQL database and role named `split-pro` and connect over the - Unix socket with peer authentication. To use another server, disable this and provide a - complete `DATABASE_URL` through {option}`${opt}.environmentFiles`. + Unix socket with peer authentication. To use another server, disable this and set + {option}`${opt}.database.host`, or provide a complete `DATABASE_URL` through + {option}`${opt}.environmentFiles`. + ''; + }; + host = mkOption { + type = types.nullOr types.str; + default = null; + example = "db.example.com"; + description = '' + Host name or IP address of an external PostgreSQL server, or the absolute path of the + directory that holds its Unix socket. When set, and + {option}`${opt}.database.createLocally` is disabled, SplitPro builds `DATABASE_URL` + from this option, {option}`${opt}.database.port`, {option}`${opt}.database.user`, + {option}`${opt}.database.name` and {option}`${opt}.database.passwordFile`. + + A `DATABASE_URL` from {option}`${opt}.environmentFiles` or + {option}`${opt}.environment` takes precedence. Use that instead for TLS or other + connection parameters. + ''; + }; + port = mkOption { + type = types.port; + default = 5432; + description = "Port of the server in {option}`${opt}.database.host`."; + }; + passwordFile = mkOption { + type = types.nullOr types.path; + default = null; + example = "/run/secrets/split-pro/db-password"; + description = '' + File containing the password of {option}`${opt}.database.user`. The file is passed to + the service as a systemd credential, so it can be owned by root. Trailing newlines are + ignored. Leave it unset for servers that don't need a password. ''; }; socketDir = mkOption { @@ -280,7 +353,8 @@ in default = "split-pro"; description = '' Database name. It must be `split-pro` when {option}`${opt}.database.createLocally` is - enabled. Otherwise only {option}`${opt}.database.configurePgCron` uses it. + enabled. Otherwise {option}`${opt}.database.host` and + {option}`${opt}.database.configurePgCron` use it. ''; }; user = mkOption { @@ -288,7 +362,8 @@ in default = "split-pro"; description = '' Database role. It must be `split-pro` when {option}`${opt}.database.createLocally` is - enabled. Otherwise only {option}`${opt}.database.configurePgCron` uses it. + enabled. Otherwise {option}`${opt}.database.host` and + {option}`${opt}.database.configurePgCron` use it. ''; }; configurePgCron = mkOption { @@ -363,8 +438,17 @@ in } { assertion = - !cfg.database.createLocally -> cfg.environmentFiles != [ ] || cfg.environment ? DATABASE_URL; - message = "${opt}: when database.createLocally is disabled, provide DATABASE_URL through ${opt}.environmentFiles."; + !db.createLocally + -> db.host != null || cfg.environmentFiles != [ ] || cfg.environment ? DATABASE_URL; + message = "${opt}: when database.createLocally is disabled, set ${opt}.database.host or provide DATABASE_URL through ${opt}.environmentFiles."; + } + { + assertion = db.createLocally -> db.host == null && db.passwordFile == null; + message = "${opt}.database.host and database.passwordFile are for external servers. Disable database.createLocally to use them."; + } + { + assertion = db.passwordFile != null -> db.host != null; + message = "${opt}.database.passwordFile is only used together with ${opt}.database.host."; } ] ++ map (row: { @@ -418,7 +502,11 @@ in WorkingDirectory = "/var/lib/split-pro"; ReadWritePaths = lib.optional (!uploadDirInState) uploadDir; EnvironmentFile = cfg.environmentFiles; - LoadCredential = mapAttrsToList (var: path: "${var}:${path}") secretFiles; + LoadCredential = + mapAttrsToList (var: path: "${var}:${path}") secretFiles + ++ optional ( + buildDatabaseUrl && db.passwordFile != null + ) "DATABASE_PASSWORD:${toString db.passwordFile}"; Restart = "on-failure"; RestartSec = 5; diff --git a/nix/split-pro.md b/nix/split-pro.md index 4227d7d6..5017430d 100644 --- a/nix/split-pro.md +++ b/nix/split-pro.md @@ -67,20 +67,38 @@ need (`database.configurePgCron`). ### External database {#module-services-split-pro-database-external} -To use any other server, put a complete connection URL in an environment file. TLS and other -connection parameters then all go in the same place: +To use any other server, disable `database.createLocally` and point the module at the server. +SplitPro then builds `DATABASE_URL` when it starts, so the password never ends up in the Nix +store: + +```nix +{ + services.split-pro.database = { + createLocally = false; + host = "db.example.com"; # or the directory of a Unix socket, such as "/run/postgresql" + port = 5432; + name = "splitpro"; + user = "splitpro"; + passwordFile = config.sops.secrets."split-pro/db-password".path; + }; +} +``` + +For TLS or other connection parameters, put a complete connection URL in an environment file +instead. A `DATABASE_URL` from `environmentFiles` takes precedence over `database.host`: ```nix { services.split-pro = { database.createLocally = false; - # Contains DATABASE_URL=postgresql://splitpro:@db.example.com:5432/splitpro + # Contains DATABASE_URL=postgresql://splitpro:@db.example.com:5432/splitpro?sslmode=require environmentFiles = [ config.sops.templates."split-pro.env".path ]; }; } ``` -Percent-encode special characters in the user name and password (`@` is `%40`, `/` is `%2F`). +In that URL, percent-encode special characters in the user name and password (`@` is `%40`, +`/` is `%2F`). The module does that for you with `database.host`. The server must load pg_cron, point `cron.database_name` at the SplitPro database and run jobs in background workers. These are the settings the module applies to a local server: diff --git a/nix/test.nix b/nix/test.nix index 204aaaff..dfbe7db2 100644 --- a/nix/test.nix +++ b/nix/test.nix @@ -78,9 +78,10 @@ in app = { virtualisation.memorySize = 2048; - # As on osiris, the complete DATABASE_URL comes from a root-owned env file (a sops template). - environment.etc."split-pro/env" = { - text = "DATABASE_URL=postgresql://splitpro:${pkgs.lib.escapeURL dbPassword}@db:5432/splitpro\n"; + # A root-owned password file, as from sops-nix. The trailing newline must be ignored, and + # the special characters must be percent-encoded in the generated DATABASE_URL. + environment.etc."split-pro/db-password" = { + text = "${dbPassword}\n"; mode = "0400"; }; environment.etc."split-pro/nextauth-secret" = { @@ -108,8 +109,13 @@ in issuer = "https://auth.example.com/application/o/split-pro/"; }; }; - database.createLocally = false; - environmentFiles = [ "/etc/split-pro/env" ]; + database = { + createLocally = false; + host = "db"; + name = "splitpro"; + user = "splitpro"; + passwordFile = "/etc/split-pro/db-password"; + }; }; }; }; @@ -185,10 +191,12 @@ in code = local.succeed(via_nginx("/api/v1/upload", "-o /dev/null -w '%{http_code}' -F file=@/tmp/big.bin")).strip() assert code == "413", f"upload over the nginx limit got {code}" - with subtest("external database via environmentFiles DATABASE_URL, *File secrets"): + with subtest("external database via database.host and passwordFile, *File secrets"): db.wait_for_unit("postgresql.target") wait_ready(app) app.succeed("test ! -e /var/lib/split-pro/nextauth-secret") + # The password stays out of the unit definition. + app.fail("systemctl cat split-pro.service | grep -F hunter2") app.succeed("curl -sf http://127.0.0.1:3000/api/auth/providers | grep -q authentik") db.succeed("sudo -u postgres psql -d splitpro -tAc 'SELECT count(*) FROM _prisma_migrations' | grep -qv '^0$'") assert_cron_runs(db, "PGPASSWORD='${dbPassword}' psql -h 127.0.0.1 -U splitpro -d splitpro") From 12abbbf6626a87091ec010dea15d076d326b15a6 Mon Sep 17 00:00:00 2001 From: krokosik Date: Sun, 29 Nov 2026 13:23:31 +0100 Subject: [PATCH 4/4] fix(nix): let the app role read cron.timezone pg_cron allows only superusers and members of pg_read_all_settings to read cron.timezone. The date-only recurrence migration, the recurrence function and the expense router read it, so upgrading a database that already has recurring expenses failed with 'permission denied to examine "cron.timezone"' for a non-superuser role. Grant pg_read_all_settings in split-pro-db-setup, list the grant in the external database docs (NixOS, Docker, configuration), and check in the VM test that the app role can read the setting. Also set strictDeps and __structuredAttrs on the package, which nixpkgs-vet requires for new packages. --- docker/README.md | 1 + docs/CONFIGURATION.md | 1 + nix/module.nix | 4 ++++ nix/package.nix | 3 +++ nix/split-pro.md | 7 +++++-- nix/test.nix | 5 +++++ 6 files changed, 19 insertions(+), 2 deletions(-) diff --git a/docker/README.md b/docker/README.md index 78b6a835..f6bcf657 100644 --- a/docker/README.md +++ b/docker/README.md @@ -193,6 +193,7 @@ CREATE EXTENSION IF NOT EXISTS pg_cron; GRANT USAGE ON SCHEMA cron TO ; GRANT SELECT, UPDATE, REFERENCES ON cron.job TO ; GRANT SELECT ON cron.job_run_details TO ; +GRANT pg_read_all_settings TO ; -- read cron.timezone, which pg_cron limits to superusers ``` **Required PostgreSQL configuration** (`postgresql.conf`): diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 7c9d51aa..662853c9 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -36,6 +36,7 @@ If SplitPro connects to an external/managed PostgreSQL instance, make sure your GRANT USAGE ON SCHEMA cron TO ; GRANT SELECT, UPDATE, REFERENCES ON cron.job TO ; GRANT SELECT ON cron.job_run_details TO ; + GRANT pg_read_all_settings TO ; -- read cron.timezone, which pg_cron limits to superusers ``` 3. Verify setup: diff --git a/nix/module.nix b/nix/module.nix index 25fae21c..1daae9b3 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -626,9 +626,13 @@ in -- * UPDATE on cron.job.schedule, because a migration rewrites that column. -- * REFERENCES on cron.job(jobid), because "ExpenseRecurrence"."jobId" has a foreign -- key to it. + -- * Membership in pg_read_all_settings, because pg_cron lets only superusers read + -- cron.timezone. A migration, the recurrence function and the expense router read + -- it to work out calendar dates. GRANT USAGE ON SCHEMA cron TO :"role"; GRANT EXECUTE ON FUNCTION cron.alter_job(bigint, text, text, text, text, boolean) TO :"role"; GRANT UPDATE (schedule), REFERENCES (jobid) ON cron.job TO :"role"; + GRANT pg_read_all_settings TO :"role"; EOF ''; }; diff --git a/nix/package.nix b/nix/package.nix index e5c516c1..f2022306 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -46,6 +46,9 @@ stdenv.mkDerivation (finalAttrs: { openssl ]; + strictDeps = true; + __structuredAttrs = true; + env = { # Validating the environment at build time would need runtime secrets. The service validates # it at startup instead. diff --git a/nix/split-pro.md b/nix/split-pro.md index 5017430d..23d92680 100644 --- a/nix/split-pro.md +++ b/nix/split-pro.md @@ -126,12 +126,15 @@ CREATE EXTENSION IF NOT EXISTS pg_cron; GRANT USAGE ON SCHEMA cron TO splitpro; GRANT EXECUTE ON FUNCTION cron.alter_job(bigint, text, text, text, text, boolean) TO splitpro; GRANT UPDATE (schedule), REFERENCES (jobid) ON cron.job TO splitpro; +GRANT pg_read_all_settings TO splitpro; ``` pg_cron already lets every role read `cron.job` and `cron.job_run_details`. The app also changes schedules with `cron.alter_job`. pg_cron revokes that function from public, but the function -still only changes jobs that belong to the caller. Finally, the app's migrations rewrite -`cron.job.schedule` and add a foreign key to `cron.job(jobid)`. +still only changes jobs that belong to the caller. The app's migrations rewrite +`cron.job.schedule` and add a foreign key to `cron.job(jobid)`. Finally, the app reads +`cron.timezone` to work out calendar dates, and pg_cron lets only superusers and members of +`pg_read_all_settings` read it. If that server is this machine's `services.postgresql`, but this module doesn't create the database, set `database.configurePgCron = true` and the module does this setup for you. Also set diff --git a/nix/test.nix b/nix/test.nix index dfbe7db2..af922392 100644 --- a/nix/test.nix +++ b/nix/test.nix @@ -72,6 +72,7 @@ in GRANT USAGE ON SCHEMA cron TO splitpro; GRANT EXECUTE ON FUNCTION cron.alter_job(bigint, text, text, text, text, boolean) TO splitpro; GRANT UPDATE (schedule), REFERENCES (jobid) ON cron.job TO splitpro; + GRANT pg_read_all_settings TO splitpro; EOF ''; }; @@ -136,6 +137,10 @@ in machine.wait_until_succeeds("curl -sf http://127.0.0.1:3000/api/readyz", timeout=180) def assert_cron_runs(machine, psql): + # pg_cron lets only superusers and members of pg_read_all_settings read cron.timezone. + # The app reads it in a migration, the recurrence function and the expense router. On a + # fresh database the migration has no rows to evaluate, so check the permission directly. + machine.succeed(psql + " -tAc \"SELECT current_setting('cron.timezone')\"") # Schedule a harmless job as the application role and wait until pg_cron has run it. machine.succeed(psql + " -c \"SELECT cron.schedule('vm-test', '1 seconds', 'SELECT 1')\"") machine.wait_until_succeeds(