8000 ErrorId for error screens and logging by dafenix · Pull Request #44072 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Closed
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
8000
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

public final class KeycloakHandlerChainCustomizer implements HandlerChainCustomizer {

private final RequestIdHandler REQUEST_ID_HANDLER = new RequestIdHandler();
private final TransactionalSessionHandler TRANSACTIONAL_SESSION_HANDLER = new TransactionalSessionHandler();

private final FormBodyHandler formBodyHandler = new FormBodyHandler(true, () -> Runnable::run, Set.of());
Expand All @@ -44,6 +45,8 @@ public List<ServerRestHandler> handlers(Phase phase, ResourceClass resourceClass

switch (phase) {
case BEFORE_METHOD_INVOKE:
// Add RequestId handler first to ensure RequestId is available throughout request lifecycle
handlers.add(REQUEST_ID_HANDLER);
if (!resourceMethod.isFormParamRequired() &&
(PATCH.equalsIgnoreCase(resourceMethod.getHttpMethod()) ||
POST.equalsIgnoreCase(resourceMethod.getHttpMethod()) ||
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package org.keycloak.quarkus.runtime.integration.resteasy;

import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
import org.jboss.resteasy.reactive.server.spi.ServerRestHandler;
import org.keycloak.models.KeycloakSession;

import org.slf4j.MDC;

import io.quarkus.arc.Arc;

import java.util.UUID;

/**
* Handler that generates or extracts a unique RequestId for each HTTP request.
* The RequestId is set in the MDC context and stored in the KeycloakSession for
* use throughout the request lifecycle.
*
* Priority:
* 1. Uses existing X-Request-ID header if present (from external systems)
* 2. Generates new UUID if no external RequestId is provided
*
* The RequestId is available:
* - In MDC with key "kc.requestId"
* - In KeycloakSession attributes with key "requestId"
* - In HTTP response headers as "X-Request-ID"
*/
public final class RequestIdHandler implements ServerRestHandler {

public static final String REQUEST_ID_HEADER = "X-Request-ID";
public static final String MDC_KEY = "kc.requestId";
public static final String SESSION_ATTRIBUTE_KEY = "requestId";

@Override
public void handle(ResteasyReactiveRequestContext requestContext) {
// Generate or extract RequestId
String requestId = extractOrGenerateRequestId(requestContext);

// Set in MDC for logging
MDC.put(MDC_KEY, requestId);

// Store in session if available
try {
requestContext.requireCDIRequestScope();
KeycloakSession session = Arc.container().instance(KeycloakSession.class).get();
if (session != null) {
session.setAttribute(SESSION_ATTRIBUTE_KEY, requestId);
}
} catch (Exception e) {
// Session might not be available yet, but MDC is set
// This is acceptable as the session will be available later
}
}

private String extractOrGenerateRequestId(ResteasyReactiveRequestContext requestContext) {
// Check for existing X-Request-ID header
String existingRequestId = requestContext.getHttpHeaders().getHeaderString(REQUEST_ID_HEADER);

if (existingRequestId != null && !existingRequestId.trim().isEmpty()) {
// Use external RequestId (from load balancer, API gateway, etc.)
return existingRequestId.trim();
} else {
// Generate new UUID for this request
return UUID.randomUUID().toString();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ void testLogMdcShowingInTheLogs(CLIResult cliResult) {
.statusCode(200);
Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(
() -> assertThat(cliResult.getOutput(), containsString("{kc.realmName=master} DEBUG [org.keycloak.")));
Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(
() -> assertThat(cliResult.getOutput(), containsString("{kc.requestId=")));
cliResult.assertStartedDevMode();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import org.jboss.logging.MDC;

import org.keycloak.OAuth2Constants;
import org.keycloak.authentication.AuthenticationFlowContext;
Expand Down Expand Up @@ -92,6 +94,7 @@
import org.keycloak.services.Urls;
import org.keycloak.services.messages.Messages;
import org.keycloak.services.resources.LoginActionsService;
import org.keycloak.services.util.RequestIdUtil;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.theme.FreeMarkerException;
import org.keycloak.theme.Theme;
Expand All @@ -105,10 +108,10 @@
import org.keycloak.utils.MediaType;
import org.keycloak.utils.MediaTypeMatcher;

import org.jboss.logging.Logger;

import static org.keycloak.models.UserModel.RequiredAction.UPDATE_PASSWORD;
import static org.keycloak.organization.utils.Organizations.resolveOrganization;
import static org.keycloak.services.error.KeycloakErrorHandler.ERROR_ATTRIBUTE_ID;
import static org.keycloak.services.error.KeycloakErrorHandler.ERROR_ID;

/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
Expand Down Expand Up @@ -337,6 +340,12 @@ protected Response createResponse(LoginFormsPages page) {
case LOGOUT_CONFIRM:
attributes.put("logoutConfirm", new LogoutConfirmBean(accessCode, authenticationSession));
break;
case LOGIN_PAGE_EXPIRED, ERROR, ERROR_WEBAUTHN:
String errorId = RequestIdUtil.getCurrentRequestId(); //ErrorIdGenerator.generate();
MDC.put(ERROR_ID, errorId);
attributes.put(ERROR_ATTRIBUTE_ID, errorId);
logger.infof("Rendering following errorId: '%s' to the user.", errorId);
break;
}

return processTemplate(theme, Templates.getTemplate(page), locale);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package org.keycloak.services.error;

import java.security.SecureRandom;

public class ErrorIdGenerator {

private static final char[] ALLOWED_CHARS = "abcdefghjkmnpqrstuvwxyz23456789".toCharArray();
private static final SecureRandom RANDOM = new SecureRandom();

public static String generate() {
StringBuilder sb = new StringBuilder(8);
for (int i = 0; i < 8; i++) {
sb.append(ALLOWED_CHARS[RANDOM.nextInt(ALLOWED_CHARS.length)]);
}
return sb.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jboss.logging.Logger;
import org.jboss.logging.MDC;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
Expand All @@ -30,6 +32,7 @@
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.messages.Messages;
import org.keycloak.services.util.RequestIdUtil;
import org.keycloak.theme.Theme;
import org.keycloak.theme.beans.AdvancedMessageFormatterMethod;
import org.keycloak.theme.beans.LocaleBean;
Expand All @@ -55,6 +58,8 @@ public class KeycloakErrorHandler implements ExceptionMapper<Throwable> {

public static final String UNCAUGHT_SERVER_ERROR_TEXT = "Uncaught server error";
public static final String ERROR_RESPONSE_TEXT = "Error response {0}";
public static final String ERROR_ID = "error.id";
public static final String ERROR_ATTRIBUTE_ID = "errorId";

@Override
public Response toResponse(Throwable throwable) {
Expand All @@ -81,9 +86,16 @@ public static Response getResponse(KeycloakSession session, Throwable throwable)
Response.Status responseStatus = getResponseStatus(throwable);
boolean isServerError = responseStatus.getFamily().equals(Response.Status.Family.SERVER_ERROR);

String errorId = RequestIdUtil.getCurrentRequestId(); //ErrorIdGenerator.generate();

if (MDC.get(ERROR_ID) == null) {
MDC.put(ERROR_ID, errorId);
}

if (isServerError) {
logger.error(UNCAUGHT_SERVER_ERROR_TEXT, throwable);
} else {
// ToDo: Discuss if this should be logged at warn level. Risk of flooding the log files.
logger.debugv(throwable, ERROR_RESPONSE_TEXT, responseStatus);
}

Expand Down Expand Up @@ -119,6 +131,10 @@ public static Response getResponse(KeycloakSession session, Throwable throwable)
FreeMarkerProvider freeMarker = session.getProvider(FreeMarkerProvider.class);
Map<String, Object> attributes = initAttributes(session, realm, theme, locale, responseStatus);

if (!attributes.containsKey(ERROR_ATTRIBUTE_ID)) {
attributes.put(ERROR_ATTRIBUTE_ID, errorId);
}

String templateName = "error.ftl";

String content = freeMarker.processTemplate(attributes, templateName, theme);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package org.keycloak.services.filters;

import jakarta.annotation.Priority;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.ext.Provider;

import org.keycloak.models.KeycloakSession;
import org.keycloak.utils.KeycloakSessionUtil;
import org.slf4j.MDC;

/**
* Filter that adds the X-Request-ID header to HTTP responses.
*
* This filter extracts the RequestId that was set by the RequestIdHandler early in the request lifecycle
* and includes it in the HTTP response headers. This allows clients to correlate requests with server logs
* and enables better traceability in distributed systems.
*
* The RequestId is retrieved from:
* 1. MDC (Mapped Diagnostic Context) - primary source
* 2. KeycloakSession attributes - fallback if MDC is not available
*
* The filter runs at priority 20, which is after the security headers filter (priority 10)
* but before most other filters, ensuring the X-Request-ID header is consistently added.
*
* @author Keycloak Team
*/
@Provider
@PreMatching
@Priority(20)
public class RequestIdHeaderFilter implements ContainerResponseFilter {

/**
* MDC key for the RequestId
*/
private static final String MDC_REQUEST_ID_KEY = "kc.requestId";

/**
* Session attribute key for the RequestId
*/
private static final String SESSION_REQUEST_ID_KEY = "requestId";

/**
* HTTP header name for the RequestId
*/
private static final String REQUEST_ID_HEADER = "X-Request-ID";

@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) {
addRequestIdHeader(containerResponseContext);
}

/**
* Adds the X-Request-ID header to the HTTP response if a RequestId is available.
*
* The method tries to retrieve the RequestId from multiple sources in order of preference:
* 1. MDC (most reliable, thread-local context)
* 2. KeycloakSession attributes (fallback)
*
* If a RequestId is found and is not empty, it's added to the response headers.
* This allows clients to correlate their requests with server-side logging.
*
* @param responseContext the HTTP response context where the header will be added
*/
private void addRequestIdHeader(ContainerResponseContext responseContext) {
String requestId = null;

// Try to get RequestId from MDC first (most reliable)
requestId = MDC.get(MDC_REQUEST_ID_KEY);

// Fallback to session attribute if MDC is not available
if (requestId == null) {
try {
KeycloakSession session = KeycloakSessionUtil.getKeycloakSession();
if (session != null) {
requestId = (String) session.getAttribute(SESSION_REQUEST_ID_KEY);
}
} catch (Exception e) {
// Session might not be available in some contexts, which is acceptable
// We'll simply not add the header in such cases
}
}

// Add X-Request-ID header if RequestId is available
if (requestId != null && !requestId.trim().isEmpty()) {
responseContext.getHeaders().add(REQUEST_ID_HEADER, requestId);
}
}
}
Loading
0