8000 [Quarkus 4] Adapt configuration handling to SmallRye Config 4 by Pepo48 · Pull Request #54827 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@
Breaking changes are identified as those that might require changes for existing users to their configurations or applications.
In minor or patch releases, {project_name} will only introduce breaking changes to fix bugs.

=== Escaping in server configuration values

The upgrade to SmallRye Config 4 changes how {project_name} interprets dollar signs and backslashes in server configuration values.

* Two consecutive dollar signs (`$$`) are now preserved. If you set `KC_DB_PASSWORD='has$$dollar'` to supply the password `has$dollar`, change it to `KC_DB_PASSWORD='has$dollar'` before upgrading.
* If you used `$$` to prevent an expression from expanding, escape the opening dollar sign with a backslash instead. For example, change `KC_DB_PASSWORD='$${vault.secret}'` to `KC_DB_PASSWORD='\${vault.secret}'` in a shell that supports single quotes.
* Before upgrading, review server configuration values that contain both a backslash and a `${...}` expression. SmallRye Config 4 now interprets backslash escapes throughout those values. For example, `\n` can become a newline where it was previously literal. To preserve a literal backslash, double it in the value that reaches expression expansion, and account separately for any escaping required by your shell or properties file. For example, with `KEYSTORE_NAME=server.p12`, set `KC_HTTPS_KEY_STORE_FILE='C:\\certs\\${KEYSTORE_NAME}'` in a shell that supports single quotes to obtain `C:\certs\server.p12`. In `conf/keycloak.conf`, write `https-key-store-file=C:\\\\certs\\\\${KEYSTORE_NAME}` because the properties file processes escapes before expression expansion.

To pass an environment value through exactly as written, use the `KCRAW_` prefix. For example, replace `KC_DB_PASSWORD` with `KCRAW_DB_PASSWORD='has$dollar'` to supply that password literally.
For details, see the link:{server_guide_base_link}/configuration#kcraw-prefix[Preserving literal values with the KCRAW_ prefix] section in the Server Configuration guide.

=== Validation of client URI fields
// https://github.com/keycloak/keycloak/issues/54046

Expand Down
51 changes: 36 additions & 15 deletions docs/guides/server/configuration.adoc
8000
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,32 @@ You can also store Quarkus properties in a Java KeyStore.

{project_name} depends upon Quarkus and MicroProfile for processing configuration values. Be aware that value expressions are supported. For example, `$\{some_key}` evaluates to the value of `some_key`.

To disable expression evaluation, the `\` character functions as an escape character. In particular, it must be used to escape the usage of `$` characters when they appear to define an expression or are repeated. For example, if you want the configuration value `my$$password`, use `my\$\$password` instead. Note that the `\` character requires additional escaping or quoting when using most unix shells, or when it appears in properties files.
For example, bash single quotes preserve the single backslash `--db-password='my\$\$password'`. Also, with bash double quotes, you need an additional backslash `--db-password="my\\$\\$password"`. Similarly in a properties file, backslash characters must also be escaped: `kc.db-password=my\\$\\$password`
To disable expression evaluation, use `\` to escape the `$` that opens an expression. Dollar signs that do not open an expression, including `$$`, are preserved without additional escaping. Backslashes may require additional escaping or quoting according to the shell or configuration-source format. For environment values that must be preserved literally, use the `KCRAW_` prefix described below.

.Windows-specific considerations
When specifying Windows file paths in configuration values, backslashes must also be escaped. For example, if you want to specify the path `C:\path\to\file`, you should write it as `C:\\path\\to\\file`. Alternatively, you can use forward slashes which don't need escaping: `C:/path/to/file`.
If a configuration value contains a `${r"${...}"}` expression, {project_name} also interprets backslash escapes throughout that value.
For example, `\n` becomes a newline and `\t` becomes a tab, even outside the expression.
Use `\\` for each backslash you want to preserve.

For example, in Bash, the following environment variables configure the HTTPS keystore file as `C:\data\server.p12`:

[source,bash]
----
export KEYSTORE_NAME=server.p12
export KC_HTTPS_KEY_STORE_FILE='C:\\data\\${r"${KEYSTORE_NAME}"}'
----

In `conf/keycloak.conf`, each backslash needs additional escaping because the properties file format also processes backslashes.
With `KEYSTORE_NAME=server.p12` exported in the environment, the following setting configures the same keystore file:

[source,properties]
----
https-key-store-file=C:\\\\data\\\\${r"${KEYSTORE_NAME}"}
----

A value without an expression keeps its backslashes during expression evaluation.
Shell quoting and properties file escaping still apply.
For Windows paths, you can also use forward slashes, for example `C:/data/server.p12`.
Use the `KCRAW_` prefix described below when an environment value must be preserved literally.

When using PowerShell and your values contain special characters like commas, use single quotes around double quotes:

Expand All @@ -179,28 +200,28 @@ When manual escaping is not feasible (like when a password is injected by a secr
[[kcraw-prefix]]
=== Preserving literal values with the KCRAW_ prefix

When setting configuration values, {project_name} (via SmallRye Config) evaluates expressions such as `$\{some_key}` and collapses `$$` to `$`. This means passwords or secrets containing `$` characters may be silently modified. While the `\` escaping described above works for values you control directly, it is not always practical - for example, when a secrets manager or orchestration tool injects the value and you cannot add escape characters.
When setting configuration values, {project_name} (via SmallRye Config) evaluates expressions such as `$\{some_key}`. This means passwords or secrets containing expression-like text may be modified. While the `\` escaping described above works for values you control directly, it is not always practical - for example, when a secrets manager or orchestration tool injects the value and you cannot add escape characters.

In these cases, use the `KCRAW_` prefix instead of `KC_` for any environment variable whose value must be preserved exactly as written. {project_name} automatically escapes `$` characters in `KCRAW_` values so that expression evaluation preserves the original value.
In these cases, use the `KCRAW_` prefix instead of `KC_` for any environment variable whose value must be preserved exactly as written. {project_name} automatically protects backslashes and expression openers in `KCRAW_` values so that expression evaluation preserves the original environment value.

.Example: Setting a database password containing special characters
[source, bash]
----
# Standard prefix — the value will be modified by expression evaluation:
export KC_DB_PASSWORD='my$$pa$\{vault}word'
# Result: "$$" is collapsed to "$" and "$\{vault}" is evaluated as an
# expression, producing "my$paword" or an error

# Raw prefix — the value is preserved exactly as written:
export KCRAW_DB_PASSWORD='my$$pa$\{vault}word'
# Result: the password is used as-is: my$$pa$\{vault}word
export PASSWORD_PART='demo'

# With the standard prefix, Keycloak expands the expression to produce my$$pademoword.
export KC_DB_PASSWORD='my$$pa${r"${PASSWORD_PART}"}word'

# With the raw prefix, Keycloak uses the literal value my$$pa${r"${PASSWORD_PART}"}word.
unset KC_DB_PASSWORD
export KCRAW_DB_PASSWORD='my$$pa${r"${PASSWORD_PART}"}word'
----

[NOTE]
====
* The `KCRAW_` prefix applies only to environment variables, where shell quoting rules make escaping of `$` unreliable. Other configuration sources are subject to their own format escaping mechanisms and their values are still treated as expressions.
* You cannot set both `KC_<KEY>` and `KCRAW_<KEY>` for the same configuration key. If both are present, {project_name} will fail to start and report a configuration error.
* Apart from escaping `$` characters, `KCRAW_` variables behave identically to their `KC_` counterparts: the same key mapping and priority rules apply.
* Apart from preserving literal values, `KCRAW_` variables behave identically to their `KC_` counterparts: the same key mapping and priority rules apply.
====

=== Formats for environment variable keys with special characters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,11 @@ private static Map<String, String> buildProperties(Map<String, String> env) {
}
}

// KCRAW_ values escape $ as $$ to prevent SmallRye Config variable interpolation
// Then replace \$ with \\ to prevent SmallRye's escapeDollarIfExists from consuming backslashes before dollars
properties.put(transformedKey, isRaw ? value.replace(&qu 8000 ot;$", "$$").replace("\\$", "\\\\") : value);
// SmallRye processes backslash escapes only when the value contains an expression.
if (isRaw && value.contains("${")) {
value = value.replace("\\", "\\\\").replace("${", "\\${");
}
properties.put(transformedKey, value);
}

return properties;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ protected <T> T getValue(String key, Function<String, T> conversion, Class<T> cl
|| (oldValue.getValue() != null && oldValue.getSourceOrdinal() > value.getSourceOrdinal())) {
value = oldValue;
}
return Optional.ofNullable(config.convert(value.getValue(), clazz)).orElse(defaultValue);
return Optional.ofNullable(value.getValue())
.map(raw -> config.requireConverter(clazz).convert(raw))
.orElse(defaultValue);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,7 @@ public void validateValues(ConfigValue configValue, BiConsumer<ConfigValue, Stri
throw new PropertyException("Invalid empty value for option %s".formatted(getOptionAndSourceMessage(configValue)));
}
try {
Configuration.getConfig().convert(v, option.getComponentType());
Configuration.getConfig().requireConverter(option.getComponentType()).convert(v);
} catch (Exception e) {
// strip the smallrye code if possible
String message = e.getMessage();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
package org.keycloak.quarkus.runtime.configuration;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceConfigurationError;
import java.util.Set;
Expand Down Expand Up @@ -58,10 +61,35 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

public class ConfigurationTest extends AbstractConfigurationTest {

@Test
public void testTypedSpiConversion() {
putEnvVar("KC_SPI_CONVERSION__COUNT", "42");
putEnvVar("KC_SPI_CONVERSION__ACTIVE", "true");
Config.Scope scope = initConfig("conversion");
assertEquals(Integer.valueOf(42), scope.getInt("count"));
assertTrue(scope.getBoolean("active"));
}

@Test
public void testMissingTypedSpiValuesUseDefaults() {
Config.Scope scope = initConfig("conversion");
assertNull(scope.getInt("missing"));
assertEquals(Integer.valueOf(17), scope.getInt("missing", 17));
assertFalse(scope.getBoolean("missing", false));
}

@Test
public void testInvalidTypedSpiValues() {
putEnvVar("KC_SPI_CONVERSION__COUNT", "not-a-number");
Config.Scope scope = initConfig("conversion");
assertThrows(IllegalArgumentException.class, () -> scope.getInt("count"));
}

@Test
public void testCamelCase() {
putEnvVar("KC_SPI_CAMEL_CASE_SCOPE_CAMEL_CASE_PROP", "foobar");
Expand Down Expand Up @@ -100,10 +128,10 @@ public void testEnvVarPriorityOverPropertiesFileMixedSpiNamingConventions() {

@Test
public void testKeycloakConfPlaceholder() {
assertEquals("info", createConfig().getRawValue("kc.log-level"));
assertEquals("info", createConfig().getConfigValue("kc.log-level").getValue());
assertTrue(Configuration.getConfig().isPropertyPresent("quarkus.log.category.\"io.k8s\".level"));
putEnvVar("SOME_LOG_LEVEL", "debug");
assertEquals("debug", createConfig().getRawValue("kc.log-level"));
assertEquals("debug", createConfig().getConfigValue("kc.log-level").getValue());
SmallRyeConfig config = ConfigBuilderCustomizer.addInterceptors(ConfigUtils.emptyConfigBuilder().setAddDefaultSources(false).addDiscoveredSources()).build();
assertNull(Expressions.withoutExpansion(() -> config.getConfigValue("kc.log-level")).getValue());
}
Expand Down Expand Up @@ -1114,10 +1142,66 @@ public void testRawAndKcConflictThrowsError() {

@Test
public void testNonRawPropertiesUnaffected() {
// Standard KC_ env var with $$ should still be subject to expression evaluation (collapsing $$ to $)
putEnvVar("KC_EXPRESSION_TEST", "dollar");
putEnvVar("KC_DB_PASSWORD", "has${kc.expression-test}");
SmallRyeConfig config = createConfig();
assertEquals("hasdollar", config.getConfigValue("kc.db-password").getValue());
}

@Test
public void testNonRawEnvVarPreservesDoubleDollar() {
putEnvVar("KC_DB_PASSWORD", "has$$dollar");
SmallRyeConfig config = createConfig();
assertEquals("has$dollar", config.getConfigValue("kc.db-password").getValue());
assertEquals("has$$dollar", config.getConfigValue("kc.db-password").getValue());
}

@Test
public void testNonRawEnvVarProcessesBackslashesThroughoutExpressionValue() {
putEnvVar("KC_EXPRESSION_TEST", "logs");
putEnvVar("KC_DB_PASSWORD", "C:\\data\\folder");
assertEquals("C:\\data\\folder", createConfig().getConfigValue("kc.db-password").getValue());

putEnvVar("KC_DB_PASSWORD", "${kc.expression-test}:C:\\data\\folder");
assertEquals("logs:C:data\folder", createConfig().getConfigValue("kc.db-password").getValue());

putEnvVar("KC_DB_PASSWORD", "C:\\\\data\\\\${kc.expression-test}\\\\folder");
assertEquals("C:\\data\\logs\\folder", createConfig().getConfigValue("kc.db-password").getValue());
}

@Test
public void testCliProcessesBackslashesThroughoutExpressionValue() {
putEnvVar("KC_EXPRESSION_TEST", "logs");
var config = createConfigFromCliArguments("--db-password=C:\\\\data\\\\${kc.expression-test}\\\\folder");
assertEquals("C:\\data\\logs\\folder", config.getConfigValue("kc.db-password").getValue());

config = createConfigFromCliArguments("--db-password=${kc.expression-test}:C:\\data\\folder");
assertEquals("logs:C:data\folder", config.getConfigValue("kc.db-password").getValue());
}

@Test
public void testFileAndExpressionBackslashEscaping() throws IOException {
var file = Files.createTempFile("keycloak-expression-", ".conf");
try {
// Four backslashes in the file become two after properties parsing, then one after expression expansion.
Files.writeString(file, "db-password=C:" + "\\".repeat(4) + "data" + "\\".repeat(4)
+ "${kc.directory}\ndirectory=logs\n");
var sources = new KeycloakPropertiesConfigSource.InFileSystem()
.getConfigSources(getClass().getClassLoader(), file);
var config = new SmallRyeConfigBuilder().addDefaultInterceptors()
.withSources(sources).build();
assertEquals("C:\\data\\logs", config.getConfigValue("kc.db-password").getValue());
} finally {
Files.delete(file);
}
}

@Test
public void testRawEnvVarPreservesBackslashesWithExpressions() {
for (String value : List.of("\\${vault.secret}", "${vault.secret}\\", "path\\to\\${vault.secret}\\$value", "$${vault.secret}")) {
putEnvVar("KCRAW_DB_PASSWORD", value);
SmallRyeConfig config = createConfig();
assertEquals(value, config.getConfigValue("kc.db-password").getValue());
}
}

@Test
Expand Down
Loading
0