Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ CREATE EXTENSION IF NOT EXISTS pg_cron;
GRANT USAGE ON SCHEMA cron TO <app_user>;
GRANT SELECT, UPDATE, REFERENCES ON cron.job TO <app_user>;
GRANT SELECT ON cron.job_run_details TO <app_user>;
GRANT pg_read_all_settings TO <app_user>; -- read cron.timezone, which pg_cron limits to superusers
```

**Required PostgreSQL configuration** (`postgresql.conf`):
Expand Down
1 change: 1 addition & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ If SplitPro connects to an external/managed PostgreSQL instance, make sure your
GRANT USAGE ON SCHEMA cron TO <app_user>;
GRANT SELECT, UPDATE, REFERENCES ON cron.job TO <app_user>;
GRANT SELECT ON cron.job_run_details TO <app_user>;
GRANT pg_read_all_settings TO <app_user>; -- read cron.timezone, which pg_cron limits to superusers
```

3. Verify setup:
Expand Down
18 changes: 17 additions & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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;
Expand Down
116 changes: 102 additions & 14 deletions nix/module.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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" (
Expand All @@ -179,20 +220,16 @@ 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;
};

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;
Expand Down Expand Up @@ -265,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 {
Expand All @@ -284,15 +353,17 @@ 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 {
type = types.str;
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 {
Expand Down Expand Up @@ -367,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: {
Expand Down Expand Up @@ -422,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;

Expand Down Expand Up @@ -542,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
'';
};
Expand Down
18 changes: 12 additions & 6 deletions nix/package.nix
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
openssl,
nixosTests ? { },
callPackage,
nix-update-script,
}:
let
nodejs = nodejs_22;
Expand All @@ -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 = [
Expand All @@ -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.
Expand Down Expand Up @@ -114,13 +117,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 { };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
};

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;
Expand Down
33 changes: 27 additions & 6 deletions nix/split-pro.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<url-encoded password>@db.example.com:5432/splitpro
# Contains DATABASE_URL=postgresql://splitpro:<url-encoded password>@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:
Expand Down Expand Up @@ -108,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
Expand Down
Loading