Repository navigation
Expand file tree
/
Copy pathJenkinsfile
More file actions
493 lines (421 loc) · 20.1 KB
/
Copy pathJenkinsfile
File metadata and controls
493 lines (421 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#!groovy
@Library([
'pipe-build-lib',
'ces-build-lib@5.5.0',
'dogu-build-lib'
]) _
import com.cloudogu.ces.cesbuildlib.K3d
import com.cloudogu.ces.cesbuildlib.Makefile
import com.cloudogu.ces.cesbuildlib.Maven
import com.cloudogu.ces.cesbuildlib.MavenInDocker
String clientSecret = ''
String keycloakCasClientSecret = ''
def pipe = new com.cloudogu.sos.pipebuildlib.DoguPipe(this, [
doguName : 'cas',
shellScripts : ['''
resources/startup.sh
resources/logging.sh
resources/create-sa.sh
resources/remove-sa.sh
resources/test-password-logging.sh
resources/pre-upgrade.sh
resources/post-upgrade.sh
resources/upgrade-notification.sh
resources/util.sh
'''
],
doBatsTests : true,
runIntegrationTests: true,
doSonarTests : true,
dependencies : ['nginx', 'cas'],
additionalDogus : ['official/postgresql', 'official/usermgt', 'official/ldap'],
defaultBranch : "master"
])
def componentRegistry = "registry.cloudogu.com"
def componentRegistryNamespace = "k8s"
def componentChartTargetDir = "target/k8s/helm"
def componentBuildImageRepository = "registry.cloudogu.com/official/cas"
def componentReleaseName = "cas"
def helmTestReleaseName = "lop-idp-${componentReleaseName}"
def goVersion = "1.26.0"
pipe.setBuildProperties()
pipe.addDefaultStages()
com.cloudogu.ces.dogubuildlib.EcoSystem ecoSystem = pipe.ecoSystem
def runMakeInGoContainer = { target ->
new com.cloudogu.ces.cesbuildlib.Docker(this)
.image("golang:${goVersion}")
.mountJenkinsUser()
.inside("--volume ${WORKSPACE}:/workdir -w /workdir") {
sh "make ${target}"
}
}
String getDoguVersion(boolean withVersionPrefix) {
def doguJson = this.readJSON file: 'dogu.json'
String version = doguJson.Version
if (withVersionPrefix) {
return "v" + version
} else {
return version
}
}
def componentStages = { group ->
group.stage('Component Checkout') {
checkout scm
}
group.stage('Component Build') {
runMakeInGoContainer("install-yq")
docker.withRegistry('https://registry.cloudogu.com/', 'cesmarvin-setup') {
sh "make docker-build"
}
}
group.stage('Component Lint') {
runMakeInGoContainer("helm-lint")
}
group.stage('Component Smoke Test (k3d)') {
K3d k3d = new K3d(this, "${WORKSPACE}", "${WORKSPACE}/k3d", env.PATH)
String imageTag = getDoguVersion(false)
try {
echo "[Component k3d] Start cluster"
k3d.startK3d()
k3d.yqEvalYamlFile("k3d_values.yaml", ".defaultConfig.env.enableFqdnApplier = true")
k3d.appendToYamlFile("k3d_values.yaml", ".components.k8s-exposition-crd.version", "1.0.0")
k3d.setup()
echo "[Component k3d] Prepare prerequisites"
k3d.kubectl("delete secret ldap-cas-sa || true")
// Steal username and password for ldap from cas dogu to use in component.
// Once we have completely transitioned to the lop-idp component in ecosystem-core,
// this will come from the ldap component and we don't need it anymore.
String casSecretRaw = k3d.kubectl("get secret cas-config -o jsonpath='{.data.config\\.yaml}'", true)
String casSecretYaml = new String(casSecretRaw.decodeBase64())
def ldapUsername = ""
def ldapPassword = ""
k3d.doInYQContainer {
ldapUsername = sh(
script: "echo '${casSecretYaml}' | yq '.sa-ldap.username'",
returnStdout: true
).trim()
ldapPassword = sh(
script: "echo '${casSecretYaml}' | yq '.sa-ldap.password'",
returnStdout: true
).trim()
echo "Read ldap secret from cas config..."
}
k3d.kubectl("create secret generic ldap-cas-sa --from-literal=username='${ldapUsername}' --from-literal=password='${ldapPassword}'")
echo "[Component k3d] Generate helm chart"
runMakeInGoContainer("helm-generate")
echo "[Component k3d] Push image to k3d registry"
k3d.registry.pushToLocalRegistry("${componentBuildImageRepository}:${imageTag}", "local-smoke/cas", imageTag)
echo "[Component k3d] Deploy component via helm"
k3d.helm("upgrade --install ${helmTestReleaseName} ${componentChartTargetDir}"
+ " --namespace default --set nameOverride=${helmTestReleaseName}"
+ " --set fullnameOverride=${helmTestReleaseName}"
+ " --set containers.cas.image.registry=${k3d.registry.imageRegistryInternalWithPort}"
+ " --set containers.cas.image.repository=local-smoke/cas"
+ " --set containers.cas.image.tag=${imageTag}"
// use ldap dogu instead of component service
+ " --set configuration.normal.ldap.host=ldap"
// disable ingress to avoid conflicts with the cas dogu
+ " --set ingress.enabled=false"
+ " --wait --timeout 5m")
echo "[Component k3d] Verify component startup"
k3d.kubectl("rollout status deployment/${helmTestReleaseName} --timeout=300s")
k3d.kubectl("wait --for=condition=ready pod -l app.kubernetes.io/instance=${helmTestReleaseName} --timeout=300s")
} catch (Exception e) {
k3d.collectAndArchiveLogs()
throw e as java.lang.Throwable
} finally {
k3d.deleteK3d()
}
}
if (pipe.gitflow.isReleaseBranch()) {
group.stage('Push Component Chart to Harbor') {
sh "make helm-package"
def componentChartFile = sh(returnStdout: true, script: "ls -1t ${componentChartTargetDir}/*.tgz 2>/dev/null | head -n 1").trim()
if (!componentChartFile) {
error("No packaged component chart found in ${componentChartTargetDir}")
}
withCredentials([usernamePassword(credentialsId: 'harborhelmchartpush', usernameVariable: 'HARBOR_USERNAME', passwordVariable: 'HARBOR_PASSWORD')]) {
sh ".bin/helm registry login ${componentRegistry} --username '${HARBOR_USERNAME}' --password '${HARBOR_PASSWORD}'"
sh ".bin/helm push ${componentChartFile} oci://${componentRegistry}/${componentRegistryNamespace}/"
sh ".bin/helm registry logout ${componentRegistry}"
}
}
}
}
pipe.addStageGroup('component', pipe.agentMultinode, componentStages)
def casSecretOverride = { String casClientSecret ->
return """
{
"oidc": {
"client_secret": "${casClientSecret}"
}
}
"""
}
def casConfigOverride = { String keycloakUrl ->
return """
{
"forgot_password_text": "Contact your admin",
"legal_urls": {
"privacy_policy": "https://www.triology.de/",
"terms_of_service": "https://docs.cloudogu.com/",
"imprint": "https://cloudogu.com/"
},
"oidc": {
"enabled": "true",
"discovery_uri": "http://${keycloakUrl}/auth/realms/Test/.well-known/openid-configuration",
"client_id": "cas",
"display_name": "cas",
"optional": "true",
"scopes": "openid email profile groups",
"allowed_groups": "testers",
"attribute_mapping": "email:mail,family_name:surname,given_name:givenName,preferred_username:username,name:displayName,groups:externalGroups"
}
}
"""
}
String globalConfigOverride = """
{
"password-policy": {
"must_contain_capital_letter": "true",
"must_contain_lower_case_letter": "true",
"must_contain_digit": "true",
"must_contain_special_character": "true",
"min_length": "14"
}
}
"""
def mergeConfigMapYaml = { String configMapName, String overrideConfig ->
sh """
kubectl get configmap ${configMapName} -n ecosystem -o yaml | .bin/yq '
.data."config.yaml" |= (
(from_yaml) * ${overrideConfig}
| to_yaml
)
' | tee ${configMapName}-output.yml | kubectl apply -f -
"""
}
def mergeSecretYaml = { String secretName, String overrideConfig ->
sh """
kubectl get secret ${secretName} -n ecosystem -o yaml | .bin/yq '
.data."config.yaml" |= (
(. | @base64d | from_yaml) * ${overrideConfig}
| to_yaml
| @base64
)
' | tee ${secretName}-output.yml | kubectl apply -f -
"""
}
pipe.insertStageAfter('Bats Tests', 'Gradle Build & Test') {
String gradleDockerImage = 'eclipse-temurin:25-jdk-alpine'
com.cloudogu.ces.cesbuildlib.Gradle gradlew = new com.cloudogu.ces.cesbuildlib.GradleWrapperInDocker(this, gradleDockerImage)
dir('app') {
gradlew "clean build"
gradlew 'test'
junit allowEmptyResults: true, testResults: '**/build/test-results/test/TEST-*.xml'
}
}
pipe.insertStageBefore('Setup', 'Start OIDC-Provider') {
// launching and setting up keycloak, adding test user, group, scope mapping etc
ecoSystem.vagrant.sshOut """
cd /dogu/integrationTests/keycloak/ && \
./kc-down.sh && \
./kc-up.sh -H ${ecoSystem.externalIP} && \
./kc-setup.sh -H ${ecoSystem.externalIP} && \
./kc-add-user.sh && \
./kc-group.sh
"""
// retrieve secret from setup
clientSecret = ecoSystem.vagrant.sshOut """
cd /dogu/integrationTests/keycloak/
cat kc_out.env | \
grep CLIENT_SECRET= kc_out.env | cut -d'=' -f2-
"""
echo "clientSecret length: ${clientSecret.size()}"
}
pipe.overrideStage('Setup') {
ecoSystem.loginBackend('cesmarvin-setup')
String casConfig = casConfigOverride(ecoSystem.externalIP + ":9000")
String casSecret = casSecretOverride(clientSecret)
ecoSystem.setup([registryConfig: """
"cas": ${casConfig},
"_global": ${globalConfigOverride}
""", registryConfigEncrypted: """
"cas": ${casSecret}
"""])
}
pipe.insertStageBefore('MN-Run Integration Tests', 'Setup Configs and Keycloak') {
echo "Setup Keycloak as OIDC provider for integration tests"
def currentContext = sh(returnStdout: true, script: "kubectl config current-context").trim()
def namespace = "ecosystem"
def random_suffix = sh(returnStdout: true, script: "head /dev/urandom | tr -dc a-z0-9 | head -c 8").trim()
def dirName = "keycloak-repo-${random_suffix}"
withCredentials([usernamePassword(credentialsId: 'SCM-Manager', usernameVariable: 'AUTH_USR', passwordVariable: 'AUTH_PS')]) {
sh(
script: "git clone https://\"${AUTH_USR}\":\"${AUTH_PS}\"@ecosystem.cloudogu.com/scm/repo/platform/account.cloudogu.com ${dirName}",
returnStdout: true
)
}
dir(dirName) {
Maven mvn = new MavenInDocker(this, "3.9.9-eclipse-temurin-17")
mvn.enableDockerHost = true
mvn "clean verify -Dmaven.test.skip=true -Ddocker.imageName=account.cloudogu.com/cloudogu-keycloak io.fabric8:docker-maven-plugin:build"
sh "docker tag account.cloudogu.com/cloudogu-keycloak:latest registry.cloudogu.com/ci/account.cloudogu.com:1.0.0"
sh "docker push registry.cloudogu.com/ci/account.cloudogu.com:1.0.0"
sh("""
sudo apt-get install curl gpg apt-transport-https --yes
curl -fsSL https://packages.buildkite.com/helm-linux/helm-debian/gpgkey | gpg --dearmor | sudo tee /usr/share/keyrings/helm.gpg > /dev/null
echo "deb [signed-by=/usr/share/keyrings/helm.gpg] https://packages.buildkite.com/helm-linux/helm-debian/any/ any main" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list
sudo apt-get update
sudo apt-get install helm""")
sh 'helm repo add bitnami https://charts.bitnami.com/bitnami'
sh 'helm repo update'
def HELM_CMD = "install"
def deploymentExists = sh(returnStatus: true, script: "helm --kube-context=${currentContext} --namespace=${namespace} list -q | grep -q '^keycloak\$'")
if (deploymentExists == 0) {
HELM_CMD = "upgrade"
}
pipe.multiNodeEcoSystem.waitForDogu("postgresql")
def postgreSqlPodName = sh(returnStdout: true, script: """kubectl get pod -l dogu.name=postgresql --namespace=ecosystem -o jsonpath='{.items[0].metadata.name}'""")
def postgresqlCreds = sh(returnStdout: true, script: "kubectl --namespace=ecosystem exec ${postgreSqlPodName} -- /create-sa.sh keycloak")
def postgreSqlCredentialLines = postgresqlCreds.trim().split("\n")
def postgresqlDatabase = postgreSqlCredentialLines.find { it.startsWith("database:") }?.split(":", 2)[1]?.trim()
def postgresqlUsername = postgreSqlCredentialLines.find { it.startsWith("username:") }?.split(":", 2)[1]?.trim()
def postgresqlPassword = postgreSqlCredentialLines.find { it.startsWith("password:") }?.split(":", 2)[1]?.trim()
sh """
helm --kube-context=${currentContext} --namespace=${namespace} ${HELM_CMD} keycloak --version 24.2.0 bitnami/keycloak \
-f ./k8s/values-shared.yaml \
-f ../integrationTests/k8s/keycloak-values.yaml \
--set "image.pullSecrets={'ces-container-registries'}" \
--set externalDatabase.user=${postgresqlUsername} \
--set externalDatabase.database=${postgresqlDatabase} \
--set externalDatabase.password=${postgresqlPassword} \
--set KC_HOSTNAME=${pipe.multiNodeEcoSystem.externalIP}
"""
}
// Wait for Keycloak pod to exist and be ready. Sometimes the pod is not created yet, so poll for it.
echo "Waiting for Keycloak pod to appear..."
def keycloakExists = sh(
script: """
kubectl get pods -n ecosystem --no-headers | grep -q '^keycloak'
""",
returnStatus: true
) == 0
int keycloakWaitAttempts = 0
int keycloakMaxAttempts = 30
while (!keycloakExists) {
echo "Keycloak pod not found yet (attempt ${keycloakWaitAttempts + 1}/${keycloakMaxAttempts}). Waiting 10s..."
sleep time: 10, unit: 'SECONDS'
keycloakExists = sh(
script: """
kubectl get pods -n ecosystem --no-headers | grep -q '^keycloak'
""",
returnStatus: true
) == 0
keycloakWaitAttempts++
if (keycloakWaitAttempts >= keycloakMaxAttempts) {
error("Timed out waiting for Keycloak pod to appear in namespace 'ecosystem'.")
}
}
//setup keycloak-postgresql network policy
sh """
kubectl apply -f integrationTests/k8s/keycloak-postgresql-network-policy.yaml -n ${namespace}
"""
echo "Waiting for Keycloak pod to be ready..."
sh "kubectl -n ecosystem wait --for=condition=ready pod -l app.kubernetes.io/name=keycloak --timeout=300s"
//setup keycloak ingress
sh """
kubectl apply -f integrationTests/k8s/keycloak-ingress.yaml -n ${namespace}
"""
// Set up the Test realm/client inside the pod and copy the generated secret to kc_out.env.
sh("""
CLIENT_REDIRECT=https://${pipe.multiNodeEcoSystem.externalIP}/cas/* \
bash ./integrationTests/keycloak/k8s/kc-setup-k8s.sh \
""")
// Ensure the OIDC test user exists in Keycloak before running integration tests.
sh("""
KC_NAMESPACE=${namespace} \
REALM=Test \
GROUP=testers \
USERNAME=tester \
EMAIL=tester@example.com \
PASSWORD=test \
bash ./integrationTests/keycloak/k8s/kc-add-user-k8s.sh
""")
// Configure Keycloak client-scope and group mapper for OIDC group claims.
sh("""
KC_NAMESPACE=${namespace} \
REALM=Test \
CLIENT_ID_STR=cas \
SCOPE_NAME=groups \
CLAIM_NAME=groups \
bash ./integrationTests/keycloak/k8s/kc-group-k8s.sh
""")
keycloakCasClientSecret = sh(returnStdout: true, script: """
grep '^CLIENT_SECRET=' kc_out.env | cut -d'=' -f2-
""").trim()
if (!keycloakCasClientSecret) {
error("Failed to read client secret from the Test realm")
}
echo "Retrieved Test realm client secret length: ${keycloakCasClientSecret.size()}"
// Verify that the ingress routes to Keycloak by polling the OIDC discovery endpoint
echo "Checking Keycloak ingress routing via external IP ${pipe.multiNodeEcoSystem.externalIP}..."
def discoveryUrl = "http://${pipe.multiNodeEcoSystem.externalIP}/auth/realms/Test/.well-known/openid-configuration"
int ingressAttempts = 0
int ingressMaxAttempts = 30
def httpCode = ''
while (ingressAttempts < ingressMaxAttempts) {
httpCode = sh(returnStdout: true, script: "curl -s -o /dev/null -w \"%{http_code}\" --max-time 5 ${discoveryUrl} || true").trim()
if (httpCode == '200') {
echo "Keycloak ingress is reachable (HTTP ${httpCode})."
break
}
echo "Keycloak ingress not reachable yet (status=${httpCode}). Waiting 10s (attempt ${ingressAttempts + 1}/${ingressMaxAttempts})..."
sleep time: 10, unit: 'SECONDS'
ingressAttempts++
}
if (httpCode != '200') {
error("Timed out waiting for Keycloak ingress to route to Keycloak (last HTTP status: ${httpCode})")
}
def casPodname = sh(returnStdout: true, script: """kubectl get pod -l dogu.name=cas --namespace=ecosystem -o jsonpath='{.items[0].metadata.name}'""").trim()
String casConfig = casConfigOverride(pipe.multiNodeEcoSystem.externalIP)
String casSecretConfig = casSecretOverride(keycloakCasClientSecret)
sh "kubectl --namespace=ecosystem cp ./integrationTests/services/ $casPodname:/etc/cas/services/production/ "
pipe.multiNodeEcoSystem.waitForDogu("cas")
sh "make install-yq"
mergeConfigMapYaml('cas-config', casConfig)
mergeSecretYaml('cas-config', casSecretConfig)
pipe.multiNodeEcoSystem.waitForDogu("cas")
mergeConfigMapYaml('global-config', globalConfigOverride)
// This may be extracted to a dogu build lib function
def globalConfigLastUpdateTime = sh(returnStdout: true, script: """kubectl get configmap -n ecosystem --show-managed-fields global-config -o json | jq -r '.metadata.managedFields[].time' | sort | tail -1""").trim()
def casDoguStartedAt = sh(returnStdout: true, script: """kubectl get dogu -n ecosystem cas -o json | jq -r '.status.startedAt'""").trim()
while (casDoguStartedAt < globalConfigLastUpdateTime) {
echo "${casDoguStartedAt} is not after ${globalConfigLastUpdateTime} yet."
echo "Waiting for CAS to restart and pick up the new global config..."
sleep time: 10, unit: 'SECONDS'
casDoguStartedAt = sh(returnStdout: true, script: """kubectl get dogu -n ecosystem cas -o json | jq -r '.status.startedAt'""").trim()
}
pipe.multiNodeEcoSystem.waitForDogu("cas")
}
pipe.overrideStage('Integration Tests') {
echo "Create custom dogu to access OAuth endpoints for the integration tests"
ecoSystem.vagrant.ssh "sudo docker cp /dogu/integrationTests/services/ cas:/etc/cas/services/production/"
ecoSystem.vagrant.sshOut "sudo docker exec cas ls /etc/cas/services/production"
// Wait for Service-Watch start delay (see: cas.service-registry.schedule.start-delay)
sleep time: 30, unit: 'SECONDS'
ecoSystem.runCypressIntegrationTests([
// Default cypress/included:13.17.0 bundles Node 22.13, too old for
// cosmiconfig@10 (pulled in by @badeball/cypress-cucumber-preprocessor@28,
// required for cypress@16 compatibility). Override to an image with a
// newer bundled Node until the shared pipeline lib's own default catches up.
cypressImage : "cypress/included:16.2.0",
enableVideo : params.EnableVideoRecording,
enableScreenshots: params.EnableScreenshotRecording])
// run special non-encrypted password test
echo "Run unencrypted password test script"
ecoSystem.vagrant.sshOut 'chmod +x /dogu/resources/test-password-logging.sh'
def testreport = ecoSystem.vagrant.sshOut "sudo /dogu/resources/test-password-logging.sh ${ecoSystem.externalIP}"
echo "${testreport}"
}
pipe.run()