@@ -54,6 +54,7 @@ in
5454
5555 frontendUrl = lib.mkOption {
5656 type = lib.types.str;
57+ apply = x: if lib.hasSuffix "/" x then x else x + "/";
5758 example = "keycloak.example.com/auth";
5859 description = ''
5960 The public URL used as base for all frontend requests. Should
@@ -84,111 +85,126 @@ in
8485 '';
8586 };
8687
87− certificatePrivateKeyBundle = lib.mkOption {
88+ sslCertificate = lib.mkOption {
8889 type = lib.types.nullOr lib.types.path;
8990 default = null;
9091 example = "/run/keys/ssl_cert";
9192 description = ''
92− The path to a PEM formatted bundle of the private key and
93− certificate to use for TLS connections.
93+ The path to a PEM formatted certificate to use for TLS/SSL
94+ connections.
9495
9596 This should be a string, not a Nix path, since Nix paths are
9697 copied into the world-readable Nix store.
9798 '';
9899 };
99100
100− databaseType = lib.mkOption {
101− type = lib.types.enum [ "mysql" "postgresql" ];
102− default = "postgresql";
103− example = "mysql";
101+ sslCertificateKey = lib.mkOption {
102+ type = lib.types.nullOr lib.types.path;
103+ default = null;
104+ example = "/run/keys/ssl_key";
104105 description = ''
105− The type of database Keycloak should connect to.
106− '';
107− };
106+ The path to a PEM formatted private key to use for TLS/SSL
107+ connections.
108108
109− databaseHost = lib.mkOption {
110− type = lib.types.str;
111− default = "localhost";
112− description = ''
113− Hostname of the database to connect to.
109+ This should be a string, not a Nix path, since Nix paths are
110+ copied into the world-readable Nix store.
114111 '';
115112 };
116113
117− databasePort =
118− let
119− dbPorts = {
120− postgresql = 5432;
121− mysql = 3306;
122− };
123− in
124− lib.mkOption {
125− type = lib.types.port;
126− default = dbPorts.${cfg.databaseType};
127− description = ''
128− Port of the database to connect to.
129− '';
130− };
114+ database = {
115+ type = lib.mkOption {
116+ type = lib.types.enum [ "mysql" "postgresql" ];
117+ default = "postgresql";
118+ example = "mysql";
119+ description = ''
120+ The type of database Keycloak should connect to.
121+ '';
122+ };
131123
132− databaseUseSSL = lib.mkOption {
133− type = lib.types.bool;
134− default = cfg.databaseHost != "localhost";
135− description = ''
136− Whether the database connection should be secured by SSL /
137− TLS.
138− '';
139− };
124+ host = lib.mkOption {
125+ type = lib.types.str;
126+ default = "localhost";
127+ description = ''
128+ Hostname of the database to connect to.
129+ '';
130+ };
140131
141− databaseCaCert = lib.mkOption {
142− type = lib.types.nullOr lib.types.path;
143− default = null;
144− description = ''
145− The SSL / TLS CA certificate that verifies the identity of the
146− database server.
132+ port =
133+ let
134+ dbPorts = {
135+ postgresql = 5432;
136+ mysql = 3306;
137+ };
138+ in
139+ lib.mkOption {
140+ type = lib.types.port;
141+ default = dbPorts.${cfg.database.type};
142+ description = ''
143+ Port of the database to connect to.
144+ '';
145+ };
147146
148− Required when PostgreSQL is used and SSL is turned on.
147+ useSSL = lib.mkOption {
148+ type = lib.types.bool;
149+ default = cfg.database.host != "localhost";
150+ description = ''
151+ Whether the database connection should be secured by SSL /
152+ TLS.
153+ '';
154+ };
149155
150− For MySQL, if left at <literal>null</literal>, the default
151− Java keystore is used, which should suffice if the server
152− certificate is issued by an official CA.
153− '';
154− };
156+ caCert = lib.mkOption {
157+ type = lib.types.nullOr lib.types.path;
158+ default = null;
159+ description = ''
160+ The SSL / TLS CA certificate that verifies the identity of the
161+ database server.
155162
156− databaseCreateLocally = lib.mkOption {
157− type = lib.types.bool;
158− default = true;
159− description = ''
160− Whether a database should be automatically created on the
161− local host. Set this to false if you plan on provisioning a
162− local database yourself. This has no effect if
163− services.keycloak.databaseHost is customized.
164− '';
165− };
163+ Required when PostgreSQL is used and SSL is turned on.
166164
167− databaseUsername = lib.mkOption {
168− type = lib.types.str;
169− default = "keycloak";
170− description = ''
171− Username to use when connecting to an external or manually
172− provisioned database; has no effect when a local database is
173− automatically provisioned.
174−
175− To use this with a local database, set <xref
176− linkend="opt-services.keycloak.databaseCreateLocally" /> to
177− <literal>false</literal> and create the database and user
178− manually. The database should be called
179− <literal>keycloak</literal>.
180− '';
181− };
165+ For MySQL, if left at <literal>null</literal>, the default
166+ Java keystore is used, which should suffice if the server
167+ certificate is issued by an official CA.
168+ '';
169+ };
182170
183− databasePasswordFile = lib.mkOption {
184− type = lib.types.path;
185− example = "/run/keys/db_password";
186− description = ''
187− File containing the database password.
171+ createLocally = lib.mkOption {
172+ type = lib.types.bool;
173+ default = true;
174+ description = ''
175+ Whether a database should be automatically created on the
176+ local host. Set this to false if you plan on provisioning a
177+ local database yourself. This has no effect if
178+ services.keycloak.database.host is customized.
179+ '';
180+ };
188181
189− This should be a string, not a Nix path, since Nix paths are
190− copied into the world-readable Nix store.
191− '';
182+ username = lib.mkOption {
183+ type = lib.types.str;
184+ default = "keycloak";
185+ description = ''
186+ Username to use when connecting to an external or manually
187+ provisioned database; has no effect when a local database is
188+ automatically provisioned.
189+
190+ To use this with a local database, set <xref
191+ linkend="opt-services.keycloak.database.createLocally" /> to
192+ <literal>false</literal> and create the database and user
193+ manually. The database should be called
194+ <literal>keycloak</literal>.
195+ '';
196+ };
197+
198+ passwordFile = lib.mkOption {
199+ type = lib.types.path;
200+ example = "/run/keys/db_password";
201+ description = ''
202+ File containing the database password.
203+
204+ This should be a string, not a Nix path, since Nix paths are
205+ copied into the world-readable Nix store.
206+ '';
207+ };
192208 };
193209
194210 package = lib.mkOption {
@@ -261,12 +277,12 @@ in
261277 config =
262278 let
263279 # We only want to create a database if we're actually going to connect to it.
264− databaseActuallyCreateLocally = cfg.databaseCreateLocally && cfg.databaseHost == "localhost";
265− createLocalPostgreSQL = databaseActuallyCreateLocally && cfg.databaseType == "postgresql";
266− createLocalMySQL = databaseActuallyCreateLocally && cfg.databaseType == "mysql";
280+ databaseActuallyCreateLocally = cfg.database.createLocally && cfg.database.host == "localhost";
281+ createLocalPostgreSQL = databaseActuallyCreateLocally && cfg.database.type == "postgresql";
282+ createLocalMySQL = databaseActuallyCreateLocally && cfg.database.type == "mysql";
267283
268284 mySqlCaKeystore = pkgs.runCommandNoCC "mysql-ca-keystore" {} ''
269− ${pkgs.jre}/bin/keytool -importcert -trustcacerts -alias MySQLCACert -file ${cfg.databaseCaCert} -keystore $out -storepass notsosecretpassword -noprompt
285+ ${pkgs.jre}/bin/keytool -importcert -trustcacerts -alias MySQLCACert -file ${cfg.database.caCert} -keystore $out -storepass notsosecretpassword -noprompt
270286 '';
271287
272288 keycloakConfig' = builtins.foldl' lib.recursiveUpdate {
@@ -282,11 +298,11 @@ in
282298 };
283299 "subsystem=datasources"."data-source=KeycloakDS" = {
284300 max-pool-size = "20";
285− user-name = if databaseActuallyCreateLocally then "keycloak" else cfg.databaseUsername;
301+ user-name = if databaseActuallyCreateLocally then "keycloak" else cfg.database.username;
286302 password = "@db-password@";
287303 };
288304 } [
289− (lib.optionalAttrs (cfg.databaseType == "postgresql") {
305+ (lib.optionalAttrs (cfg.database.type == "postgresql") {
290306 "subsystem=datasources" = {
291307 "jdbc-driver=postgresql" = {
292308 driver-module-name = "org.postgresql";
@@ -294,16 +310,16 @@ in
294310 driver-xa-datasource-class-name = "org.postgresql.xa.PGXADataSource";
295311 };
296312 "data-source=KeycloakDS" = {
297− connection-url = "jdbc:postgresql://${cfg.databaseHost}:${builtins.toString cfg.databasePort}/keycloak";
313+ connection-url = "jdbc:postgresql://${cfg.database.host}:${builtins.toString cfg.database.port}/keycloak";
298314 driver-name = "postgresql";
299− "connection-properties=ssl".value = lib.boolToString cfg.databaseUseSSL;
300− } // (lib.optionalAttrs (cfg.databaseCaCert != null) {
301− "connection-properties=sslrootcert".value = cfg.databaseCaCert;
315+ "connection-properties=ssl".value = lib.boolToString cfg.database.useSSL;
316+ } // (lib.optionalAttrs (cfg.database.caCert != null) {
317+ "connection-properties=sslrootcert".value = cfg.database.caCert;
302318 "connection-properties=sslmode".value = "verify-ca";
303319 });
304320 };
305321 })
306− (lib.optionalAttrs (cfg.databaseType == "mysql") {
322+ (lib.optionalAttrs (cfg.database.type == "mysql") {
307323 "subsystem=datasources" = {
308324 "jdbc-driver=mysql" = {
309325 driver-module-name = "com.mysql";
@@ -311,22 +327,22 @@ in
311327 driver-class-name = "com.mysql.jdbc.Driver";
312328 };
313329 "data-source=KeycloakDS" = {
314− connection-url = "jdbc:mysql://${cfg.databaseHost}:${builtins.toString cfg.databasePort}/keycloak";
330+ connection-url = "jdbc:mysql://${cfg.database.host}:${builtins.toString cfg.database.port}/keycloak";
315331 driver-name = "mysql";
316− "connection-properties=useSSL".value = lib.boolToString cfg.databaseUseSSL;
317− "connection-properties=requireSSL".value = lib.boolToString cfg.databaseUseSSL;
318− "connection-properties=verifyServerCertificate".value = lib.boolToString cfg.databaseUseSSL;
332+ "connection-properties=useSSL".value = lib.boolToString cfg.database.useSSL;
333+ "connection-properties=requireSSL".value = lib.boolToString cfg.database.useSSL;
334+ "connection-properties=verifyServerCertificate".value = lib.boolToString cfg.database.useSSL;
319335 "connection-properties=characterEncoding".value = "UTF-8";
320336 valid-connection-checker-class-name = "org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker";
321337 validate-on-match = true;
322338 exception-sorter-class-name = "org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter";
323− } // (lib.optionalAttrs (cfg.databaseCaCert != null) {
339+ } // (lib.optionalAttrs (cfg.database.caCert != null) {
324340 "connection-properties=trustCertificateKeyStoreUrl".value = "file:${mySqlCaKeystore}";
325341 "connection-properties=trustCertificateKeyStorePassword".value = "notsosecretpassword";
326342 });
327343 };
328344 })
329− (lib.optionalAttrs (cfg.certificatePrivateKeyBundle != null) {
345+ (lib.optionalAttrs (cfg.sslCertificate != null && cfg.sslCertificateKey != null) {
330346 "socket-binding-group=standard-sockets"."socket-binding=https".port = cfg.httpsPort;
331347 "core-service=management"."security-realm=UndertowRealm"."server-identity=ssl" = {
332348 keystore-path = "/run/keycloak/ssl/certificate_private_key_bundle.p12";
@@ -537,7 +553,9 @@ in
537553
538554 jbossCliScript = pkgs.writeText "jboss-cli-script" (mkJbossScript keycloakConfig');
539555
540− keycloakConfig = pkgs.runCommandNoCC "keycloak-config" {} ''
556+ keycloakConfig = pkgs.runCommandNoCC "keycloak-config" {
557+ nativeBuildInputs = [ cfg.package ];
558+ } ''
541559 export JBOSS_BASE_DIR="$(pwd -P)";
542560 export JBOSS_MODULEPATH="${cfg.package}/modules";
543561 export JBOSS_LOG_DIR="$JBOSS_BASE_DIR/log";
@@ -547,11 +565,11 @@ in
547565
548566 mkdir -p {deployments,ssl}
549567
550− "${cfg.package}/bin/standalone.sh"&
568+ standalone.sh&
551569
552570 attempt=1
553571 max_attempts=30
554− while ! ${cfg.package}/bin/jboss-cli.sh --connect ':read-attribute(name=server-state)'; do
572+ while ! jboss-cli.sh --connect ':read-attribute(name=server-state)'; do
555573 if [[ "$attempt" == "$max_attempts" ]]; then
556574 echo "ERROR: Could not connect to Keycloak after $attempt attempts! Failing.." >&2
557575 exit 1
@@ -561,7 +579,7 @@ in
561579 (( attempt++ ))
562580 done
563581
564− ${cfg.package}/bin/jboss-cli.sh --connect --file=${jbossCliScript} --echo-command
582+ jboss-cli.sh --connect --file=${jbossCliScript} --echo-command
565583
566584 cp configuration/standalone.xml $out
567585 '';
@@ -570,8 +588,8 @@ in
570588
571589 assertions = [
572590 {
573− assertion = (cfg.databaseUseSSL && cfg.databaseType == "postgresql") -> (cfg.databaseCaCert != null);
574− message = "A CA certificate must be specified (in 'services.keycloak.databaseCaCert') when PostgreSQL is used with SSL";
591+ assertion = (cfg.database.useSSL && cfg.database.type == "postgresql") -> (cfg.database.caCert != null);
592+ message = "A CA certificate must be specified (in 'services.keycloak.database.caCert') when PostgreSQL is used with SSL";
575593 }
576594 ];
577595
@@ -581,6 +599,7 @@ in
581599 after = [ "postgresql.service" ];
582600 before = [ "keycloak.service" ];
583601 bindsTo = [ "postgresql.service" ];
602+ path = [ config.services.postgresql.package ];
584603 serviceConfig = {
585604 Type = "oneshot";
586605 RemainAfterExit = true;
@@ -588,13 +607,15 @@ in
588607 Group = "postgres";
589608 };
590609 script = ''
591− set -eu
610+ set -o errexit -o pipefail -o nounset -o errtrace
611+ shopt -s inherit_errexit
592612
593− PSQL=${config.services.postgresql.package}/bin/psql
613+ create_role="$(mktemp)"
614+ trap 'rm -f "$create_role"' ERR EXIT
594615
595− db_password="$(<'${cfg.databasePasswordFile}')"
596− $PSQL -tAc "SELECT 1 FROM pg_roles WHERE rolname='keycloak'" | grep -q 1 || $PSQL -tAc "CREATE ROLE keycloak WITH LOGIN PASSWORD '$db_password' CREATEDB"
597− $PSQL -tAc "SELECT 1 FROM pg_database WHERE datname = 'keycloak'" | grep -q 1 || $PSQL -tAc 'CREATE DATABASE "keycloak" OWNER "keycloak"'
616+ echo "CREATE ROLE keycloak WITH LOGIN PASSWORD '$(<'${cfg.database.passwordFile}')' CREATEDB" > "$create_role"
617+ psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='keycloak'" | grep -q 1 || psql -tA --file="$create_role"
618+ psql -tAc "SELECT 1 FROM pg_database WHERE datname = 'keycloak'" | grep -q 1 || psql -tAc 'CREATE DATABASE "keycloak" OWNER "keycloak"'
598619 '';
599620 };
600621
@@ -602,6 +623,7 @@ in
602623 after = [ "mysql.service" ];
603624 before = [ "keycloak.service" ];
604625 bindsTo = [ "mysql.service" ];
626+ path = [ config.services.mysql.package ];
605627 serviceConfig = {
606628 Type = "oneshot";
607629 RemainAfterExit = true;
@@ -609,13 +631,14 @@ in
609631 Group = config.services.mysql.group;
610632 };
611633 script = ''
612− set -eu
634+ set -o errexit -o pipefail -o nounset -o errtrace
635+ shopt -s inherit_errexit
613636
614− db_password="$(<'${cfg.databasePasswordFile}')"
637+ db_password="$(<'${cfg.database.passwordFile}')"
615638 ( echo "CREATE USER IF NOT EXISTS 'keycloak'@'localhost' IDENTIFIED BY '$db_password';"
616639 echo "CREATE DATABASE keycloak CHARACTER SET utf8 COLLATE utf8_unicode_ci;"
617640 echo "GRANT ALL PRIVILEGES ON keycloak.* TO 'keycloak'@'localhost';"
618− ) | ${config.services.mysql.package}/bin/mysql -N
641+ ) | mysql -N
619642 '';
620643 };
621644
@@ -634,6 +657,8 @@ in
634657 bindsTo = databaseServices;
635658 wantedBy = [ "multi-user.target" ];
636659 path = with pkgs; [
660+ cfg.package
661+ openssl
637662 replace-secret
638663 ];
639664 environment = {
@@ -644,14 +669,21 @@ in
644669 serviceConfig = {
645670 ExecStartPre = let
646671 startPreFullPrivileges = ''
647− set -eu
672+ set -o errexit -o pipefail -o nounset -o errtrace
673+ shopt -s inherit_errexit
648674
649− install -T -m 0400 -o keycloak -g keycloak '${cfg.databasePasswordFile}' /run/keycloak/secrets/db_password
650− '' + lib.optionalString (cfg.certificatePrivateKeyBundle != null) ''
651− install -T -m 0400 -o keycloak -g keycloak '${cfg.certificatePrivateKeyBundle}' /run/keycloak/secrets/ssl_cert_pk_bundle
675+ umask u=rwx,g=,o=
676+
677+ install -T -m 0400 -o keycloak -g keycloak '${cfg.database.passwordFile}' /run/keycloak/secrets/db_password
678+ '' + lib.optionalString (cfg.sslCertificate != null && cfg.sslCertificateKey != null) ''
679+ install -T -m 0400 -o keycloak -g keycloak '${cfg.sslCertificate}' /run/keycloak/secrets/ssl_cert
680+ install -T -m 0400 -o keycloak -g keycloak '${cfg.sslCertificateKey}' /run/keycloak/secrets/ssl_key
652681 '';
653682 startPre = ''
654− set -eu
683+ set -o errexit -o pipefail -o nounset -o errtrace
684+ shopt -s inherit_errexit
685+
686+ umask u=rwx,g=,o=
655687
656688 install -m 0600 ${cfg.package}/standalone/configuration/*.properties /run/keycloak/configuration
657689 install -T -m 0600 ${keycloakConfig} /run/keycloak/configuration/standalone.xml
@@ -659,13 +691,16 @@ in
659691 replace-secret '@db-password@' '/run/keycloak/secrets/db_password' /run/keycloak/configuration/standalone.xml
660692
661693 export JAVA_OPTS=-Djboss.server.config.user.dir=/run/keycloak/configuration
662− ${cfg.package}/bin/add-user-keycloak.sh -u admin -p '${cfg.initialAdminPassword}'
663− '' + lib.optionalString (cfg.certificatePrivateKeyBundle != null) ''
694+ add-user-keycloak.sh -u admin -p '${cfg.initialAdminPassword}'
695+ '' + lib.optionalString (cfg.sslCertificate != null && cfg.sslCertificateKey != null) ''
664696 pushd /run/keycloak/ssl/
665− cat /run/keycloak/secrets/ssl_cert_pk_bundle <(echo) /etc/ssl/certs/ca-certificates.crt > allcerts.pem
666− ${pkgs.openssl}/bin/openssl pkcs12 -export -in /run/keycloak/secrets/ssl_cert_pk_bundle -chain \
667− -name "${cfg.frontendUrl}" -out certificate_private_key_bundle.p12 \
668− -CAfile allcerts.pem -passout pass:notsosecretpassword
697+ cat /run/keycloak/secrets/ssl_cert <(echo) \
698+ /run/keycloak/secrets/ssl_key <(echo) \
699+ /etc/ssl/certs/ca-certificates.crt \
700+ > allcerts.pem
701+ openssl pkcs12 -export -in /run/keycloak/secrets/ssl_cert -inkey /run/keycloak/secrets/ssl_key -chain \
702+ -name "${cfg.frontendUrl}" -out certificate_private_key_bundle.p12 \
703+ -CAfile allcerts.pem -passout pass:notsosecretpassword
669704 popd
670705 '';
671706 in [
@@ -697,4 +732,5 @@ in
697732 };
698733
699734 meta.doc = ./keycloak.xml;
735+ meta.maintainers = [ lib.maintainers.talyz ];
700736}