wchisp: remove overuse of with lib (#357239)
[NixPkgs.git] / nixos / tests / keycloak.nix
blobbaed9419061dfc6eddf67075e4b6bec2fcc99f37
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.
5 let
6   certs = import ./common/acme/server/snakeoil-certs.nix;
7   frontendUrl = "https://${certs.domain}";
9   keycloakTest = databaseType: import ./make-test-python.nix (
10     { pkgs, ... }:
11     let
12       initialAdminPassword = "h4Iho\"JFn't2>iQIR9";
13       adminPasswordFile = pkgs.writeText "admin-password" "${initialAdminPassword}";
14     in
15     {
16       name = "keycloak";
17       meta = with pkgs.lib.maintainers; {
18         maintainers = [ talyz ];
19       };
21       nodes = {
22         keycloak = { config, ... }: {
23           virtualisation.memorySize = 2047;
25           security.pki.certificateFiles = [
26             certs.ca.cert
27           ];
29           networking.extraHosts = ''
30             127.0.0.1 ${certs.domain}
31           '';
33           services.keycloak = {
34             enable = true;
35             settings = {
36               hostname = certs.domain;
37             };
38             inherit initialAdminPassword;
39             sslCertificate = "${certs.${certs.domain}.cert}";
40             sslCertificateKey = "${certs.${certs.domain}.key}";
41             database = {
42               type = databaseType;
43               username = "bogus";
44               name = "also bogus";
45               passwordFile = "${pkgs.writeText "dbPassword" ''wzf6\"vO"Cb\nP>p#6;c&o?eu=q'THE'''H''''E''}";
46             };
47             plugins = with config.services.keycloak.package.plugins; [
48               keycloak-discord
49               keycloak-metrics-spi
50             ];
51           };
52           environment.systemPackages = with pkgs; [
53             htmlq
54             jq
55           ];
56         };
57       };
59       testScript =
60         let
61           client = {
62             clientId = "test-client";
63             name = "test-client";
64             redirectUris = [ "urn:ietf:wg:oauth:2.0:oob" ];
65           };
67           user = {
68             firstName = "Chuck";
69             lastName = "Testa";
70             username = "chuck.testa";
71             email = "chuck.testa@example.com";
72           };
74           password = "password1234";
76           realm = {
77             enabled = true;
78             realm = "test-realm";
79             clients = [ client ];
80             users = [
81               (
82                 user // {
83                   enabled = true;
84                   credentials = [{
85                     type = "password";
86                     temporary = false;
87                     value = password;
88                   }];
89                 }
90               )
91             ];
92           };
94           realmDataJson = pkgs.writeText "realm-data.json" (builtins.toJSON realm);
96           jqCheckUserinfo = pkgs.writeText "check-userinfo.jq" ''
97             if {
98               "firstName": .given_name,
99               "lastName": .family_name,
100               "username": .preferred_username,
101               "email": .email
102             } != ${builtins.toJSON user} then
103               error("Wrong user info!")
104             else
105               empty
106             end
107           '';
108         in ''
109           keycloak.start()
110           keycloak.wait_for_unit("keycloak.service")
111           keycloak.wait_for_open_port(443)
112           keycloak.wait_until_succeeds("curl -sSf ${frontendUrl}")
114           ### Realm Setup ###
116           # Get an admin interface access token
117           keycloak.succeed("""
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
124           """)
126           # Register the metrics SPI
127           keycloak.succeed(
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'"""
132           )
134           # Publish the realm, including a test OIDC client and user
135           keycloak.succeed(
136               "curl -sSf -H @admin_auth_header -X POST -H 'Content-Type: application/json' -d @${realmDataJson} '${frontendUrl}/admin/realms/'"
137           )
139           # Generate and save the client secret. To do this we need
140           # Keycloak's internal id for the client.
141           keycloak.succeed(
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",
144           )
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
152           # post url.
153           keycloak.succeed(
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"
156           )
158           # Post the login form and save the response. Once again tidy up
159           # the HTML, then extract the authorization code.
160           keycloak.succeed(
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"
163           )
165           # Exchange the authorization code for an access token.
166           keycloak.succeed(
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"
168           )
170           # Use the access token on the OIDC userinfo endpoint and check
171           # that the returned user info matches what we initialized the
172           # realm with.
173           keycloak.succeed(
174               "curl -sSf -H @auth_header '${frontendUrl}/realms/${realm.realm}/protocol/openid-connect/userinfo' | jq -f ${jqCheckUserinfo}"
175           )
176         '';
177     }
178   );
181   postgres = keycloakTest "postgresql";
182   mariadb = keycloakTest "mariadb";
183   mysql = keycloakTest "mysql";