1 # This tests Keycloak: it starts the service, creates a realm with an
2 # OIDC client and a user, and simulates the user logging in to the
3 # client using their Keycloak login.
6 certs = import ./common/acme/server/snakeoil-certs.nix;
7 frontendUrl = "https://${certs.domain}";
9 keycloakTest = databaseType: import ./make-test-python.nix (
12 initialAdminPassword = "h4Iho\"JFn't2>iQIR9";
13 adminPasswordFile = pkgs.writeText "admin-password" "${initialAdminPassword}";
17 meta = with pkgs.lib.maintainers; {
18 maintainers = [ talyz ];
22 keycloak = { config, ... }: {
23 virtualisation.memorySize = 2047;
25 security.pki.certificateFiles = [
29 networking.extraHosts = ''
30 127.0.0.1 ${certs.domain}
36 hostname = certs.domain;
38 inherit initialAdminPassword;
39 sslCertificate = "${certs.${certs.domain}.cert}";
40 sslCertificateKey = "${certs.${certs.domain}.key}";
45 passwordFile = "${pkgs.writeText "dbPassword" ''wzf6\"vO"Cb\nP>p#6;c&o?eu=q'THE'''H''''E''}";
47 plugins = with config.services.keycloak.package.plugins; [
52 environment.systemPackages = with pkgs; [
62 clientId = "test-client";
64 redirectUris = [ "urn:ietf:wg:oauth:2.0:oob" ];
70 username = "chuck.testa";
71 email = "chuck.testa@example.com";
74 password = "password1234";
94 realmDataJson = pkgs.writeText "realm-data.json" (builtins.toJSON realm);
96 jqCheckUserinfo = pkgs.writeText "check-userinfo.jq" ''
98 "firstName": .given_name,
99 "lastName": .family_name,
100 "username": .preferred_username,
102 } != ${builtins.toJSON user} then
103 error("Wrong user info!")
110 keycloak.wait_for_unit("keycloak.service")
111 keycloak.wait_for_open_port(443)
112 keycloak.wait_until_succeeds("curl -sSf ${frontendUrl}")
116 # Get an admin interface access token
118 curl -sSf -d 'client_id=admin-cli' \
119 -d 'username=admin' \
120 -d "password=$(<${adminPasswordFile})" \
121 -d 'grant_type=password' \
122 '${frontendUrl}/realms/master/protocol/openid-connect/token' \
123 | jq -r '"Authorization: bearer " + .access_token' >admin_auth_header
126 # Register the metrics SPI
128 """${pkgs.jre}/bin/keytool -import -alias snakeoil -file ${certs.ca.cert} -storepass aaaaaa -keystore cacert.jks -noprompt""",
129 """KC_OPTS='-Djavax.net.ssl.trustStore=cacert.jks -Djavax.net.ssl.trustStorePassword=aaaaaa' kcadm.sh config credentials --server '${frontendUrl}' --realm master --user admin --password "$(<${adminPasswordFile})" """,
130 """KC_OPTS='-Djavax.net.ssl.trustStore=cacert.jks -Djavax.net.ssl.trustStorePassword=aaaaaa' kcadm.sh update events/config -s 'eventsEnabled=true' -s 'adminEventsEnabled=true' -s 'eventsListeners+=metrics-listener'""",
131 """curl -sSf '${frontendUrl}/realms/master/metrics' | grep '^keycloak_admin_event_UPDATE'"""
134 # Publish the realm, including a test OIDC client and user
136 "curl -sSf -H @admin_auth_header -X POST -H 'Content-Type: application/json' -d @${realmDataJson} '${frontendUrl}/admin/realms/'"
139 # Generate and save the client secret. To do this we need
140 # Keycloak's internal id for the client.
142 "curl -sSf -H @admin_auth_header '${frontendUrl}/admin/realms/${realm.realm}/clients?clientId=${client.name}' | jq -r '.[].id' >client_id",
143 "curl -sSf -H @admin_auth_header -X POST '${frontendUrl}/admin/realms/${realm.realm}/clients/'$(<client_id)'/client-secret' | jq -r .value >client_secret",
147 ### Authentication Testing ###
149 # Start the login process by sending an initial request to the
150 # OIDC authentication endpoint, saving the returned page. Tidy
151 # up the HTML (XmlStarlet is picky) and extract the login form
154 "curl -sSf -c cookie '${frontendUrl}/realms/${realm.realm}/protocol/openid-connect/auth?client_id=${client.name}&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=openid+email&response_type=code&response_mode=query&nonce=qw4o89g3qqm' >login_form",
155 "htmlq '#kc-form-login' --attribute action --filename login_form --output form_post_url"
158 # Post the login form and save the response. Once again tidy up
159 # the HTML, then extract the authorization code.
161 "curl -sSf -L -b cookie -d 'username=${user.username}' -d 'password=${password}' -d 'credentialId=' \"$(<form_post_url)\" >auth_code_html",
162 "htmlq '#code' --attribute value --filename auth_code_html --output auth_code"
165 # Exchange the authorization code for an access token.
167 "curl -sSf -d grant_type=authorization_code -d code=$(<auth_code) -d client_id=${client.name} -d client_secret=$(<client_secret) -d redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob '${frontendUrl}/realms/${realm.realm}/protocol/openid-connect/token' | jq -r '\"Authorization: bearer \" + .access_token' >auth_header"
170 # Use the access token on the OIDC userinfo endpoint and check
171 # that the returned user info matches what we initialized the
174 "curl -sSf -H @auth_header '${frontendUrl}/realms/${realm.realm}/protocol/openid-connect/userinfo' | jq -f ${jqCheckUserinfo}"
181 postgres = keycloakTest "postgresql";
182 mariadb = keycloakTest "mariadb";
183 mysql = keycloakTest "mysql";