828dcb39c9dd850587649180d825a27d2419f691
[nonrtric.git] / test / common / keycloak_api_functions.sh
1 #!/bin/bash
2
3 #  ============LICENSE_START===============================================
4 #  Copyright (C) 2021 Nordix Foundation. All rights reserved.
5 #  ========================================================================
6 #  Licensed under the Apache License, Version 2.0 (the "License");
7 #  you may not use this file except in compliance with the License.
8 #  You may obtain a copy of the License at
9 #
10 #       http://www.apache.org/licenses/LICENSE-2.0
11 #
12 #  Unless required by applicable law or agreed to in writing, software
13 #  distributed under the License is distributed on an "AS IS" BASIS,
14 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 #  See the License for the specific language governing permissions and
16 #  limitations under the License.
17 #  ============LICENSE_END=================================================
18 #
19
20 # This is a script that contains container/service management functions and test functions for Keycloak
21
22
23 ################ Test engine functions ################
24
25 # Create the image var used during the test
26 # arg: <image-tag-suffix> (selects staging, snapshot, release etc)
27 # <image-tag-suffix> is present only for images with staging, snapshot,release tags
28 __KEYCLOAK_imagesetup() {
29         __check_and_create_image_var KEYCLOAK "KEYCLOAK_IMAGE" "KEYCLOAK_IMAGE_BASE" "KEYCLOAK_IMAGE_TAG" REMOTE_OTHER "$KEYCLOAK_DISPLAY_NAME"
30 }
31
32 # Pull image from remote repo or use locally built image
33 # arg: <pull-policy-override> <pull-policy-original>
34 # <pull-policy-override> Shall be used for images allowing overriding. For example use a local image when test is started to use released images
35 # <pull-policy-original> Shall be used for images that does not allow overriding
36 # Both var may contain: 'remote', 'remote-remove' or 'local'
37 __KEYCLOAK_imagepull() {
38         __check_and_pull_image $2 "$KEYCLOAK_DISPLAY_NAME" $KEYCLOAK_APP_NAME KEYCLOAK_IMAGE
39 }
40
41 # Build image (only for simulator or interfaces stubs owned by the test environment)
42 # arg: <image-tag-suffix> (selects staging, snapshot, release etc)
43 # <image-tag-suffix> is present only for images with staging, snapshot,release tags
44 __KEYCLOAK_imagebuild() {
45         echo -e $RED" Image for app KEYCLOAK shall never be built"$ERED
46 }
47
48 # Generate a string for each included image using the app display name and a docker images format string
49 # If a custom image repo is used then also the source image from the local repo is listed
50 # arg: <docker-images-format-string> <file-to-append>
51 __KEYCLOAK_image_data() {
52         echo -e "$KEYCLOAK_DISPLAY_NAME\t$(docker images --format $1 $KEYCLOAK_IMAGE)" >>   $2
53         if [ ! -z "$KEYCLOAK_IMAGE_SOURCE" ]; then
54                 echo -e "-- source image --\t$(docker images --format $1 $KEYCLOAK_IMAGE_SOURCE)" >>   $2
55         fi
56 }
57
58 # Scale kubernetes resources to zero
59 # All resources shall be ordered to be scaled to 0, if relevant. If not relevant to scale, then do no action.
60 # This function is called for apps fully managed by the test script
61 __KEYCLOAK_kube_scale_zero() {
62         __kube_scale_all_resources $KUBE_KEYCLOAK_NAMESPACE autotest KEYCLOAK
63 }
64
65 # Scale kubernetes resources to zero and wait until this has been accomplished, if relevant. If not relevant to scale, then do no action.
66 # This function is called for prestarted apps not managed by the test script.
67 __KEYCLOAK_kube_scale_zero_and_wait() {
68         echo -e $RED" KEYCLOAK app is not scaled in this state"$ERED
69 }
70
71 # Delete all kube resouces for the app
72 # This function is called for apps managed by the test script.
73 __KEYCLOAK_kube_delete_all() {
74         __kube_delete_all_resources $KUBE_KEYCLOAK_NAMESPACE autotest KEYCLOAK
75 }
76
77 # Store docker logs
78 # This function is called for apps managed by the test script.
79 # args: <log-dir> <file-prexix>
80 __KEYCLOAK_store_docker_logs() {
81         if [ $RUNMODE == "KUBE" ]; then
82                 kubectl $KUBECONF  logs -l "autotest=KEYCLOAK" -n $KUBE_KEYCLOAK_NAMESPACE --tail=-1 > $1$2_keycloak.log 2>&1
83         else
84                 docker logs $KEYCLOAK_APP_NAME > $1$2_keycloak.log 2>&1
85         fi
86 }
87
88 # Initial setup of protocol, host and ports
89 # This function is called for apps managed by the test script.
90 # args: -
91 __KEYCLOAK_initial_setup() {
92         use_keycloak_http
93 }
94
95 # Set app short-name, app name and namespace for logging runtime statistics of kubernets pods or docker containers
96 # For docker, the namespace shall be excluded
97 # This function is called for apps managed by the test script as well as for prestarted apps.
98 # args: -
99 __KEYCLOAK_statisics_setup() {
100         if [ $RUNMODE == "KUBE" ]; then
101                 echo "KEYCLOAK $KEYCLOAK_APP_NAME $KUBE_KEYCLOAK_NAMESPACE"
102         else
103                 echo "KEYCLOAK $KEYCLOAK_APP_NAME"
104         fi
105 }
106
107 # Check application requirements, e.g. helm, the the test needs. Exit 1 if req not satisfied
108 # args: -
109 __KEYCLOAK_test_requirements() {
110         which jq > /dev/null
111         if [ $? -ne 0 ]; then
112                 echo $RED" 'jq' is required to run tests. Pls install 'jq'"
113                 return 1
114         fi
115 }
116
117 #######################################################
118
119 # Set http as the protocol to use for all communication to the Keycloak
120 # args: -
121 # (Function for test scripts)
122 use_keycloak_http() {
123         __keycloak_set_protocoll "http" $KEYCLOAK_INTERNAL_PORT $KEYCLOAK_EXTERNAL_PORT
124 }
125
126 # Set https as the protocol to use for all communication to the Keycloak
127 # args: -
128 # (Function for test scripts)
129 use_keycloak_https() {
130         __keycloak_set_protocoll "https" $KEYCLOAK_INTERNAL_SECURE_PORT $KEYCLOAK_EXTERNAL_SECURE_PORT
131 }
132
133 # Setup paths to svc/container for internal and external access
134 # args: <protocol> <internal-port> <external-port>
135 __keycloak_set_protocoll() {
136         echo -e $BOLD"$KEYCLOAK_DISPLAY_NAME protocol setting"$EBOLD
137         echo -e " Using $BOLD $1 $EBOLD towards $KEYCLOAK_DISPLAY_NAME"
138
139         ## Access to Keycloak
140
141         KEYCLOAK_SERVICE_PATH=$1"://"$KEYCLOAK_APP_NAME":"$2  # docker access, container->container and script->container via proxy
142         KEYCLOAK_SERVICE_PORT=$2
143         KEYCLOAK_SERVICE_HOST=$KEYCLOAK_APP_NAME
144         KEYCLOAK_ISSUER_PATH=$1"://"$KEYCLOAK_APP_NAME
145         if [ $RUNMODE == "KUBE" ]; then
146                 KEYCLOAK_SERVICE_PATH=$1"://"$KEYCLOAK_APP_NAME.$KUBE_KEYCLOAK_NAMESPACE":"$3 # kube access, pod->svc and script->svc via proxy
147                 KEYCLOAK_SERVICE_PORT=$3
148                 KEYCLOAK_SERVICE_HOST=$KEYCLOAK_APP_NAME.$KUBE_KEYCLOAK_NAMESPACE
149                 KEYCLOAK_ISSUER_PATH=$1"://"$KEYCLOAK_APP_NAME.$KUBE_KEYCLOAK_NAMESPACE
150         fi
151         KEYCLOAK_SERVICE_HTTPX=$1
152
153         echo ""
154 }
155
156 ### Admin API functions Keycloak
157
158 ###########################
159 ### Keycloak functions
160 ###########################
161
162 # Export env vars for config files, docker compose and kube resources
163 # args:
164 __keycloak_export_vars() {
165         export KEYCLOAK_APP_NAME
166         export KEYCLOAK_DISPLAY_NAME
167
168         export DOCKER_SIM_NWNAME
169         export KUBE_KEYCLOAK_NAMESPACE
170
171         export KEYCLOAK_IMAGE
172         export KEYCLOAK_INTERNAL_PORT
173         export KEYCLOAK_EXTERNAL_PORT
174
175         export KEYCLOAK_ADMIN_USER
176         export KEYCLOAK_ADMIN_PWD
177         export KEYCLOAK_KC_PROXY
178 }
179
180
181 # Start the Keycloak in the simulator group
182 # args: -
183 # (Function for test scripts)
184 start_keycloak() {
185
186         echo -e $BOLD"Starting $KEYCLOAK_DISPLAY_NAME"$EBOLD
187
188         if [ $RUNMODE == "KUBE" ]; then
189
190                 # Check if app shall be fully managed by the test script
191                 __check_included_image "KEYCLOAK"
192                 retcode_i=$?
193
194                 # Check if app shall only be used by the testscipt
195                 __check_prestarted_image "KEYCLOAK"
196                 retcode_p=$?
197
198                 if [ $retcode_i -ne 0 ] && [ $retcode_p -ne 0 ]; then
199                         echo -e $RED"The $KEYCLOAK_NAME app is not included as managed nor prestarted in this test script"$ERED
200                         echo -e $RED"The $KEYCLOAK_APP_NAME will not be started"$ERED
201                         exit
202                 fi
203                 if [ $retcode_i -eq 0 ] && [ $retcode_p -eq 0 ]; then
204                         echo -e $RED"The $KEYCLOAK_APP_NAME app is included both as managed and prestarted in this test script"$ERED
205                         echo -e $RED"The $KEYCLOAK_APP_NAME will not be started"$ERED
206                         exit
207                 fi
208
209                 if [ $retcode_p -eq 0 ]; then
210                         echo -e " Using existing $KEYCLOAK_APP_NAME deployment and service"
211                         echo " Setting keycloak replicas=1"
212                         __kube_scale deployment $KEYCLOAK_APP_NAME $KUBE_KEYCLOAK_NAMESPACE 1
213                 fi
214
215                 if [ $retcode_i -eq 0 ]; then
216                         echo -e " Creating $KEYCLOAK_APP_NAME deployment and service"
217
218             __kube_create_namespace $KUBE_KEYCLOAK_NAMESPACE
219
220                         __keycloak_export_vars
221
222                         # Create service and app
223                         input_yaml=$SIM_GROUP"/"$KEYCLOAK_COMPOSE_DIR"/"svc_app.yaml
224                         output_yaml=$PWD/tmp/keycloak_svc_app.yaml
225                         __kube_create_instance "service/app" $KEYCLOAK_APP_NAME $input_yaml $output_yaml
226
227                 fi
228
229                 __check_service_start $KEYCLOAK_APP_NAME $KEYCLOAK_SERVICE_PATH$KEYCLOAK_ALIVE_URL
230         else
231
232                 # Check if docker app shall be fully managed by the test script
233                 __check_included_image 'KEYCLOAK'
234                 if [ $? -eq 1 ]; then
235                         echo -e $RED"The Keycloak app is not included as managed in this test script"$ERED
236                         echo -e $RED"The Keycloak will not be started"$ERED
237                         exit
238                 fi
239
240                 __keycloak_export_vars
241
242                 __start_container $KEYCLOAK_COMPOSE_DIR "" NODOCKERARGS 1 $KEYCLOAK_APP_NAME
243
244         __check_service_start $KEYCLOAK_APP_NAME $KEYCLOAK_SERVICE_PATH$KEYCLOAK_ALIVE_URL
245         fi
246     echo ""
247     return 0
248 }
249
250 # Excute a curl cmd towards the keycloak and check the response code is 2XX.
251 # args: <curl-cmd-string>
252 # resp: <returned-payload> if return code is 0 otherwise <error-info>
253 __execute_curl_to_keycloak() {
254
255         proxyflag=""
256         if [ ! -z "$KUBE_PROXY_PATH" ]; then
257                 if [ $KUBE_PROXY_HTTPX == "http" ]; then
258                         proxyflag=" --proxy $KUBE_PROXY_PATH"
259                 else
260                         proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
261                 fi
262         fi
263         __cmd="curl -skw %{http_code} $proxyflag $1"
264         echo " CMD: $__cmd" >> $HTTPLOG
265         res=$($__cmd)
266         echo " RESP: $res" >> $HTTPLOG
267         retcode=$?
268     if [ $retcode -ne 0 ]; then
269         __log_conf_fail_general " Fatal error when executing curl, response: "$retcode
270         echo "$res"
271                 return 1
272     fi
273     status=${res:${#res}-3}
274         if [ $status -lt 200 ] && [ $status -gt 299 ]; then
275                 __log_conf_fail_status_code "2XX" $status
276                 echo "$res"
277                 return 1
278         fi
279         echo ${res:0:${#res}-3}
280         return 0
281 }
282
283 # # Excute a curl cmd towards the keycloak and check the response code is 2XX.
284 # # args: <command-file>
285 # # resp: <returned-payload> if return code is 0 otherwise <error-info>
286 # __execute_curl_to_keycloak2() {
287
288 #     # TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
289 #     # echo "(${BASH_LINENO[0]}) - ${TIMESTAMP}: ${FUNCNAME[0]}" $@ >> $HTTPLOG
290 #       proxyflag=""
291 #       if [ ! -z "$KUBE_PROXY_PATH" ]; then
292 #               if [ $KUBE_PROXY_HTTPX == "http" ]; then
293 #                       proxyflag=" --proxy $KUBE_PROXY_PATH"
294 #               else
295 #                       proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
296 #               fi
297 #       fi
298 #       __cmd="curl -skw %{http_code} $proxyflag "$(< $1)
299 #       echo " CMD: $__cmd" >> $HTTPLOG
300 #       res=$(curl -skw %{http_code} $proxyflag $(< $1))
301 #       echo " RESP: $res" >> $HTTPLOG
302 #       retcode=$?
303 #     if [ $retcode -ne 0 ]; then
304 #         __log_conf_fail_general " Fatal error when executing curl, response: "$retcode
305 #         echo "$res"
306 #               return 1
307 #     fi
308 #     status=${res:${#res}-3}
309 #       if [ $status -lt 200 ] && [ $status -gt 299 ]; then
310 #               __log_conf_fail_status_code "2XX" $status
311 #               echo "$res"
312 #               return 1
313 #       fi
314 #       echo ${res:0:${#res}-3}
315 #       return 0
316 # }
317
318 # Excute a curl cmd towards the keycloak and check the response code is 2XX.
319 # args: <operation> <url> <token> <json>
320 # resp: <returned-payload> if return code is 0 otherwise <error-info>
321 __execute_curl_to_keycloak2() {
322         proxyflag=""
323         if [ ! -z "$KUBE_PROXY_PATH" ]; then
324                 if [ $KUBE_PROXY_HTTPX == "http" ]; then
325                         proxyflag=" --proxy $KUBE_PROXY_PATH"
326                 else
327                         proxyflag=" --proxy-insecure --proxy $KUBE_PROXY_PATH"
328                 fi
329         fi
330         if [ $1 == "POST" ]; then
331                 if [ $# -eq 3 ]; then
332                         echo  curl -X POST -skw %{http_code} $proxyflag "$2" -H "Authorization: Bearer $3" >> $HTTPLOG
333                         res=$(curl -X POST -skw %{http_code} $proxyflag "$2" -H "Authorization: Bearer $3")
334                         retcode=$?
335                 else
336                         echo  curl -X POST -skw %{http_code} $proxyflag "$2" -H "Content-Type: application/json" -H "Authorization: Bearer $3" --data-binary "$4" >> $HTTPLOG
337                         res=$(curl -X POST -skw %{http_code} $proxyflag "$2" -H "Content-Type: application/json" -H "Authorization: Bearer $3" --data-binary "$4")
338                         retcode=$?
339                 fi
340         elif [ $1 == "PUT" ]; then
341                 if [ $# -eq 3 ]; then
342                         echo  curl -X PUT -skw %{http_code} $proxyflag "$2" -H "Authorization: Bearer $3" >> $HTTPLOG
343                         res=$(curl -X PUT -skw %{http_code} $proxyflag "$2" -H "Authorization: Bearer $3")
344                         retcode=$?
345                 else
346                         echo  curl -X PUT -skw %{http_code} $proxyflag "$2" -H "Content-Type: application/json" -H "Authorization: Bearer $3" --data-binary "$4" >> $HTTPLOG
347                         res=$(curl -X PUT -skw %{http_code} $proxyflag "$2" -H "Content-Type: application/json" -H "Authorization: Bearer $3" --data-binary "$4")
348                         retcode=$?
349                 fi
350         elif [ $1 == "GET" ]; then
351                 echo  curl -X GET -skw %{http_code} $proxyflag "$2" -H "Authorization: Bearer $3" >> $HTTPLOG
352                 res=$(curl -X GET -skw %{http_code} $proxyflag "$2" -H "Authorization: Bearer $3")
353                 retcode=$?
354         fi
355         echo " RESP: $res" >> $HTTPLOG
356     if [ $retcode -ne 0 ]; then
357         __log_conf_fail_general " Fatal error when executing curl, response: "$retcode
358         echo "$res"
359                 return 1
360     fi
361     status=${res:${#res}-3}
362         if [ $status -lt 200 ] && [ $status -gt 299 ]; then
363                 __log_conf_fail_status_code "2XX" $status
364                 echo "$res"
365                 return 1
366         fi
367         echo ${res:0:${#res}-3}
368         return 0
369 }
370
371 # Extract JWT access token from json structure
372 # args: <json>
373 __keycloak_decode_jwt() {
374     echo $1 | jq -r .access_token | jq -R 'split(".") | .[1] | @base64d | fromjson'
375         return 0
376 }
377
378 # Get the admin token to use for subsequent rest calls to keycloak
379 # args: -
380 keycloak_api_obtain_admin_token() {
381         __log_conf_start $@
382         __curl_string="-X POST $KEYCLOAK_SERVICE_PATH$KEYCLOAK_ADMIN_URL_PREFIX/protocol/openid-connect/token     -H Content-Type:application/x-www-form-urlencoded     -d username="$KEYCLOAK_ADMIN_USER" -d password="$KEYCLOAK_ADMIN_PWD" -d grant_type=password -d client_id="$KEYCLOAK_ADMIN_CLIENT
383         __TMP_TOKEN=$(__execute_curl_to_keycloak "$__curl_string")
384         if [ $? -ne 0 ]; then
385         __log_conf_fail_general " Fatal error when executing curl, response: "$?
386         return 1
387         fi
388
389         __KEYCLOAK_ADMIN_TOKEN=$(echo "$__TMP_TOKEN" | jq  -r '.access_token')
390         if [ $? -ne 0 ]; then
391         __log_conf_fail_general " Fatal error when extracting token, response: "$?
392         return 1
393         fi
394
395         echo "Decoded token:" >> $HTTPLOG
396         __keycloak_decode_jwt "$__TMP_TOKEN" >> $HTTPLOG
397
398         __KEYCLOAK_ADMIN_TOKEN_EXP=$(echo "$__TMP_TOKEN" | jq  -r '.expires_in')
399         if [ $? -ne 0 ]; then
400         __log_conf_fail_general " Fatal error when extracting expiry time, response: "$?
401         return 1
402         fi
403         echo " Admin token obtained. Expires in $__KEYCLOAK_ADMIN_TOKEN_EXP seconds"
404
405         __log_conf_ok
406         return 0
407 }
408
409 # Create a realm, name, enabled, expiry-time
410 # args: <realm-name> true|false <token-expiry>
411 keycloak_api_create_realm() {
412         __log_conf_start $@
413         __json='{"realm":"'$1'","enabled":'$2',"accessTokenLifespan":'$3'}'
414         res=$(__execute_curl_to_keycloak2 POST "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX" "$__KEYCLOAK_ADMIN_TOKEN" "$__json")
415         if [ $? -ne 0 ]; then
416                 __log_conf_fail_general " Fatal error when creating realm, response: "$?
417                 return 1
418         fi
419         __log_conf_ok
420         return 0
421 }
422
423 # Update a realm, name, enabled, expiry-time
424 # args: <realm-name> true|false <token-expiry>
425 keycloak_api_update_realm() {
426         __log_conf_start $@
427         __json='{"realm":"'$1'","enabled":'$2',"accessTokenLifespan":'$3'}'
428         res=$(__execute_curl_to_keycloak2 PUT "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1" "$__KEYCLOAK_ADMIN_TOKEN" "$__json")
429         if [ $? -ne 0 ]; then
430                 __log_conf_fail_general " Fatal error when updating realm, response: "$?
431                 return 1
432         fi
433         __log_conf_ok
434         return 0
435 }
436
437 # Create a client
438 # args: <realm-name> <client-name>
439 keycloak_api_create_confidential_client() {
440         __log_conf_start $@
441         __json='{"clientId":"'$2'","publicClient":false,"serviceAccountsEnabled": true,"rootUrl":"https://example.com/example/","adminUrl":"https://example.com/example/"}'
442         res=$(__execute_curl_to_keycloak2 POST "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients" "$__KEYCLOAK_ADMIN_TOKEN" "$__json")
443         if [ $? -ne 0 ]; then
444                 __log_conf_fail_general " Fatal error when ucreating client, response: "$?
445                 return 1
446         fi
447         __log_conf_ok
448         return 0
449 }
450
451 __keycloak_api_get_client_id() {
452         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
453         echo "(${BASH_LINENO[0]}) - ${TIMESTAMP}: ${FUNCNAME[0]}" $@ >> $HTTPLOG
454
455         res=$(__execute_curl_to_keycloak2 GET "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients?clientId=$2" "$__KEYCLOAK_ADMIN_TOKEN")
456         if [ $? -ne 0 ]; then
457                 return 1
458         fi
459         echo $res | jq -r '.[0].id'
460         return 0
461 }
462
463 __keycloak_api_get_service_account_id() {
464         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
465         echo "(${BASH_LINENO[0]}) - ${TIMESTAMP}: ${FUNCNAME[0]}" $@ >> $HTTPLOG
466
467         res=$(__execute_curl_to_keycloak2 GET "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients$2/service-account-user" "$__KEYCLOAK_ADMIN_TOKEN")
468         if [ $? -ne 0 ]; then
469                 return 1
470         fi
471         echo $res | jq -r '.[0].id'
472         return 0
473 }
474
475 # Generate secret for client
476 # args: <realm-name> <client-name>
477 keycloak_api_generate_client_secret() {
478         __log_conf_start $@
479         __c_id=$(__keycloak_api_get_client_id $1 $2)
480         if [ $? -ne 0 ]; then
481                 __log_conf_fail_general " Fatal error when getting client id, response: "$?
482                 return 1
483         fi
484         res=$(__execute_curl_to_keycloak2 POST "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients/$__c_id/client-secret" "$__KEYCLOAK_ADMIN_TOKEN")
485         if [ $? -ne 0 ]; then
486                 __log_conf_fail_general " Fatal error when generating client secret, response: "$?
487                 return 1
488         fi
489         __c_sec=$(__execute_curl_to_keycloak2 GET "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients/$__c_id/client-secret" "$__KEYCLOAK_ADMIN_TOKEN")
490         if [ $? -ne 0 ]; then
491                 __log_conf_fail_general " Fatal error when getting client secret, response: "$?
492                 return 1
493         fi
494         __c_sec=$(echo $__c_sec | jq -r .value)
495         echo " Client id    : $__c_id"
496         echo " Client secret: $__c_sec"
497         __log_conf_ok
498         return 0
499 }
500
501 # Get secret for client
502 # args: <realm-name> <client-name>
503 keycloak_api_get_client_secret() {
504         __log_conf_start $@
505         __c_id=$(__keycloak_api_get_client_id $1 $2)
506         if [ $? -ne 0 ]; then
507                 __log_conf_fail_general " Fatal error when getting client id, response: "$?
508                 return 1
509         fi
510         __c_sec=$(__execute_curl_to_keycloak2 GET "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients/$__c_id/client-secret" "$__KEYCLOAK_ADMIN_TOKEN")
511         if [ $? -ne 0 ]; then
512                 __log_conf_fail_general " Fatal error when getting client secret, response: "$?
513                 return 1
514         fi
515         __c_sec=$(echo $__c_sec | jq -r .value)
516         echo " Client id    : $__c_id"
517         echo " Client secret: $__c_sec"
518         __log_conf_ok
519         return 0
520 }
521
522 # Create client roles
523 # args: <realm-name> <client-name> <role>+
524 keycloak_api_create_client_roles() {
525         __log_conf_start $@
526         __c_id=$(__keycloak_api_get_client_id $1 $2)
527         if [ $? -ne 0 ]; then
528                 __log_conf_fail_general " Fatal error when getting client id, response: "$?
529                 return 1
530         fi
531         __realm=$1
532         shift; shift;
533     while [ $# -gt 0 ]; do
534                 __json='{"name":"'$1'"}'
535                 res=$(__execute_curl_to_keycloak2 POST "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$__realm/clients/$__c_id/roles" "$__KEYCLOAK_ADMIN_TOKEN" "$__json")
536                 if [ $? -ne 0 ]; then
537                         __log_conf_fail_general " Fatal error when creating client role, response: "$?
538                         return 1
539                 fi
540                 shift
541         done
542         __log_conf_ok
543         return 0
544 }
545
546 # Get a client token
547 # args: <realm-name> <client-name>
548 keycloak_api_get_client_token() {
549         __log_conf_start $@
550         __c_id=$(__keycloak_api_get_client_id $1 $2)
551         if [ $? -ne 0 ]; then
552                 __log_conf_fail_general " Fatal error when getting client id, response: "$?
553                 return 1
554         fi
555         __c_sec=$(__execute_curl_to_keycloak2 GET "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients/$__c_id/client-secret" "$__KEYCLOAK_ADMIN_TOKEN")
556         if [ $? -ne 0 ]; then
557                 __log_conf_fail_general " Fatal error when getting client secret, response: "$?
558                 return 1
559         fi
560         __c_sec=$(echo $__c_sec | jq -r .value)
561         __curl_string="-X POST $KEYCLOAK_SERVICE_PATH$KEYCLOAK_TOKEN_URL_PREFIX/$1/protocol/openid-connect/token     -H Content-Type:application/x-www-form-urlencoded     -d client_id="$2" -d client_secret="$__c_sec" -d grant_type=client_credentials"
562         __TMP_TOKEN=$(__execute_curl_to_keycloak "$__curl_string")
563         if [ $? -ne 0 ]; then
564                 __log_conf_fail_general " Fatal error when getting client token, response: "$?
565                 return 1
566         fi
567         echo $__TMP_TOKEN| jq -r .access_token
568         __log_conf_ok
569         return 0
570 }
571
572 # Read a client token
573 # args: <realm-name> <client-name>
574 keycloak_api_read_client_token() {
575         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
576         echo "(${BASH_LINENO[0]}) - ${TIMESTAMP}: ${FUNCNAME[0]}" $@ >> $HTTPLOG
577         __c_id=$(__keycloak_api_get_client_id $1 $2)
578         if [ $? -ne 0 ]; then
579                 echo "<error-no-token>"
580                 return 1
581         fi
582         __c_sec=$(__execute_curl_to_keycloak2 GET "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients/$__c_id/client-secret" "$__KEYCLOAK_ADMIN_TOKEN")
583         if [ $? -ne 0 ]; then
584                 echo "<error-no-token>"
585                 return 1
586         fi
587         __c_sec=$(echo $__c_sec | jq -r .value)
588         __curl_string="-X POST $KEYCLOAK_SERVICE_PATH$KEYCLOAK_TOKEN_URL_PREFIX/$1/protocol/openid-connect/token     -H Content-Type:application/x-www-form-urlencoded     -d client_id="$2" -d client_secret="$__c_sec" -d grant_type=client_credentials"
589         __TMP_TOKEN=$(__execute_curl_to_keycloak "$__curl_string")
590         if [ $? -ne 0 ]; then
591                 echo "<error-no-token>"
592                 return 1
593         fi
594         echo $__TMP_TOKEN| jq -r .access_token
595         return 0
596 }
597
598 # Read secret for client
599 # args: <realm-name> <client-name>
600 keycloak_api_read_client_secret() {
601         TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
602         echo "(${BASH_LINENO[0]}) - ${TIMESTAMP}: ${FUNCNAME[0]}" $@ >> $HTTPLOG
603         __c_id=$(__keycloak_api_get_client_id $1 $2)
604         if [ $? -ne 0 ]; then
605                 echo "<error-no-secret>"
606                 return 1
607         fi
608         __c_sec=$(__execute_curl_to_keycloak2 GET "$KEYCLOAK_SERVICE_PATH$KEYCLOAK_REALM_URL_PREFIX/$1/clients/$__c_id/client-secret" "$__KEYCLOAK_ADMIN_TOKEN")
609         if [ $? -ne 0 ]; then
610                 echo "<error-no-secret>"
611                 return 1
612         fi
613         __c_sec=$(echo $__c_sec | jq -r .value)
614         echo $__c_sec
615         return 0
616 }