feat(postgresql): consolidate database and role-password boilerplate on Vega (#274) #287
No reviewers
Labels
No labels
area:authentication
area:flake-utilities
area:performance
area:tbd
host:chaos
host:cosmos
host:electra
host:fleet
host:lena
host:lyra
host:mass-storage
host:media1
host:nimmog-de
host:nova
host:pangolin
host:pangolin-vps
host:phone
host:router
host:vega
investigation
phase:cutover
phase:deploy
phase:mcp
phase:module
phase:packaging
phase:prep
phase:validation
priority:high
priority:medium
project:attic-postgres-lyra-rollout
project:auto-update-reliability
project:auto-update-remediation
project:declarative-purity-cleanup
project:external-review
project:fleet-boundary-cleanup
project:host-facts-refactor
project:lyra-nixos-deploy
project:lyra-service-stack-migration
project:nebula-mesh-network
project:nix-idioms-hygiene
project:nixos-build-deployment-pipeline
project:security-hardening
project:service-stack-migration
project:vega-sillytavern-cutover
project:wiki-rebuild
repo:numtide/flake-utils
repo:numtide/nix-auth
repo:numtide/nixos-passthru-cache
repo:numtide/nix-relay
service:auto-update
service:gitlab
service:hermes
service:mem0
service:nix
service:sillytavern
service:slskd
service:synthseek
service:tdarr
No milestone
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
nimmo/nixos-config!287
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/issue-274-consolidate-postgresql-boilerplate"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Context
Ref #274 (Milestone: Nix Idioms and Architecture Hygiene)
In
hosts/vega/databases/andmodules/databases/immich.nix, several services repeated ~50-line oneshot systemd services executingALTER ROLE <name> WITH LOGIN PASSWORD '$password'and database ownership queries. Additionally, standalone single-database definitions (atticd.nix,forgejo.nix,metamcp.nix,openwebui.nix,postgres.nix) existed as tiny 3-line files doing nothing other than appending toservices.postgresql.ensureDatabases.Changes
modules/databases/postgresql-role-password.nix):services.postgresql.rolePasswords.<name>submodule option.owner = "postgres:postgres", mode0400, withrestartUnits = [ "postgresql-set-<name>-password.service" ]).services.postgresql.ensureDatabasesandservices.postgresql.ensureUsers.postgresql-set-<name>-password(ordered after and requiringpostgresql-setup.service) that runsALTER ROLE ... WITH LOGIN PASSWORD ...;andALTER DATABASE ... OWNER TO ...;viapsql <<SQLstdin.services.serviceFailureMonitor.services.modules/databases/immich.nixto userolePasswords.immich.hosts/vega/databases/(freshrss.nix,paperless.nix,radarr.nix,sonarr.nix,whisparr-v3.nix) to use declarativerolePasswords.atticd,forgejo,metamcp_db,openwebui,postgres) intohosts/vega/databases/postgresql.nix.atticd.nix,forgejo.nix,metamcp.nix,openwebui.nix,postgres.nix).pages/projects/nixos-config/postgresql-role-passwords.md.Validation
nix flake checkpassed cleanly (all checks passed! flake check OK, includingformattingandservice-failure-monitor-coverage).ensureDatabasescontains all 14 expected databases:freshrss,immich,paperless,radarr-log,radarr-main,sonarr-log,sonarr-main,whisparr-v3-log,whisparr-v3-main,atticd,forgejo,metamcp_db,openwebui,postgres(identical set to pre-refactor baseline).ensureUserscontains all 6 expected roles (freshrss,immich,paperless,radarr,sonarr,whisparr-v3), all withlogin = true.psql <<SQLheredoc execution and robust quoting.serviceFailureMonitorincludes all 6 role-password units.electra,vega,lena, andlyraall evaluate and dry-run cleanly.Automated code review
Reviewed commit:
4119ba3c28a0d046dba4b44289270016439f6d5bVerdict: Ready to merge
No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory.
Overall assessment
Reviewed the PostgreSQL role-password consolidation (new
modules/databases/postgresql-role-password.nix, six migrated consumers, and the mergedhosts/vega/databases/postgresql.nix) against the checked-out tree. Cross-checks passed: the five deleted stubs (atticd,forgejo,metamcp,openwebui,postgres) are no imported anywhere (hosts/vega/databases/postgresql.nixre-lists all five names inensureDatabases), no file still references the removedsops.secretsattribute names (*-db-password-postgres,radarr-db-password,immich-db-password-postgres, ...) — the app-level secrets inmodules/services/{freshrss,paperless,bookstack,immich}.nixuse distinct names and are untouched — and the generated unit names (postgresql-set-<name>-password) match the names added toservices.serviceFailureMonitor.servicesby the same module. One latent defect in the new module's generated shell script is reported; the remaining observations are questions about evaluation-time merging and unit ordering that cannot be settled from the supplied material.Blocking findings
None.
Important findings
None.
Suggestions
databasesis empty orensureDBOwnership = false(modules/databases/postgresql-role-password.nix:164; high confidence)The generated
scriptends with--variable=ON_ERROR_STOP=1 <<SQL(line 162) and the terminator is appended to an interpolated value:${alterDatabasesCmd}SQL(line 164), inside an indented string whose closing''is indented two columns less than the body, so the emitted script keeps two leading spaces on that line.alterDatabasesCmd(line 136) is""whenroleCfg.databases == [ ]— the documented default for thedatabasesoption — or whenensureDBOwnership = false, so the terminator line becomesSQL, which is not a valid terminator for an unquoted<<SQLheredoc; bash then reads to EOF and fails with a syntax error. The six current call sites all pass a non-emptydatabaseslist, whose trailing\nputsSQLat column 1, so this does not affect the evaluated Vega config today.Impact: Any future or default use of the module (
databases = [ ], orensureDBOwnership = falseon a role that does have databases) produces apostgresql-set-<name>-passwordoneshot that fails at start; because the module also adds that unit toservices.serviceFailureMonitor.services, the failure would surface as a spurious runtime service failure instead of an evaluation-time configuration error.Suggested fix: Emit the terminator on its own unindented source line (build the SQL body as a separate string and interpolate it before a dedicated
SQLline), or makealterDatabasesCmdalways end with a newline and use${alterDatabasesCmd}\nSQL, or rejectdatabases == [ ]at evaluation time when the unit is generated.Tests and validation
Questions
hosts/vega/default.niximports../../modules/databases/immich.nix(which now declaresimports = [ ./postgresql-role-password.nix ]) and./databases/postgresql.nix(which imports the same file directly), so the module is reachable twice on Vega. Please confirm the evaluated config does not duplicate theservices.postgresql.rolePasswordsoption definition or double the entries contributed toservices.postgresql.ensureDatabasesandservices.postgresql.ensureUsers(list-typed options merge by concatenation); the PR's reportedensureDatabasesbeing a set would not reveal duplicated list entries.freshrss,paperlessandimmichmoved from the removedservices.postgresql.ensureUsers[].ensureDBOwnership = truetoALTER DATABASE ... OWNER TO ...inside the generated oneshot, which is ordered only afterpostgresql-setup.service. Is it intended that the application services are not ordered afterpostgresql-set-<name>-password.service, so a consumer can start while the database owner is stillpostgres?freshrss-db-password-postgres->postgresql-role-password-freshrss). I found no reference to the old names in this tree; please confirm no live container bind mount, backup include, or runbook outside the repository names the old paths.Review limitations
nix flake check, the repository's formatting/service-failure-monitor-coverage checks, and the evaluatedensureDatabases/ensureUsers/systemd.servicesvalues could not be re-derived; the PR's validation statements were treated as untrusted evidence.psql <<SQLscript (heredoc termination, indentation stripping of the Nix indented string, quoting of$password_sql) was inferred from the source text rather than executed.pages/projects/nixos-config/postgresql-role-passwords.md, the referenced issue #274, or the CI logs.Diff coverage
hosts/vega/databases/atticd.nix: reviewed — included in a context-limited batchhosts/vega/databases/forgejo.nix: reviewed — included in a context-limited batchhosts/vega/databases/freshrss.nix: reviewed — included in a context-limited batchhosts/vega/databases/metamcp.nix: reviewed — included in a context-limited batchhosts/vega/databases/openwebui.nix: reviewed — included in a context-limited batchhosts/vega/databases/paperless.nix: reviewed — included in a context-limited batchhosts/vega/databases/postgres.nix: reviewed — included in a context-limited batchhosts/vega/databases/postgresql.nix: reviewed — included in a context-limited batchhosts/vega/databases/radarr.nix: reviewed — included in a context-limited batchhosts/vega/databases/sonarr.nix: reviewed — included in a context-limited batchhosts/vega/databases/whisparr-v3.nix: reviewed — included in a context-limited batchmodules/databases/immich.nix: reviewed — included in a context-limited batchmodules/databases/postgresql-role-password.nix: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
77296f8eba348a3f34f049988a90df41a72bcb6bVerdict: Ready to merge
No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory.
Overall assessment
The PR replaces per-service PostgreSQL role/password boilerplate with a
services.postgresql.rolePasswordssubmodule (modules/databases/postgresql-role-password.nix), migrates the six Vega role definitions (freshrss, paperless, radarr, sonarr, whisparr-v3) and modules/databases/immich.nix to it, and inlines the five role-lessensureDatabasesentries (atticd, forgejo, metamcp_db, openwebui, postgres) into hosts/vega/databases/postgresql.nix. I verified in the checked-out tree that the deleted per-database files are no longer referenced from any host (only./databases/postgresql.nixis imported, hosts/vega/default.nix:58), that no consumer still refers to the old secret attribute names (freshrss-db-password-postgres,radarr-db-password,immich-db-password-postgres, etc. return no matches; the unrelatedfreshrss-db-password/paperless-db-password/immich-db-passwordnames in modules/services/* are distinct attributes that already existed before the change), that the new module import paths resolve (hosts/vega/databases/postgresql.nix:9../../../modules/databases/postgresql-role-password.nix, modules/databases/immich.nix./postgresql-role-password.nix), and that the generated database lists do not overlap the explicit list in postgresql.nix. No test fixture in tests/ references PostgreSQL, so no repository rule requires added coverage. One concrete, evidence-backed defect remains: the submodule'sensureDBOwnershipoption is consumed only by the oneshot SQL generator and is never propagated into the generatedservices.postgresql.ensureUsersentries, so the evaluated NixOS output no longer matches the pre-refactorensureUsersshape for freshrss, paperless, and immich.Blocking findings
None.
Important findings
None.
Suggestions
ensureDBOwnershipis not propagated to the NixOSensureUsersfield it is named after (modules/databases/postgresql-role-password.nix:124; high confidence)The submodule declares
ensureDBOwnership(line 68, defaulttrue, described as "Whether to grant ownership of specified databases to this role") and uses it only as a guard for the generatedALTER DATABASE "<db>" OWNER TO "<role>";SQL in the oneshot (line 142). Theservices.postgresql.ensureUsersgeneration (lines 117-125) emits onlyname = roleCfg.role;andensureClauses.login = roleCfg.login;— it never sets the NixOSensureDBOwnershipfield. The diff shows the pre-refactor definitions did set it:hosts/vega/databases/freshrss.nixandhosts/vega/databases/paperless.nixeach hadensureUsers = [ { name = <x>; ensureDBOwnership = true; } ];, andmodules/databases/immich.nixhad{ name = "immich"; ensureDBOwnership = true; ensureClauses.login = true; }. Conversely, the generated entries now addensureClauses.login = truefor freshrss and paperless, which those files did not previously declare.Impact: The evaluated
services.postgresql.ensureUsersoutput differs from the pre-refactor baseline for every migrated role:ensureDBOwnershipis dropped andensureClauses.login = trueis added for freshrss and paperless. The end state is equivalent on a healthy boot because the oneshot (orderedafter/requirespostgresql-setup.service) now issues theALTER DATABASE ... OWNER TO ...that NixOS previously issued duringpostgresql-setup.service, so this is not a demonstrated runtime regression. The concrete problem is the option contract:ensureDBOwnershipshadows the NixOS field name but cannot control it, so the generated configuration is not the documented NixOS mechanism and a reader comparing this module against upstreamservices.postgresql.ensureUserswill be misled.Suggested fix: Either emit
ensureDBOwnership = roleCfg.ensureDBOwnership;in the generatedensureUsersentry at line 124 so the option drives the NixOS field it is named after (and keep the oneshotALTER DATABASEonly when needed), or rename the submodule option (e.g.alterDatabaseOwnership) and state in its description that ownership is set by the generated oneshot rather than bypostgresql-setup.service. Also make thelogindefault explicit for freshrss/paperless if the addedensureClauses.login = truewas not intended.Tests and validation
Questions
ensureDBOwnership = truefrom the generatedensureUsersentries for freshrss, paperless, and immich deliberate (ownership delegated entirely to the oneshot), or should the submodule option also drive the NixOS field?ensureClauses.login = truefor freshrss and paperless intended? Their pre-refactorensureUsersentries declared onlyensureDBOwnership, and the diff shows noensureClausesfor either.Review limitations
nix flake check,just test, or evaluate the configuration, so I cannot independently confirm the PR's claim that the evaluatedensureDatabases/ensureUsers/failure-monitor sets match the pre-refactor baseline; theensureUserscomparison above is read directly from the supplied diff and module source.services.postgresqlmodule source, so the exact runtime semantics ofensureUsers.ensureDBOwnershipandensureClauses.login, and whetherservices.postgresqlaccepts a newrolePasswordssub-attribute in this pinned nixpkgs, are taken from the field names visible in the diff and from the PR's reported passingnix flake checkrather than from supplied upstream source.postgresql-role-password-<name>) or that.sops.yamlrecipients cover them; thesopsFile/keyvalues are unchanged by the diff and I did not decrypt or inspect secret values.psql ... <<SQLscript are not verified by me, and I report no defect in them.Diff coverage
hosts/vega/databases/atticd.nix: reviewed — included in a context-limited batchhosts/vega/databases/forgejo.nix: reviewed — included in a context-limited batchhosts/vega/databases/freshrss.nix: reviewed — included in a context-limited batchhosts/vega/databases/metamcp.nix: reviewed — included in a context-limited batchhosts/vega/databases/openwebui.nix: reviewed — included in a context-limited batchhosts/vega/databases/paperless.nix: reviewed — included in a context-limited batchhosts/vega/databases/postgres.nix: reviewed — included in a context-limited batchhosts/vega/databases/postgresql.nix: reviewed — included in a context-limited batchhosts/vega/databases/radarr.nix: reviewed — included in a context-limited batchhosts/vega/databases/sonarr.nix: reviewed — included in a context-limited batchhosts/vega/databases/whisparr-v3.nix: reviewed — included in a context-limited batchmodules/databases/immich.nix: reviewed — included in a context-limited batchmodules/databases/postgresql-role-password.nix: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
0c2aa9d3734abfc4171c16fd6ad4fb176c31a00aVerdict: Ready to merge
No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory.
Overall assessment
Refactor of Vega's per-service PostgreSQL role-password boilerplate into a new submodule option,
services.postgresql.rolePasswords.<name>(modules/databases/postgresql-role-password.nix), with freshrss, paperless, radarr, sonarr, whisparr-v3 (hosts/vega/databases/) and immich (modules/databases/immich.nix) migrated to the declarative form, and the five single-database stubs (atticd, forgejo, metamcp, openwebui, postgres) folded into a singleensureDatabaseslist in hosts/vega/databases/postgresql.nix. I checked the checked-out tree: all five folded database names are present in hosts/vega/databases/postgresql.nix:22 (atticd,forgejo,metamcp_db,openwebui,postgres), matching the deleted stub files in the diff; no file in the tree still imports the deleted stubs (grep databases/(atticd|forgejo|...)returns nothing) and no docs or tests reference them or the old unit/secret names (grep 'postgresql-set-'andgrep 'db-password-postgres'match only the new module). The SOPS keys used by the migrated call sites still resolve (secrets/databases/{radarr,sonarr,whisparr-v3}.yamleach containdatabase.password;secrets/freshrss.yamlandsecrets/paperless.yamlcontaindb-password). The module reproduces the previous generated output for the six call sites:owner/group/mode = "0400", theALTER ROLE "<role>" WITH LOGIN PASSWORDclause, theALTER DATABASE ... OWNER TOclauses for radarr/sonarr/whisparr-v3, thepostgresql-set-<name>-passwordunit names, thepostgresql-setup.serviceordering, and theserviceFailureMonitorentries. The heredoc terminatorSQLis emitted at column 0 after Nix indented-string de-indentation (minimum line indentation in thescriptstring is 10 spaces, and the closing''line is not counted), so it terminates for any number of SQL commands.serviceFailureMonitorconsumes itsserviceslist vialib.genAttrs(modules/services/service-failure-monitor.nix:74), so duplicate entries are collapsed. No blocking defect found; one actionable observation about an option whose meaning differs between the two places the module uses it.Blocking findings
None.
Important findings
None.
Suggestions
The submodule declares one
ensureDBOwnershipboolean (default true, documented as "Whether to grant ownership of specified databases to this role"), but the two consumers gate it differently: theservices.postgresql.ensureUsersentry at line 125 usesroleCfg.ensureDBOwnership && (builtins.elem roleCfg.role roleCfg.databases), while the generated unit at line 143 uses onlyroleCfg.ensureDBOwnership && roleCfg.databases != [ ]. In the supplied call sites this is what keeps radarr/sonarr/whisparr-v3 atensureDBOwnership = falseinensureUsers(their roles areradarr/sonarr/whisparr-v3whilehosts/vega/databases/radarr.nixdeclaresdatabases = [ "radarr-log" "radarr-main" ]) and attruefor freshrss/paperless/immich, which matches the pre-refactorensureUsersblocks in the diff. The name-equality test is an implicit condition no caller states.Impact: Ownership for a role whose name does not literally appear in its own
databaseslist is asserted only by the oneshot unit, never bypostgresql-setup, while a role whose name does coincide gets it from both. A caller that setsensureDBOwnership = trueexpectingpostgresql-setupto claim ownership gets a different result depending on the role/database naming, and a future rename of a role or database silently moves ownership between the two mechanisms. No current Vega configuration is mis-evaluated, so this is not a defect in the supplied state.Suggested fix: Make the intent explicit: drive both consumers from the single
ensureDBOwnershipflag (the unit'sALTER DATABASEalready covers the non-name-matching case), or split the option into two, e.g.setupDbOwnershipfor theensureUsersentry andassignOwnershipfor the generated unit, so the caller states which behaviour it wants instead of relying on name equality.Tests and validation
Questions
ensureUsers = [ { name = ...; ensureDBOwnership = true; } ]with noensureClauses; the module now always emitsensureClauses.login = roleCfg.loginwithlogindefaulting to true (modules/databases/postgresql-role-password.nix:70 and :124), sopostgresql-setupgrants LOGIN to those two roles. The end state matches the old oneshot units, which ranALTER ROLE <name> WITH LOGIN PASSWORD ..., but was the explicit LOGIN clause inensureUsersintended for these two roles?freshrss-db-password-postgres,paperless-db-password-postgres,radarr-db-password,sonarr-db-password,whisparr-v3-db-password,immich-db-password-postgrestopostgresql-role-password-<name>, which changes the installed secret file paths.grepover the checked-out tree finds no remaining reference to the old names, but I cannot see operator scripts, container bind mounts, or live host state outside the flake - can you confirm nothing external reads the old paths?../../../modules/databases/postgresql-role-password.nixand modules/databases/immich.nix:9 imports./postgresql-role-password.nix, and hosts/vega/default.nix imports both (lines 57 and 58). Itsconfigblock is therefore instantiated twice, soservices.postgresql.ensureDatabasesandensureUsersreceive each entry twice and each generated unit'swantedBy/after/requiresand each secret'srestartUnitslist is duplicated. I found no consumer that is order- or duplicate-sensitive (service-failure-monitor.nix useslib.genAttrs; the backup script enumerates databases from psql rather than fromensureDatabases), but please confirmnix flake checkand the evaluatedservices.postgresql.rolePasswordsattrset (six entries) are as intended.<<SQLheredoc instead of--command=. Was that switch deliberate (e.g. to keep multi-command units readable insystemctl cat), given that an unquoted heredoc also subjects its body to shell parameter expansion, which is what the$password_sqlinterpolation relies on?Review limitations
nix flake check, evaluate any host, or execute repository code; this review container has no Nix. The evaluated option values (the 14ensureDatabases, the 6ensureUsers, theserviceFailureMonitorentries, the generated unit scripts) are inferred by reading the module and call sites, not observed from an evaluation..sops.yamlkey/recipient policy, secret file contents beyond the keys I grepped, or live host state, running units, and activation behaviour.nix flake checkas the validation gate for Nix module/configuration changes), and tests/ contains no PostgreSQL fixtures (grep postgresqlin tests/ returns no matches).services.postgresqloption types or itspostgresql-setupscript behaviour against a source; claims aboutensureUsers/ensureClauses.loginsemantics are inferred from the diff's pre-refactor configuration, not from supplied nixpkgs source.Diff coverage
hosts/vega/databases/atticd.nix: reviewed — included in a context-limited batchhosts/vega/databases/forgejo.nix: reviewed — included in a context-limited batchhosts/vega/databases/freshrss.nix: reviewed — included in a context-limited batchhosts/vega/databases/metamcp.nix: reviewed — included in a context-limited batchhosts/vega/databases/openwebui.nix: reviewed — included in a context-limited batchhosts/vega/databases/paperless.nix: reviewed — included in a context-limited batchhosts/vega/databases/postgres.nix: reviewed — included in a context-limited batchhosts/vega/databases/postgresql.nix: reviewed — included in a context-limited batchhosts/vega/databases/radarr.nix: reviewed — included in a context-limited batchhosts/vega/databases/sonarr.nix: reviewed — included in a context-limited batchhosts/vega/databases/whisparr-v3.nix: reviewed — included in a context-limited batchmodules/databases/immich.nix: reviewed — included in a context-limited batchmodules/databases/postgresql-role-password.nix: reviewed — included in a context-limited batchReview metadata