forked from keycloak/keycloak
-
Notifications
You must be signed in to change notification settings - Fork 1
/
KeycloakProcessor.java
807 lines (681 loc) · 39.4 KB
/
KeycloakProcessor.java
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.quarkus.deployment;
import static org.keycloak.quarkus.runtime.KeycloakRecorder.DEFAULT_HEALTH_ENDPOINT;
import static org.keycloak.quarkus.runtime.KeycloakRecorder.DEFAULT_METRICS_ENDPOINT;
import static org.keycloak.quarkus.runtime.Providers.getProviderManager;
import static org.keycloak.quarkus.runtime.configuration.Configuration.getConfig;
import static org.keycloak.quarkus.runtime.configuration.Configuration.getPropertyNames;
import static org.keycloak.quarkus.runtime.configuration.MicroProfileConfigProvider.NS_QUARKUS;
import static org.keycloak.quarkus.runtime.configuration.QuarkusPropertiesConfigSource.QUARKUS_PROPERTY_ENABLED;
import static org.keycloak.quarkus.runtime.storage.legacy.database.LegacyJpaConnectionProviderFactory.QUERY_PROPERTY_PREFIX;
import static org.keycloak.connections.jpa.util.JpaUtils.loadSpecificNamedQueries;
import static org.keycloak.representations.provider.ScriptProviderDescriptor.AUTHENTICATORS;
import static org.keycloak.representations.provider.ScriptProviderDescriptor.MAPPERS;
import static org.keycloak.representations.provider.ScriptProviderDescriptor.POLICIES;
import static org.keycloak.quarkus.runtime.Environment.getProviderFiles;
import static org.keycloak.theme.ClasspathThemeProviderFactory.KEYCLOAK_THEMES_JSON;
import static org.keycloak.representations.provider.ScriptProviderDescriptor.SAML_MAPPERS;
import javax.persistence.Entity;
import javax.persistence.spi.PersistenceUnitTransactionType;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import io.quarkus.agroal.spi.JdbcDataSourceBuildItem;
import io.quarkus.arc.deployment.BuildTimeConditionBuildItem;
import io.quarkus.datasource.deployment.spi.DevServicesDatasourceResultBuildItem;
import io.quarkus.deployment.IsDevelopment;
import io.quarkus.deployment.annotations.Consume;
import io.quarkus.deployment.builditem.BootstrapConfigSetupCompleteBuildItem;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.ExecutorBuildItem;
import io.quarkus.deployment.builditem.GeneratedResourceBuildItem;
import io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem;
import io.quarkus.deployment.builditem.IndexDependencyBuildItem;
import io.quarkus.deployment.builditem.StaticInitConfigSourceProviderBuildItem;
import io.quarkus.hibernate.orm.deployment.AdditionalJpaModelBuildItem;
import io.quarkus.hibernate.orm.deployment.HibernateOrmConfig;
import io.quarkus.hibernate.orm.deployment.PersistenceXmlDescriptorBuildItem;
import io.quarkus.hibernate.orm.deployment.integration.HibernateOrmIntegrationRuntimeConfiguredBuildItem;
import io.quarkus.resteasy.server.common.deployment.ResteasyDeploymentCustomizerBuildItem;
import io.quarkus.runtime.configuration.ProfileManager;
import io.quarkus.vertx.http.deployment.RouteBuildItem;
import io.quarkus.vertx.http.runtime.HttpBuildTimeConfig;
import io.smallrye.config.ConfigValue;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
import org.hibernate.jpa.boot.internal.PersistenceXmlParser;
import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.logging.Logger;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.resteasy.spi.ResteasyDeployment;
import org.keycloak.Config;
import org.keycloak.common.crypto.FipsMode;
import org.keycloak.config.SecurityOptions;
import org.keycloak.config.StorageOptions;
import org.keycloak.config.TransactionOptions;
import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.connections.jpa.JpaConnectionSpi;
import org.keycloak.models.map.storage.jpa.JpaMapStorageProviderFactory;
import org.keycloak.protocol.saml.mappers.DeployedScriptSAMLProtocolMapper;
import org.keycloak.quarkus.runtime.QuarkusProfile;
import org.keycloak.quarkus.runtime.configuration.PersistedConfigSource;
import org.keycloak.quarkus.runtime.configuration.QuarkusPropertiesConfigSource;
import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMapper;
import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers;
import org.keycloak.quarkus.runtime.integration.jaxrs.QuarkusKeycloakApplication;
import org.keycloak.authentication.AuthenticatorSpi;
import org.keycloak.authentication.authenticators.browser.DeployedScriptAuthenticatorFactory;
import org.keycloak.authorization.policy.provider.PolicySpi;
import org.keycloak.authorization.policy.provider.js.DeployedScriptPolicyFactory;
import org.keycloak.common.Profile;
import org.keycloak.common.util.StreamUtil;
import org.keycloak.quarkus.runtime.configuration.Configuration;
import org.keycloak.quarkus.runtime.configuration.KeycloakConfigSourceProvider;
import org.keycloak.quarkus.runtime.configuration.MicroProfileConfigProvider;
import org.keycloak.connections.jpa.DefaultJpaConnectionProviderFactory;
import org.keycloak.connections.jpa.updater.liquibase.LiquibaseJpaUpdaterProviderFactory;
import org.keycloak.connections.jpa.updater.liquibase.conn.DefaultLiquibaseConnectionProvider;
import org.keycloak.policy.BlacklistPasswordPolicyProviderFactory;
import org.keycloak.protocol.ProtocolMapperSpi;
import org.keycloak.protocol.oidc.mappers.DeployedScriptOIDCProtocolMapper;
import org.keycloak.provider.EnvironmentDependentProviderFactory;
import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.provider.ProviderManager;
import org.keycloak.provider.Spi;
import org.keycloak.quarkus.runtime.KeycloakRecorder;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.vertx.http.deployment.FilterBuildItem;
import org.keycloak.quarkus.runtime.services.health.KeycloakReadyHealthCheck;
import org.keycloak.quarkus.runtime.storage.database.jpa.NamedJpaConnectionProviderFactory;
import org.keycloak.quarkus.runtime.themes.FlatClasspathThemeResourceProviderFactory;
import org.keycloak.representations.provider.ScriptProviderDescriptor;
import org.keycloak.representations.provider.ScriptProviderMetadata;
import org.keycloak.quarkus.runtime.integration.web.NotFoundHandler;
import org.keycloak.services.ServicesLogger;
import org.keycloak.theme.ClasspathThemeProviderFactory;
import org.keycloak.theme.ClasspathThemeResourceProviderFactory;
import org.keycloak.theme.FolderThemeProviderFactory;
import org.keycloak.theme.JarThemeProviderFactory;
import org.keycloak.theme.ThemeResourceSpi;
import org.keycloak.transaction.JBossJtaTransactionManagerLookup;
import org.keycloak.quarkus.runtime.Environment;
import org.keycloak.url.DefaultHostnameProviderFactory;
import org.keycloak.url.FixedHostnameProviderFactory;
import org.keycloak.url.RequestHostnameProviderFactory;
import org.keycloak.util.JsonSerialization;
import org.keycloak.vault.FilesPlainTextVaultProviderFactory;
class KeycloakProcessor {
private static final Logger logger = Logger.getLogger(KeycloakProcessor.class);
private static final String JAR_FILE_SEPARATOR = "!/";
private static final Map<String, Function<ScriptProviderMetadata, ProviderFactory>> DEPLOYEABLE_SCRIPT_PROVIDERS = new HashMap<>();
private static final String KEYCLOAK_SCRIPTS_JSON_PATH = "META-INF/keycloak-scripts.json";
private static final List<Class<? extends ProviderFactory>> IGNORED_PROVIDER_FACTORY = Arrays.asList(
JBossJtaTransactionManagerLookup.class,
DefaultJpaConnectionProviderFactory.class,
DefaultLiquibaseConnectionProvider.class,
FolderThemeProviderFactory.class,
LiquibaseJpaUpdaterProviderFactory.class,
DefaultHostnameProviderFactory.class,
FixedHostnameProviderFactory.class,
RequestHostnameProviderFactory.class,
FilesPlainTextVaultProviderFactory.class,
BlacklistPasswordPolicyProviderFactory.class,
ClasspathThemeResourceProviderFactory.class,
JarThemeProviderFactory.class,
JpaMapStorageProviderFactory.class);
static {
DEPLOYEABLE_SCRIPT_PROVIDERS.put(AUTHENTICATORS, KeycloakProcessor::registerScriptAuthenticator);
DEPLOYEABLE_SCRIPT_PROVIDERS.put(POLICIES, KeycloakProcessor::registerScriptPolicy);
DEPLOYEABLE_SCRIPT_PROVIDERS.put(MAPPERS, KeycloakProcessor::registerScriptMapper);
DEPLOYEABLE_SCRIPT_PROVIDERS.put(SAML_MAPPERS, KeycloakProcessor::registerSAMLScriptMapper);
}
private static ProviderFactory registerScriptAuthenticator(ScriptProviderMetadata metadata) {
return new DeployedScriptAuthenticatorFactory(metadata);
}
private static ProviderFactory registerScriptPolicy(ScriptProviderMetadata metadata) {
return new DeployedScriptPolicyFactory(metadata);
}
private static ProviderFactory registerScriptMapper(ScriptProviderMetadata metadata) {
return new DeployedScriptOIDCProtocolMapper(metadata);
}
private static ProviderFactory registerSAMLScriptMapper(ScriptProviderMetadata metadata) {
return new DeployedScriptSAMLProtocolMapper(metadata);
}
@BuildStep
FeatureBuildItem getFeature() {
return new FeatureBuildItem("keycloak");
}
/**
* <p>Configures the persistence unit for Quarkus.
*
* <p>The main reason we have this build step is because we re-use the same persistence unit from {@code keycloak-model-jpa}
* module, the same used by the Wildfly distribution. The {@code hibernate-orm} extension expects that the dialect is statically
* set to the persistence unit if there is any from the classpath and we use this method to obtain the dialect from the configuration
* file so that we can build the application with whatever dialect we want. In addition to the dialect, we should also be
* allowed to set any additional defaults that we think that makes sense.
*
* @param config
* @param descriptors
*/
@BuildStep(onlyIf = {IsJpaStoreEnabled.class})
@Record(ExecutionTime.RUNTIME_INIT)
void configurePersistenceUnits(HibernateOrmConfig config,
List<PersistenceXmlDescriptorBuildItem> descriptors,
List<JdbcDataSourceBuildItem> jdbcDataSources,
BuildProducer<AdditionalJpaModelBuildItem> additionalJpaModel,
CombinedIndexBuildItem indexBuildItem,
BuildProducer<HibernateOrmIntegrationRuntimeConfiguredBuildItem> runtimeConfigured,
KeycloakRecorder recorder) {
ParsedPersistenceXmlDescriptor defaultUnitDescriptor = null;
List<String> userManagedEntities = new ArrayList<>();
for (PersistenceXmlDescriptorBuildItem item : descriptors) {
ParsedPersistenceXmlDescriptor descriptor = item.getDescriptor();
if ("keycloak-default".equals(descriptor.getName())) {
defaultUnitDescriptor = descriptor;
configureDefaultPersistenceUnitProperties(defaultUnitDescriptor, config, jdbcDataSources);
runtimeConfigured.produce(new HibernateOrmIntegrationRuntimeConfiguredBuildItem("keycloak", defaultUnitDescriptor.getName())
.setInitListener(recorder.createDefaultUnitListener()));
} else {
Properties properties = descriptor.getProperties();
// register a listener for customizing the unit configuration at runtime
runtimeConfigured.produce(new HibernateOrmIntegrationRuntimeConfiguredBuildItem("keycloak", descriptor.getName())
.setInitListener(recorder.createUserDefinedUnitListener(properties.getProperty(AvailableSettings.DATASOURCE))));
userManagedEntities.addAll(descriptor.getManagedClassNames());
}
}
if (defaultUnitDescriptor == null) {
throw new RuntimeException("No default persistence unit found.");
}
configureDefaultPersistenceUnitEntities(defaultUnitDescriptor, indexBuildItem, userManagedEntities);
}
@BuildStep(onlyIf = IsJpaStoreEnabled.class)
void produceDefaultPersistenceUnit(BuildProducer<PersistenceXmlDescriptorBuildItem> producer) {
String storage = Configuration.getRawValue(
MicroProfileConfigProvider.NS_KEYCLOAK_PREFIX.concat(StorageOptions.STORAGE.getKey()));
ParsedPersistenceXmlDescriptor descriptor;
if (storage == null) {
descriptor = PersistenceXmlParser.locateIndividualPersistenceUnit(
Thread.currentThread().getContextClassLoader().getResource("default-persistence.xml"));
} else {
descriptor = PersistenceXmlParser.locateIndividualPersistenceUnit(
Thread.currentThread().getContextClassLoader().getResource("default-map-jpa-persistence.xml"));
}
producer.produce(new PersistenceXmlDescriptorBuildItem(descriptor));
}
private void configureDefaultPersistenceUnitProperties(ParsedPersistenceXmlDescriptor descriptor, HibernateOrmConfig config,
List<JdbcDataSourceBuildItem> jdbcDataSources) {
Properties unitProperties = descriptor.getProperties();
unitProperties.setProperty(AvailableSettings.DIALECT, config.defaultPersistenceUnit.dialect.dialect.orElse(null));
if (Objects.equals(getConfig().getConfigValue("kc.transaction-jta-enabled").getValue(), "disabled")) {
unitProperties.setProperty(AvailableSettings.JPA_TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
// Only changing this for the new map storage to keep the legacy JPA store untouched as it wasn't tested for the legacy store.
// follow-up on this in https://github.com/keycloak/keycloak/issues/13222 to re-visit the auto-commit handling
String storage = Configuration.getRawValue(
MicroProfileConfigProvider.NS_KEYCLOAK_PREFIX.concat(StorageOptions.STORAGE.getKey()));
if (storage != null) {
// Needed to change the connection handling to avoid Hibernate returning the connection too early,
// which then interfered with the auto-commit reset that's done at the end of the transaction and PgConnection throwing a "Cannot commit when autoCommit is enabled."
// The current default is DELAYED_ACQUISITION_AND_RELEASE_BEFORE_TRANSACTION_COMPLETION which would only make sense for JTA IMHO.
// https://github.com/quarkusio/quarkus/blob/8d89101ffa65465b33d06360047095046bb726e4/extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/boot/FastBootMetadataBuilder.java#L287-L288
unitProperties.setProperty(AvailableSettings.CONNECTION_HANDLING, PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION.name());
}
} else {
// will happen for both "enabled" and "xa"
unitProperties.setProperty(AvailableSettings.JPA_TRANSACTION_TYPE, PersistenceUnitTransactionType.JTA.name());
}
unitProperties.setProperty(AvailableSettings.QUERY_STARTUP_CHECKING, Boolean.FALSE.toString());
String dbKind = jdbcDataSources.get(0).getDbKind();
for (Entry<Object, Object> query : loadSpecificNamedQueries(dbKind.toLowerCase()).entrySet()) {
unitProperties.setProperty(QUERY_PROPERTY_PREFIX + query.getKey(), query.getValue().toString());
}
}
private void configureDefaultPersistenceUnitEntities(ParsedPersistenceXmlDescriptor descriptor, CombinedIndexBuildItem indexBuildItem,
List<String> userManagedEntities) {
IndexView index = indexBuildItem.getIndex();
Collection<AnnotationInstance> annotations = index.getAnnotations(DotName.createSimple(Entity.class.getName()));
for (AnnotationInstance annotation : annotations) {
AnnotationTarget target = annotation.target();
String targetName = target.asClass().name().toString();
if (!userManagedEntities.contains(targetName)
&& (!targetName.startsWith("org.keycloak") || targetName.startsWith("org.keycloak.testsuite"))) {
descriptor.addClasses(targetName);
}
}
}
/**
* <p>Load the built-in provider factories during build time so we don't spend time looking up them at runtime. By loading
* providers at this stage we are also able to perform a more dynamic configuration based on the default providers.
*
* <p>User-defined providers are going to be loaded at startup</p>
*
* @param recorder
*/
@Record(ExecutionTime.STATIC_INIT)
@BuildStep
KeycloakSessionFactoryPreInitBuildItem configureKeycloakSessionFactory(KeycloakRecorder recorder, List<PersistenceXmlDescriptorBuildItem> descriptors) {
Profile.setInstance(new QuarkusProfile());
Map<Spi, Map<Class<? extends Provider>, Map<String, Class<? extends ProviderFactory>>>> factories = new HashMap<>();
Map<Class<? extends Provider>, String> defaultProviders = new HashMap<>();
Map<String, ProviderFactory> preConfiguredProviders = new HashMap<>();
for (Entry<Spi, Map<Class<? extends Provider>, Map<String, ProviderFactory>>> entry : loadFactories(preConfiguredProviders)
.entrySet()) {
Spi spi = entry.getKey();
checkProviders(spi, entry.getValue(), defaultProviders);
for (Entry<Class<? extends Provider>, Map<String, ProviderFactory>> value : entry.getValue().entrySet()) {
for (ProviderFactory factory : value.getValue().values()) {
factories.computeIfAbsent(spi,
key -> new HashMap<>())
.computeIfAbsent(spi.getProviderClass(), aClass -> new HashMap<>()).put(factory.getId(),factory.getClass());
}
}
if (spi instanceof JpaConnectionSpi) {
configureUserDefinedPersistenceUnits(descriptors, factories, preConfiguredProviders, spi);
}
if (spi instanceof ThemeResourceSpi) {
configureThemeResourceProviders(factories, spi);
}
}
recorder.configSessionFactory(factories, defaultProviders, preConfiguredProviders, loadThemesFromClassPath(), Environment.isRebuild());
return new KeycloakSessionFactoryPreInitBuildItem();
}
private List<ClasspathThemeProviderFactory.ThemesRepresentation> loadThemesFromClassPath() {
try {
List<ClasspathThemeProviderFactory.ThemesRepresentation> themes = new ArrayList<>();
Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(KEYCLOAK_THEMES_JSON);
while (resources.hasMoreElements()) {
themes.add(JsonSerialization.readValue(resources.nextElement().openStream(), ClasspathThemeProviderFactory.ThemesRepresentation.class));
}
return themes;
} catch (IOException e) {
throw new RuntimeException("Failed to load themes", e);
}
}
private void configureThemeResourceProviders(Map<Spi, Map<Class<? extends Provider>, Map<String, Class<? extends ProviderFactory>>>> factories, Spi spi) {
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> resources = classLoader.getResources(FlatClasspathThemeResourceProviderFactory.THEME_RESOURCES);
if (resources.hasMoreElements()) {
// make sure theme resources are loaded using a flat classpath. if no resources are available the provider is not registered
factories.computeIfAbsent(spi, key -> new HashMap<>()).computeIfAbsent(spi.getProviderClass(), aClass -> new HashMap<>()).put(FlatClasspathThemeResourceProviderFactory.ID, FlatClasspathThemeResourceProviderFactory.class);
}
} catch (Exception e) {
throw new RuntimeException("Failed to install default theme resource provider", e);
}
}
private void configureUserDefinedPersistenceUnits(List<PersistenceXmlDescriptorBuildItem> descriptors,
Map<Spi, Map<Class<? extends Provider>, Map<String, Class<? extends ProviderFactory>>>> factories,
Map<String, ProviderFactory> preConfiguredProviders, Spi spi) {
descriptors.stream()
.map(PersistenceXmlDescriptorBuildItem::getDescriptor)
.map(ParsedPersistenceXmlDescriptor::getName)
.filter(Predicate.not("keycloak-default"::equals)).forEach(new Consumer<String>() {
@Override
public void accept(String unitName) {
NamedJpaConnectionProviderFactory factory = new NamedJpaConnectionProviderFactory();
factory.setUnitName(unitName);
factories.get(spi).get(JpaConnectionProvider.class).put(unitName, NamedJpaConnectionProviderFactory.class);
preConfiguredProviders.put(unitName, factory);
}
});
}
/**
* Register the custom {@link org.eclipse.microprofile.config.spi.ConfigSource} implementations.
*
* @param configSources
*/
@BuildStep(onlyIfNot = IsIntegrationTest.class )
void configureConfigSources(BuildProducer<StaticInitConfigSourceProviderBuildItem> configSources) {
configSources.produce(new StaticInitConfigSourceProviderBuildItem(KeycloakConfigSourceProvider.class.getName()));
}
@BuildStep(onlyIf = IsIntegrationTest.class)
void prepareTestEnvironment(BuildProducer<StaticInitConfigSourceProviderBuildItem> configSources, DevServicesDatasourceResultBuildItem dbConfig) {
configSources.produce(new StaticInitConfigSourceProviderBuildItem("org.keycloak.quarkus.runtime.configuration.test.TestKeycloakConfigSourceProvider"));
// we do not enable dev services by default and the DevServicesDatasourceResultBuildItem might not be available when discovering build steps
// Quarkus seems to allow that when the DevServicesDatasourceResultBuildItem is not the only parameter to the build step
// this might be too sensitive and break if Quarkus changes the behavior
if (dbConfig != null && dbConfig.getDefaultDatasource() != null) {
Map<String, String> configProperties = dbConfig.getDefaultDatasource().getConfigProperties();
for (Entry<String, String> dbConfigProperty : configProperties.entrySet()) {
PropertyMapper mapper = PropertyMappers.getMapper(dbConfigProperty.getKey());
if (mapper == null) {
continue;
}
String kcProperty = mapper.getFrom();
if (kcProperty.endsWith("db")) {
// db kind set when running tests
continue;
}
System.setProperty(kcProperty, dbConfigProperty.getValue());
}
}
}
/**
* <p>Make the build time configuration available at runtime so that the server can run without having to specify some of
* the properties again.
*/
@BuildStep(onlyIf = IsReAugmentation.class)
void persistBuildTimeProperties(BuildProducer<GeneratedResourceBuildItem> resources) {
Properties properties = new Properties();
putPersistedProperty(properties, "kc.db");
for (String name : getPropertyNames()) {
putPersistedProperty(properties, name);
}
for (File jar : getProviderFiles().values()) {
properties.put(String.format("kc.provider.file.%s.last-modified", jar.getName()), String.valueOf(jar.lastModified()));
}
String profile = Environment.getProfile();
if (profile != null) {
properties.put(Environment.PROFILE, profile);
properties.put(ProfileManager.QUARKUS_PROFILE_PROP, profile);
}
properties.put(QUARKUS_PROPERTY_ENABLED, String.valueOf(QuarkusPropertiesConfigSource.getConfigurationFile() != null));
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
properties.store(outputStream, " Auto-generated, DO NOT change this file");
resources.produce(new GeneratedResourceBuildItem(PersistedConfigSource.PERSISTED_PROPERTIES, outputStream.toByteArray()));
} catch (Exception cause) {
throw new RuntimeException("Failed to persist configuration", cause);
}
}
private void putPersistedProperty(Properties properties, String name) {
PropertyMapper mapper = PropertyMappers.getMapper(name);
ConfigValue value = null;
if (mapper == null) {
if (name.startsWith(NS_QUARKUS)) {
value = Configuration.getConfigValue(name);
if (!QuarkusPropertiesConfigSource.isSameSource(value)) {
return;
}
}
} else if (mapper.isBuildTime()) {
name = mapper.getFrom();
value = Configuration.getConfigValue(name);
}
if (value != null && value.getValue() != null) {
String rawValue = value.getRawValue();
if (rawValue == null) {
rawValue = value.getValue();
}
properties.put(name, rawValue);
}
}
/**
* This will cause quarkus tu include specified modules in the jandex index. For example keycloak-services is needed as it includes
* most of the JAX-RS resources, which are required to register Resteasy builtin providers. See {@link ResteasyDeployment#isRegisterBuiltin()}.
* Similar reason is liquibase
*
* @param indexDependencyBuildItemBuildProducer
*/
@BuildStep
void index(BuildProducer<IndexDependencyBuildItem> indexDependencyBuildItemBuildProducer) {
indexDependencyBuildItemBuildProducer.produce(new IndexDependencyBuildItem("org.liquibase", "liquibase-core"));
indexDependencyBuildItemBuildProducer.produce(new IndexDependencyBuildItem("org.keycloak", "keycloak-services"));
}
@BuildStep(onlyIf = IsJpaStoreEnabled.class, onlyIfNot = IsLegacyStoreEnabled.class)
void indexNewJpaStore(BuildProducer<IndexDependencyBuildItem> indexDependencyBuildItemBuildProducer) {
indexDependencyBuildItemBuildProducer.produce(new IndexDependencyBuildItem("org.keycloak", "keycloak-model-map-jpa"));
}
@BuildStep(onlyIf = IsLegacyStoreEnabled.class)
void indexLegacyJpaStore(BuildProducer<IndexDependencyBuildItem> indexDependencyBuildItemBuildProducer) {
indexDependencyBuildItemBuildProducer.produce(new IndexDependencyBuildItem("org.keycloak", "keycloak-model-jpa"));
}
@Record(ExecutionTime.RUNTIME_INIT)
@BuildStep
void initializeFilter(BuildProducer<FilterBuildItem> filters, KeycloakRecorder recorder, HttpBuildTimeConfig httpBuildConfig,
ExecutorBuildItem executor) {
String rootPath = httpBuildConfig.rootPath;
List<String> ignoredPaths = new ArrayList<>();
if (isHealthEnabled()) {
ignoredPaths.add(rootPath + "health");
}
if (isMetricsEnabled()) {
ignoredPaths.add(rootPath + "metrics");
}
filters.produce(new FilterBuildItem(recorder.createRequestFilter(ignoredPaths, executor.getExecutorProxy()),FilterBuildItem.AUTHORIZATION - 10));
}
@BuildStep
void disableMetricsEndpoint(BuildProducer<RouteBuildItem> routes) {
if (!isMetricsEnabled()) {
routes.produce(RouteBuildItem.builder().route(DEFAULT_METRICS_ENDPOINT.concat("/*")).handler(new NotFoundHandler()).build());
}
}
@BuildStep
void disableHealthEndpoint(BuildProducer<RouteBuildItem> routes, BuildProducer<BuildTimeConditionBuildItem> removeBeans,
CombinedIndexBuildItem index) {
boolean healthDisabled = !isHealthEnabled();
if (healthDisabled) {
routes.produce(RouteBuildItem.builder().route(DEFAULT_HEALTH_ENDPOINT.concat("/*")).handler(new NotFoundHandler()).build());
}
boolean metricsDisabled = !isMetricsEnabled();
if (healthDisabled || metricsDisabled) {
// disables the single check we provide which depends on metrics enabled
ClassInfo disabledBean = index.getIndex()
.getClassByName(DotName.createSimple(KeycloakReadyHealthCheck.class.getName()));
removeBeans.produce(new BuildTimeConditionBuildItem(disabledBean.asClass(), false));
}
}
@BuildStep
void configureResteasy(BuildProducer<ResteasyDeploymentCustomizerBuildItem> deploymentCustomizerProducer) {
deploymentCustomizerProducer.produce(new ResteasyDeploymentCustomizerBuildItem(new Consumer<ResteasyDeployment>() {
@Override
public void accept(ResteasyDeployment resteasyDeployment) {
// we need to explicitly set the application to avoid errors at build time due to the application
// from keycloak-services also being added to the index
resteasyDeployment.setApplicationClass(QuarkusKeycloakApplication.class.getName());
// we need to disable the sanitizer to avoid escaping text/html responses from the server
resteasyDeployment.setProperty(ResteasyContextParameters.RESTEASY_DISABLE_HTML_SANITIZER, Boolean.TRUE);
}
}));
}
@Consume(BootstrapConfigSetupCompleteBuildItem.class)
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void setCryptoProvider(KeycloakRecorder recorder) {
FipsMode fipsMode = Configuration.getOptionalValue(
MicroProfileConfigProvider.NS_KEYCLOAK_PREFIX + SecurityOptions.FIPS_MODE.getKey()).map(
FipsMode::valueOf).orElse(FipsMode.disabled);
recorder.setCryptoProvider(fipsMode);
}
@BuildStep(onlyIf = IsDevelopment.class)
void configureDevMode(BuildProducer<HotDeploymentWatchedFileBuildItem> hotFiles) {
hotFiles.produce(new HotDeploymentWatchedFileBuildItem("META-INF/keycloak.conf"));
}
private Map<Spi, Map<Class<? extends Provider>, Map<String, ProviderFactory>>> loadFactories(
Map<String, ProviderFactory> preConfiguredProviders) {
Config.init(new MicroProfileConfigProvider());
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ProviderManager pm = getProviderManager(classLoader);
Map<Spi, Map<Class<? extends Provider>, Map<String, ProviderFactory>>> factories = new HashMap<>();
for (Spi spi : pm.loadSpis()) {
Map<Class<? extends Provider>, Map<String, ProviderFactory>> providers = new HashMap<>();
List<ProviderFactory> loadedFactories = new ArrayList<>();
String provider = Config.getProvider(spi.getName());
if (provider == null) {
loadedFactories.addAll(pm.load(spi));
} else {
ProviderFactory factory = pm.load(spi, provider);
if (factory != null) {
loadedFactories.add(factory);
}
}
Map<String, ProviderFactory> deployedScriptProviders = loadDeployedScriptProviders(classLoader, spi);
loadedFactories.addAll(deployedScriptProviders.values());
preConfiguredProviders.putAll(deployedScriptProviders);
for (ProviderFactory factory : loadedFactories) {
if (IGNORED_PROVIDER_FACTORY.contains(factory.getClass())) {
continue;
}
Config.Scope scope = Config.scope(spi.getName(), factory.getId());
if (isEnabled(factory, scope)) {
if (spi.isInternal() && !isInternal(factory)) {
ServicesLogger.LOGGER.spiMayChange(factory.getId(), factory.getClass().getName(), spi.getName());
}
providers.computeIfAbsent(spi.getProviderClass(), aClass -> new HashMap<>()).put(factory.getId(),
factory);
} else {
logger.debugv("SPI {0} provider {1} disabled", spi.getName(), factory.getId());
}
}
factories.put(spi, providers);
}
return factories;
}
private Map<String, ProviderFactory> loadDeployedScriptProviders(ClassLoader classLoader, Spi spi) {
Map<String, ProviderFactory> providers = new HashMap<>();
if (supportsDeployeableScripts(spi)) {
try {
Enumeration<URL> urls = classLoader.getResources(KEYCLOAK_SCRIPTS_JSON_PATH);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
int fileSeparator = url.getFile().indexOf(JAR_FILE_SEPARATOR);
if (fileSeparator != -1) {
JarFile jarFile = new JarFile(url.getFile().substring("file:".length(), fileSeparator));
JarEntry descriptorEntry = jarFile.getJarEntry(KEYCLOAK_SCRIPTS_JSON_PATH);
ScriptProviderDescriptor descriptor;
try (InputStream is = jarFile.getInputStream(descriptorEntry)) {
descriptor = JsonSerialization.readValue(is, ScriptProviderDescriptor.class);
}
for (Entry<String, List<ScriptProviderMetadata>> entry : descriptor.getProviders().entrySet()) {
if (isScriptForSpi(spi, entry.getKey())) {
for (ScriptProviderMetadata metadata : entry.getValue()) {
ProviderFactory provider = createDeployableScriptProvider(jarFile, entry, metadata);
providers.put(metadata.getId(), provider);
}
}
}
}
}
} catch (IOException e) {
throw new RuntimeException("Failed to discover script providers", e);
}
}
return providers;
}
private ProviderFactory createDeployableScriptProvider(JarFile jarFile, Entry<String, List<ScriptProviderMetadata>> entry,
ScriptProviderMetadata metadata) throws IOException {
String fileName = metadata.getFileName();
if (fileName == null) {
throw new RuntimeException("You must provide the script file name");
}
JarEntry scriptFile = jarFile.getJarEntry(fileName);
try (InputStream in = jarFile.getInputStream(scriptFile)) {
metadata.setCode(StreamUtil.readString(in, StandardCharsets.UTF_8));
}
metadata.setId(new StringBuilder("script").append("-").append(fileName).toString());
String name = metadata.getName();
if (name == null) {
name = fileName;
}
metadata.setName(name);
return DEPLOYEABLE_SCRIPT_PROVIDERS.get(entry.getKey()).apply(metadata);
}
private boolean isScriptForSpi(Spi spi, String type) {
if (spi instanceof ProtocolMapperSpi && (MAPPERS.equals(type) || SAML_MAPPERS.equals(type))) {
return true;
} else if (spi instanceof PolicySpi && POLICIES.equals(type)) {
return true;
} else if (spi instanceof AuthenticatorSpi && AUTHENTICATORS.equals(type)) {
return true;
}
return false;
}
private boolean supportsDeployeableScripts(Spi spi) {
return spi instanceof ProtocolMapperSpi || spi instanceof PolicySpi || spi instanceof AuthenticatorSpi;
}
private boolean isEnabled(ProviderFactory factory, Config.Scope scope) {
if (!scope.getBoolean("enabled", true)) {
return false;
}
if (factory instanceof EnvironmentDependentProviderFactory) {
return ((EnvironmentDependentProviderFactory) factory).isSupported(scope);
}
return true;
}
private boolean isInternal(ProviderFactory<?> factory) {
String packageName = factory.getClass().getPackage().getName();
return packageName.startsWith("org.keycloak") && !packageName.startsWith("org.keycloak.examples");
}
private void checkProviders(Spi spi,
Map<Class<? extends Provider>, Map<String, ProviderFactory>> factoriesMap,
Map<Class<? extends Provider>, String> defaultProviders) {
String defaultProvider = Config.getProvider(spi.getName());
if (defaultProvider != null) {
Map<String, ProviderFactory> map = factoriesMap.get(spi.getProviderClass());
if (map == null || map.get(defaultProvider) == null) {
throw new RuntimeException("Failed to find provider " + defaultProvider + " for " + spi.getName());
}
} else {
Map<String, ProviderFactory> factories = factoriesMap.get(spi.getProviderClass());
if (factories != null && factories.size() == 1) {
defaultProvider = factories.values().iterator().next().getId();
}
if (factories != null) {
if (defaultProvider == null) {
Optional<ProviderFactory> highestPriority = factories.values().stream()
.max(Comparator.comparing(ProviderFactory::order));
if (highestPriority.isPresent() && highestPriority.get().order() > 0) {
defaultProvider = highestPriority.get().getId();
}
}
}
if (defaultProvider == null && (factories == null || factories.containsKey("default"))) {
defaultProvider = "default";
}
}
if (defaultProvider != null) {
defaultProviders.put(spi.getProviderClass(), defaultProvider);
} else {
logger.debugv("No default provider for {0}", spi.getName());
}
}
private boolean isMetricsEnabled() {
return Configuration.getOptionalBooleanValue(MicroProfileConfigProvider.NS_KEYCLOAK_PREFIX.concat("metrics-enabled")).orElse(false);
}
private boolean isHealthEnabled() {
return Configuration.getOptionalBooleanValue(MicroProfileConfigProvider.NS_KEYCLOAK_PREFIX.concat("health-enabled")).orElse(false);
}
}