blob: 768c7844a8b37e8cd781863d86ceda7a7c74629e [file] [log] [blame]
Nico Huber7f8dc5b2023-07-25 16:48:01 +00001#!/bin/sh
2
3set -eu
4
5kca() {
6 /opt/keycloak/bin/kcadm.sh "$@"
7}
8
9kca_cred() {
10 kca config credentials \
11 --server http://keycloak:8080 \
12 --realm master \
13 --user ${KEYCLOAK_ADMIN} \
14 --password ${KEYCLOAK_ADMIN_PASSWORD}
15}
16
17secret() {
18 seed=$(cat /run/secrets/seed)
19 printf "%s:%40s" "${seed}" "$*" | sha256sum | sed 's/[[:space:]].*//'
20}
21
22i=15
23sleep ${i} # give it a moment to come up
24while kca_cred 2>&1 | grep -q 'Connection refused\|Bad Gateway'; do
25 if [ ${i} -eq 60 ]; then
26 echo "ERROR: Couldn't login to Keycloak after ${i}s."
27 exit 1
28 fi
29 echo Waiting...
30 sleep 1
31 i=$((i+1))
32done
33if ! kca_cred; then
34 echo "ERROR: Failed to login to Keycloak."
35 exit 2
36fi
37
38REALM=${SA_REALM:-sourcearcade}
39if kca get realms/${REALM} --fields id >/dev/null 2>&1; then
40 echo Realm ${REALM} already set up.
41else
42 kca create realms -f - <<EOF
43 {
44 "realm" : "${REALM}",
45 "enabled" : true,
46 "sslRequired" : "all",
47 "registrationAllowed" : true,
48 "resetPasswordAllowed" : true,
49 "rememberMe" : true,
50 "verifyEmail" : true,
51 "smtpServer" : {
52 "host" : "mail.${SA_PUBLIC_DOMAIN_NAME}",
53 "port" : "465",
54 "auth" : true,
55 "ssl" : true,
56 "user" : "keycloak@${SA_PUBLIC_DOMAIN_NAME}",
57 "password" : "$(secret mail:keycloak)",
58 "from" : "keycloak@${SA_PUBLIC_DOMAIN_NAME}",
59 "fromDisplayName" : "SourceArcade"
60 },
61 "identityProviders" : [ {
62 "alias" : "github",
63 "providerId" : "github",
64 "enabled" : true,
65 "config" : {
66 "clientId" : "${GITHUB_OAUTH_CLIENT_ID}",
67 "clientSecret" : "${GITHUB_OAUTH_CLIENT_SECRET}"
68 }
69 } ]
70 }
71EOF
72
73 ac_id=$(kca get clients -r ${REALM} -q clientId=account-console --fields id \
74 | sed -n 's/.*"id" : "\(.*\)".*/\1/p')
75 kca update clients/${ac_id} -r ${REALM} -s webOrigins='[ "+" ]'
76
77 echo New realm ${REALM} set up.
78fi
79
80if kca get clients -r ${REALM} -q clientId=gerrit --fields clientId | grep -q gerrit; then
81 echo Gerrit client in realm ${REALM} already set up.
82else
83 kca create clients -r ${REALM} -f - <<EOF
84 {
85 "clientId" : "gerrit",
86 "name" : "Gerrit",
87 "enabled" : true,
88 "description" : "SourceArcade review platform",
89 "rootUrl" : "https://review.${SA_PUBLIC_DOMAIN_NAME}",
90 "clientAuthenticatorType" : "client-secret",
91 "secret" : "$(secret kc:gerrit)",
92 "protocol" : "openid-connect",
93 "directAccessGrantsEnabled" : false
94 }
95EOF
96 echo Gerrit client in realm ${REALM} set up.
97fi