Skip to content
Open
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 @@ -107,10 +107,14 @@ public Response handleToken(IdpVerifyAccountLinkActionToken token, ActionTokenCo
authSession.getClient().getClientId(), authSession.getTabId(), AuthenticationProcessor.getClientData(session, authSession));
String confirmUri = builder.build(realm.getName()).toString();

String idpUsername = token.getIdentityProviderUsername() != null ? token.getIdentityProviderUsername() : "";
String idpAlias = token.getIdentityProviderAlias() != null ? token.getIdentityProviderAlias() : "";
LoginFormsProvider forms = session.getProvider(LoginFormsProvider.class);
return forms.setAuthenticationSession(authSession)
.setAttribute("messageHeader", forms.getMessage(Messages.CONFIRM_ACCOUNT_LINKING, token.getIdentityProviderUsername(), token.getIdentityProviderAlias()))
.setSuccess(Messages.CONFIRM_ACCOUNT_LINKING_BODY, token.getIdentityProviderUsername(), token.getIdentityProviderAlias())
.setAttribute("messageHeader", Messages.CONFIRM_ACCOUNT_LINKING)
.setAttribute("messageHeaderUsername", idpUsername)
.setAttribute("messageHeaderAlias", idpAlias)
.setSuccess(Messages.CONFIRM_ACCOUNT_LINKING_BODY, idpUsername, idpAlias)
.setAttribute(Constants.TEMPLATE_ATTR_ACTION_URI, confirmUri)
.createInfoPage();
}
Expand All @@ -130,10 +134,12 @@ public Response handleToken(IdpVerifyAccountLinkActionToken token, ActionTokenCo

setUserVerifiedSingleObject(token, realm, session, user);

String idpUsername = token.getIdentityProviderUsername() != null ? token.getIdentityProviderUsername() : "";
String idpAlias = token.getIdentityProviderAlias() != null ? token.getIdentityProviderAlias() : "";
return session.getProvider(LoginFormsProvider.class)
.setAuthenticationSession(authSession)
.setAttribute("messageHeader", Messages.IDENTITY_PROVIDER_LINK_SUCCESS_HEADER)
.setSuccess(Messages.IDENTITY_PROVIDER_LINK_SUCCESS, token.getIdentityProviderAlias(), token.getIdentityProviderUsername())
.setSuccess(Messages.IDENTITY_PROVIDER_LINK_SUCCESS, idpAlias, idpUsername)
.setAttribute(Constants.SKIP_LINK, true)
.createInfoPage();
}
Expand Down Expand Up @@ -172,10 +178,12 @@ private static String getUserVerifiedSingleObjectKey(String userId, String idpAl

private Response sendLinkConfirmedAlready(KeycloakSession session, EventBuilder event, UserModel user, IdpVerifyAccountLinkActionToken token) {
event.user(user).error(Errors.IDENTITY_PROVIDER_LINK_CONFIRMED_ALREADY);
String idpUsername = token.getIdentityProviderUsername() != null ? token.getIdentityProviderUsername() : "";
String idpAlias = token.getIdentityProviderAlias() != null ? token.getIdentityProviderAlias() : "";
return session.getProvider(LoginFormsProvider.class)
.setAuthenticationSession(session.getContext().getAuthenticationSession())
.setAttribute("messageHeader", Messages.IDENTITY_PROVIDER_LINK_CONFIRMED_ALREADY_HEADER)
.setInfo(Messages.IDENTITY_PROVIDER_LINK_CONFIRMED_ALREADY, token.getIdentityProviderAlias(), token.getIdentityProviderUsername())
.setInfo(Messages.IDENTITY_PROVIDER_LINK_CONFIRMED_ALREADY, idpAlias, idpUsername)
.createInfoPage();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,12 @@ protected LoginFormsProvider setupForm(AuthenticationFlowContext context, Multiv
SerializedBrokeredIdentityContext serializedCtx0 = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT);
if (serializedCtx0 != null) {
BrokeredIdentityContext ctx0 = serializedCtx0.deserialize(context.getSession(), context.getAuthenticationSession());
form.setError(Messages.NESTED_FIRST_BROKER_FLOW_MESSAGE, ctx0.getIdpConfig().getAlias(), ctx0.getUsername());
String alias = ctx0.getIdpConfig().getAlias() != null ? ctx0.getIdpConfig().getAlias() : "";
String username = ctx0.getUsername() != null ? ctx0.getUsername() : "";
form.setError(Messages.NESTED_FIRST_BROKER_FLOW_MESSAGE, alias, username);
form.setAttribute("nestedIdpHeader", Messages.NESTED_FIRST_BROKER_FLOW_MESSAGE);
form.setAttribute("nestedIdpAlias", alias);
form.setAttribute("nestedIdpUsername", username);
context.getAuthenticationSession().setAuthNote(AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT, null);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
/*
* 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;

import java.io.File;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import org.keycloak.theme.beans.MessageFormatterMethod;

import freemarker.core.HTMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
* Test verifying FreeMarker FTL template parsing, HTML escaping, and sanitization for identity provider link email and info templates (Fixes #51277).
*/
public class TemplateSanitizationTest {

private Configuration cfg;
private KeycloakSanitizerMethod kcSanitize;
private MessageFormatterMethod msg;

@Before
public void setUp() throws Exception {
cfg = new Configuration(Configuration.VERSION_2_3_32);
cfg.setOutputFormat(HTMLOutputFormat.INSTANCE);

kcSanitize = new KeycloakSanitizerMethod();

Properties props = new Properties();
props.setProperty("identityProviderLinkBodyHtml", "<p>Someone wants to link your account <b>{1}</b> with identity provider <b>{0}</b> as user <b>{2}</b>.</p><p><a href=\"{3}\">Link account</a></p>");
props.setProperty("confirmAccountLinking", "Confirm linking account {0} of identity provider {1} with your account.");
props.setProperty("nestedFirstBrokerFlowMessage", "Re-authenticating with {0} as {1}.");
msg = new MessageFormatterMethod(Locale.US, props);
}

private File getThemeFile(String themePath, String relativePath) {
File file = new File("../themes/src/main/resources/theme/" + themePath + "/" + relativePath);
if (!file.exists()) {
file = new File("themes/src/main/resources/theme/" + themePath + "/" + relativePath);
}
return file;
}

private String getMarkerExpression(String themePath, String relativePath, String marker) throws Exception {
File templateFile = getThemeFile(themePath, relativePath);
String ftlSource = new String(Files.readAllBytes(templateFile.toPath()), StandardCharsets.UTF_8);
return Arrays.stream(ftlSource.split("\\R"))
.map(String::trim)
.filter(line -> line.contains(marker) && line.contains("kcSanitize("))
.findFirst()
.orElseThrow(() -> new AssertionError("Sanitization marker '" + marker + "' not found in " + relativePath));
}

@Test
public void testIdentityProviderLinkFtlTemplateRendering() throws Exception {
String sinkLine = getMarkerExpression("base", "email/html/identity-provider-link.ftl", "identityProviderLinkBodyHtml");
Template template = new Template("identity-provider-link", sinkLine, cfg);

String[] testPayloads = new String[] {
"NormalUser",
"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>John",
"User \"Test\" & Admin",
"user{0}with{1}tokens",
"user__KC_IDP_USERNAME__name"
};

for (String payload : testPayloads) {
Map<String, Object> model = new HashMap<>();
Map<String, Object> idpCtx = new HashMap<>();
idpCtx.put("username", payload);

model.put("kcSanitize", kcSanitize);
model.put("msg", msg);
model.put("identityProviderDisplayName", "GitHub");
model.put("realmName", "master");
model.put("identityProviderContext", idpCtx);
model.put("link", "https://keycloak.example/link");
model.put("linkExpiration", "5");
model.put("linkExpirationFormatter", new TemplateMethodModelEx() {
@Override
public Object exec(List arguments) throws TemplateModelException {
return arguments.isEmpty() ? "5 minutes" : arguments.get(0) + " minutes";
}
});

StringWriter writer = new StringWriter();
template.process(model, writer);
String result = writer.toString();

Assert.assertFalse("Payload <script> tag must not render as live HTML", result.contains("<script>"));
Assert.assertFalse("Payload <img> tag must not render as live HTML", result.contains("<img"));
Assert.assertTrue("Template HTML link formatting must be preserved", result.contains("<a href=\"https://keycloak.example/link\" rel=\"nofollow\">Link account</a>"));

if (payload.contains("__KC_")) {
Assert.assertTrue("Sentinel text must survive safely in email output", result.contains(payload));
}
}
}

@Test
public void testInfoFtlMessageHeaderSanitization() throws Exception {
String sinkLine = getMarkerExpression("base", "login/info.ftl", "messageHeaderUsername");
Template template = new Template("info-header", sinkLine, cfg);

String[] testPayloads = new String[] {
"NormalUser",
"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>John",
"User \"Test\" & Admin",
"user{0}with{1}tokens",
"user__KC_MSG_HEADER_ALIAS__name",
"user__KC_MSG_HEADER_USERNAME__name"
};

for (String payload : testPayloads) {
Map<String, Object> model = new HashMap<>();
model.put("kcSanitize", kcSanitize);
model.put("msg", msg);
model.put("messageHeader", "confirmAccountLinking");
model.put("messageHeaderUsername", payload);
model.put("messageHeaderAlias", "github");

StringWriter writer = new StringWriter();
template.process(model, writer);
String result = writer.toString();

Assert.assertFalse("Payload <script> tag must not render as live HTML in info header", result.contains("<script>"));
Assert.assertFalse("Payload <img> tag must not render as live HTML in info header", result.contains("<img"));

if (payload.contains("__KC_")) {
Assert.assertTrue("Sentinel text must survive safely in info header output", result.contains(payload));
}
}
}

@Test
public void testTemplateFtlNestedBrokerSummarySanitization() throws Exception {
String sinkLine = getMarkerExpression("base", "login/template.ftl", "nestedIdpUsername");
Template template = new Template("template-summary", sinkLine, cfg);

String[] testPayloads = new String[] {
"NormalUser",
"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>John",
"User \"Test\" & Admin",
"user{0}with{1}tokens",
"user__KC_NESTED_IDP_ALIAS__name",
"user__KC_NESTED_IDP_USERNAME__name"
};

for (String payload : testPayloads) {
Map<String, Object> model = new HashMap<>();
Map<String, Object> message = new HashMap<>();
message.put("summary", "nestedFirstBrokerFlowMessage");
model.put("kcSanitize", kcSanitize);
model.put("msg", msg);
model.put("message", message);
model.put("nestedIdpHeader", "nestedFirstBrokerFlowMessage");
model.put("nestedIdpAlias", "github");
model.put("nestedIdpUsername", payload);

Map<String, Object> properties = new HashMap<>();
properties.put("kcAlertTitleClass", "alert-title");
model.put("properties", properties);

StringWriter writer = new StringWriter();
template.process(model, writer);
String result = writer.toString();

Assert.assertFalse("Payload <script> tag must not render as live HTML in summary", result.contains("<script>"));
Assert.assertFalse("Payload <img> tag must not render as live HTML in summary", result.contains("<img"));

if (payload.contains("__KC_")) {
Assert.assertTrue("Sentinel text must survive safely in summary output", result.contains(payload));
}
}
}

@Test
public void testKeycloakV2TemplateNestedBrokerSummarySanitization() throws Exception {
String sinkLine = getMarkerExpression("keycloak.v2", "login/template.ftl", "nestedIdpUsername");
Template template = new Template("v2-template-summary", sinkLine, cfg);

String[] testPayloads = new String[] {
"NormalUser",
"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>John",
"User \"Test\" & Admin",
"user{0}with{1}tokens",
"user__KC_NESTED_IDP_ALIAS__name",
"user__KC_NESTED_IDP_USERNAME__name"
};

for (String payload : testPayloads) {
Map<String, Object> model = new HashMap<>();
Map<String, Object> message = new HashMap<>();
message.put("summary", "nestedFirstBrokerFlowMessage");
model.put("kcSanitize", kcSanitize);
model.put("msg", msg);
model.put("message", message);
model.put("nestedIdpHeader", "nestedFirstBrokerFlowMessage");
model.put("nestedIdpAlias", "github");
model.put("nestedIdpUsername", payload);

Map<String, Object> properties = new HashMap<>();
properties.put("kcAlertTitleClass", "alert-title");
model.put("properties", properties);

StringWriter writer = new StringWriter();
template.process(model, writer);
String result = writer.toString();

Assert.assertFalse("Payload <script> tag must not render as live HTML in V2 summary", result.contains("<script>"));
Assert.assertFalse("Payload <img> tag must not render as live HTML in V2 summary", result.contains("<img"));

if (payload.contains("__KC_")) {
Assert.assertTrue("Sentinel text must survive safely in V2 summary output", result.contains(payload));
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<#import "template.ftl" as layout>
<@layout.emailLayout>
${kcSanitize(msg("identityProviderLinkBodyHtml", identityProviderDisplayName, realmName, identityProviderContext.username, link, linkExpiration, linkExpirationFormatter(linkExpiration)))?no_esc}
${kcSanitize(msg("identityProviderLinkBodyHtml", identityProviderDisplayName, realmName, "__KC_IDP_USERNAME__", link, linkExpiration, linkExpirationFormatter(linkExpiration)))?replace("__KC_IDP_USERNAME__", ((identityProviderContext.username!)?esc)?markup_string)?no_esc}
</@layout.emailLayout>
6 changes: 4 additions & 2 deletions themes/src/main/resources/theme/base/login/info.ftl
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<#import "template.ftl" as layout>
<@layout.registrationLayout displayMessage=false; section>
<#if section = "header">
<#if messageHeader??>
${kcSanitize(msg("${messageHeader}"))?no_esc}
<#if messageHeader?? && messageHeaderUsername??>
${kcSanitize(msg(messageHeader))?replace("{0}", "__KC_MSG_HEADER_USERNAME__")?replace("{1}", "__KC_MSG_HEADER_ALIAS__")?replace("__KC_MSG_HEADER_ALIAS__", ((messageHeaderAlias!)?esc)?markup_string)?replace("__KC_MSG_HEADER_USERNAME__", ((messageHeaderUsername!)?esc)?markup_string)?no_esc}
<#elseif messageHeader??>
${kcSanitize(msg(messageHeader))?no_esc}
<#else>
${message.summary}
</#if>
Expand Down
7 changes: 6 additions & 1 deletion themes/src/main/resources/theme/base/login/template.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,12 @@
<#if message.type = 'error'><span class="${properties.kcFeedbackErrorIcon!}"></span></#if>
<#if message.type = 'info'><span class="${properties.kcFeedbackInfoIcon!}"></span></#if>
</div>
<span class="${properties.kcAlertTitleClass!}">${kcSanitize(message.summary)?no_esc}</span>
<#if nestedIdpUsername?? && nestedIdpHeader??>
<#-- Single-pass MessageFormat pattern sanitization with collision-free sentinels followed by post-sanitization variable escaping to prevent XSS entity decoding bypass -->
<span class="${properties.kcAlertTitleClass!}">${kcSanitize(msg(nestedIdpHeader))?replace("{0}", "__KC_NESTED_IDP_ALIAS__")?replace("{1}", "__KC_NESTED_IDP_USERNAME__")?replace("__KC_NESTED_IDP_ALIAS__", ((nestedIdpAlias!)?esc)?markup_string)?replace("__KC_NESTED_IDP_USERNAME__", ((nestedIdpUsername!)?esc)?markup_string)?no_esc}</span>
<#else>
<span class="${properties.kcAlertTitleClass!}">${kcSanitize(message.summary)?no_esc}</span>
</#if>
Comment on lines +186 to +191
</div>
</#if>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,12 @@
<#if message.type = 'error'><span class="${properties.kcFeedbackErrorIcon!}"></span></#if>
<#if message.type = 'info'><span class="${properties.kcFeedbackInfoIcon!}"></span></#if>
</div>
<span class="${properties.kcAlertTitleClass!} kc-feedback-text">${message.summary}</span>
<#if nestedIdpUsername?? && nestedIdpHeader??>
<#-- Single-pass MessageFormat pattern sanitization with collision-free sentinels followed by post-sanitization variable escaping to prevent XSS entity decoding bypass -->
<span class="${properties.kcAlertTitleClass!} kc-feedback-text">${kcSanitize(msg(nestedIdpHeader))?replace("{0}", "__KC_NESTED_IDP_ALIAS__")?replace("{1}", "__KC_NESTED_IDP_USERNAME__")?replace("__KC_NESTED_IDP_ALIAS__", ((nestedIdpAlias!)?esc)?markup_string)?replace("__KC_NESTED_IDP_USERNAME__", ((nestedIdpUsername!)?esc)?markup_string)?no_esc}</span>
<#else>
<span class="${properties.kcAlertTitleClass!} kc-feedback-text">${kcSanitize(message.summary)?no_esc}</span>
</#if>
</div>
</#if>

Expand Down