8000 Avoid merging message bundle and attributes into a new map by ahus1 · Pull Request #52991 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
import org.keycloak.theme.ThemeResourcesParser;
import org.keycloak.theme.beans.AdvancedMessageFormatterMethod;
import org.keycloak.theme.beans.LocaleBean;
import org.keycloak.theme.beans.MessageAttributeProperties;
import org.keycloak.theme.beans.MessageBean;
import org.keycloak.theme.beans.MessageFormatterMethod;
import org.keycloak.theme.beans.MessagesPerFieldBean;
Expand Down Expand Up @@ -153,6 +154,7 @@ public class FreeMarkerLoginFormsProvider implements LoginFormsProvider {

protected final Map<String, Object> attributes = new HashMap<>();
private Function<Map<String, Object>, Map<String, Object>> attributeMapper;
private MessageAttributeProperties messageAttributeProperties;

public FreeMarkerLoginFormsProvider(KeycloakSession session) {
this.session = session;
Expand Down Expand Up @@ -430,9 +432,8 @@ protected Properties handleThemeResources(Theme theme, Locale locale) {
Properties messagesBundle;
try {
messagesBundle = theme.getEnhancedMessages(realm, locale);
Map<Object, Object> msgParams = new HashMap<>(attributes);
msgParams.putAll(messagesBundle);
attributes.put("msg", new MessageFormatterMethod(locale, msgParams));
messageAttributeProperties = new MessageAttributeProperties(messagesBundle, attributes);
attributes.put("msg", new MessageFormatterMethod(locale, messageAttributeProperties));
attributes.put("advancedMsg", new AdvancedMessageFormatterMethod(locale, messagesBundle));
} catch (IOException e) {
logger.warn("Failed to load messages", e);
Expand Down Expand Up @@ -641,6 +642,14 @@ protected Response processTemplate(Theme theme, String templateName, Locale loca

attributes.put("pageId", templateName.substring(0, templateName.length() - 4));

// Rebind "msg"'s attribute lookups to this final, post-attributeMapper map: if attributeMapper
// returned a replacement map rather than mutating this.attributes in place, a ${...} placeholder
// inside a translated message string must still see the same map FreeMarker itself renders
// against, or the two could silently resolve the same key to different values.
if (messageAttributeProperties != null) {
messageAttributeProperties.rebind(attributes);
}

String result = freeMarker.processTemplate(attributes, templateName, theme);
Response.ResponseBuilder builder = Response.status(status == null ? Response.Status.OK : status).type(MediaType.TEXT_HTML_UTF_8_TYPE).language(locale).entity(result);
for (Map.Entry<String, String> entry : httpResponseHeaders.entrySet()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
* Copyright 2026 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.theme.beans;

import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
* Read-only {@link Properties} view used to resolve {@code ${...}} placeholders inside message strings
* (see {@link MessageFormatterMethod}), checking the message bundle first and falling back to arbitrary
* template attributes (e.g. {@code ${realm.displayName}}).
* <p>
* This is a zero-copy alternative to merging the message bundle and the template attributes into a new
* map: message lookups are delegated to {@code messages} via {@link Properties}' native {@code defaults}
* chaining, and attribute lookups hold a reference to the (still-mutable-elsewhere) {@code attributes}
* map.
* <p>
* That reference is rebindable (see {@link #rebind(Map)}), not just held live from construction: {@code
* FreeMarkerLoginFormsProvider} constructs this instance in {@code handleThemeResources()}, but the map it
* actually hands to FreeMarker for rendering (in {@code processTemplate()}) can be a different instance by
* then, if an {@code attributeMapper} is registered and returns a replacement map rather than mutating the
* original in place. Without rebinding, a {@code ${...}} placeholder embedded inside a translated message
* string would keep resolving against the original, pre-mapper map, while the exact same placeholder
* written directly in a template file resolves against the post-mapper map - the two would silently
* disagree. {@code FreeMarkerLoginFormsProvider} calls {@link #rebind(Map)} with the post-mapper map right
* before rendering, so both paths resolve attributes as of the same, final render-time view.
*/
public class MessageAttributeProperties extends Properties {

private Map<String, Object> attributes;

public MessageAttributeProperties(Properties messages, Map<String, Object> attributes) {
super(messages);
this.attributes = attributes;
}

/**
* Rebinds attribute lookups to a different {@code attributes} map, replacing the one passed to the
* constructor. Called by {@code FreeMarkerLoginFormsProvider.processTemplate()} once the final,
* post-{@code attributeMapper} map is known, so lookups made while rendering (e.g. from {@link
* MessageFormatterMethod}) see the same map FreeMarker itself renders against.
*/
public void rebind(Map<String, Object> attributes) {
this.attributes = attributes;
}

@Override
public String getProperty(String key) {
String value = super.getProperty(key);
if (value != null) {
return value;
}
Object attribute = attributes.get(key);
return attribute != null ? attribute.toString() : null;
}

/**
* {@link Hashtable#getOrDefault(Object, Object)} only consults this instance's own (always empty) entries,
* ignoring the {@code Properties} {@code defaults} chain that {@link #getProperty(String)} relies on.
* Route it through {@link #getProperty(String)} instead, so callers using either method see the same result.
*/
@Override
public Object getOrDefault(Object key, Object defaultValue) {
if (key instanceof String) {
String value = getProperty((String) key);
if (value != null) {
return value;
}
}
return defaultValue;
}

@Override
public synchronized Object setProperty(String key, String value) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized Object put(Object key, Object value) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
Comment thread
ahus1 marked this conversation as resolved.
Resolved
}

@Override
public synchronized Object remove(Object key) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized void putAll(Map<?, ?> t) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized void clear() {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized Object putIfAbsent(Object key, Object value) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized boolean remove(Object key, Object value) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized boolean replace(Object key, Object oldValue, Object newValue) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized Object replace(Object key, Object value) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized Object computeIfAbsent(Object key, Function<? super Object, ?> mappingFunction) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized Object computeIfPresent(Object key, BiFunction<? super Object, ? super Object, ?> remappingFunction) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized Object compute(Object key, BiFunction<? super Object, ? super Object, ?> remappingFunction) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized Object merge(Object key, Object value, BiFunction<? super Object, ? super Object, ?> remappingFunction) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}

@Override
public synchronized void replaceAll(BiFunction<? super Object, ? super Object, ?> function) {
throw new UnsupportedOperationException("MessageAttributeProperties is read-only");
}
}
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/*
* Copyright 2026 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.theme.beans;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;

public class MessageAttributePropertiesTest {

@Test
public void resolvesMessageKeyBeforeAttribute() {
Properties messages = new Properties();
messages.setProperty("greeting", "hello");

Map<String, Object> attributes = new HashMap<>();
attributes.put("greeting", "should not be used");

MessageAttributeProperties properties = new MessageAttributeProperties(messages, attributes);

assertEquals("hello", properties.getProperty("greeting"));
}

@Test
public void fallsBackToAttributeWhenMessageMissing() {
Properties messages = new Properties();

Map<String, Object> attributes = new HashMap<>();
attributes.put("realm", "example-realm");

MessageAttributeProperties properties = new MessageAttributeProperties(messages, attributes);

assertEquals("example-realm", properties.getProperty("realm"));
}

@Test
public void returnsNullWhenKeyIsUnknown() {
MessageAttributeProperties properties = new MessageAttributeProperties(new Properties(), new HashMap<>());

assertNull(properties.getProperty("unknown"));
}

@Test
public void resolvesAttributesAsOfRenderTimeNotConstructionTime() {
Properties messages = new Properties();
Map<String, Object> attributes = new HashMap<>();

MessageAttributeProperties properties = new MessageAttributeProperties(messages, attributes);

assertNull(properties.getProperty("url"));

// Deliberate: FreeMarkerLoginFormsProvider.processTemplate() resolves native ${...} template
// expressions against the same, by-then fully-populated attributes map. Attributes added after
// this instance is constructed (as happens while createCommonAttributes() keeps populating it)
// must become visible too, so a ${...} placeholder embedded inside a translated message string
// resolves consistently with the same placeholder written directly in a template file.
attributes.put("url", "https://example.org");

assertEquals("https://example.org", properties.getProperty("url"));
}

@Test
public void rebindSwitchesAttributeLookupsToTheGivenMap() {
Properties messages = new Properties();
Map<String, Object> original = new HashMap<>();
original.put("url", "https://original.example.org");

MessageAttributeProperties properties = new MessageAttributeProperties(messages, original);
assertEquals("https://original.example.org", properties.getProperty("url"));

// Simulates FreeMarkerLoginFormsProvider.processTemplate() rebinding to the map returned by a
// registered attributeMapper, which may be a different instance rather than a mutation of the
// original: lookups must follow the rebound map, not stay pinned to the one passed to the
// constructor.
Map<String, Object> replacement = new HashMap<>();
replacement.put("url", "https://mapped.example.org");
properties.rebind(replacement);

assertEquals("https://mapped.example.org", properties.getProperty("url"));

// The original map is no longer consulted at all, even if it is still mutated afterwards.
original.put("url", "https://should-not-be-seen.example.org");
assertEquals("https://mapped.example.org", properties.getProperty("url"));
}

@Test
public void isReadOnly() {
MessageAttributeProperties properties = new MessageAttributeProperties(new Properties(), new HashMap<>());

assertThrows(UnsupportedOperationException.class, () -> properties.setProperty("key", "value"));
assertThrows(UnsupportedOperationException.class, () -> properties.put("key", "value"));
assertThrows(UnsupportedOperationException.class, () -> properties.remove("key"));
assertThrows(UnsupportedOperationException.class, () -> properties.putAll(new HashMap<>()));
assertThrows(UnsupportedOperationException.class, properties::clear);
assertThrows(UnsupportedOperationException.class, () -> properties.putIfAbsent("key", "value"));
assertThrows(UnsupportedOperationException.class, () -> properties.remove("key", "value"));
assertThrows(UnsupportedOperationException.class, () -> properties.replace("key", "old", "new"));
assertThrows(UnsupportedOperationException.class, () -> properties.replace("key", "value"));
assertThrows(UnsupportedOperationException.class, () -> properties.computeIfAbsent("key", k -> "value"));
assertThrows(UnsupportedOperationException.class, () -> properties.computeIfPresent("key", (k, v) -> "value"));
assertThrows(UnsupportedOperationException.class, () -> properties.compute("key", (k, v) -> "value"));
assertThrows(UnsupportedOperationException.class, () -> properties.merge("key", "value", (a, b) -> b));
assertThrows(UnsupportedOperationException.class, () -> properties.replaceAll((k, v) -> v));
}

@Test
public void getOrDefaultResolvesMessageBeforeAttribute() {
Properties messages = new Properties();
messages.setProperty("greeting", "hello");

Map<String, Object> attributes = new HashMap<>();
attributes.put("greeting", "should not be used");

MessageAttributeProperties properties = new MessageAttributeProperties(messages, attributes);

// MessageFormatterMethod.exec() looks up messages via getOrDefault(), not getProperty() - it must
// go through the same message-then-attribute lookup, not Hashtable's own (always empty) entries.
assertEquals("hello", properties.getOrDefault("greeting", "greeting"));
}

@Test
public void getOrDefaultFallsBackToAttribute() {
Properties messages = new Properties();
Map<String, Object> attributes = new HashMap<>();
attributes.put("realm", "example-realm");

MessageAttributeProperties properties = new MessageAttributeProperties(messages, attributes);

assertEquals("example-realm", properties.getOrDefault("realm", "realm"));
}

@Test
public void getOrDefaultFallsBackToDefaultValueWhenKeyIsUnknown() {
MessageAttributeProperties properties = new MessageAttributeProperties(new Properties(), new HashMap<>());

assertEquals("unknown", properties.getOrDefault("unknown", "unknown"));
}
}
Loading
0