From 9d9698a1538683126d13845e8aa8013bf8396577 Mon Sep 17 00:00:00 2001
From: Lars Seipel <ls@slrz.net>
Date: Tue, 4 Mar 2025 11:42:42 +0100
Subject: [PATCH] connector/ldap: hex-encode UserID to ensure it is UTF8

---
 connector/ldap/tweak.go | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/connector/ldap/tweak.go b/connector/ldap/tweak.go
index 34facee7..0a97e765 100644
--- a/connector/ldap/tweak.go
+++ b/connector/ldap/tweak.go
@@ -1,6 +1,7 @@
 package ldap
 
 import (
+	"encoding/hex"
 	"strings"
 
 	"github.com/dexidp/dex/connector"
@@ -9,10 +10,18 @@ import (
 // TweakIdentity adjusts attributes received from the LDAP directory. Don't ask
 // why this is necessary. Just learn to accept it.
 func tweakIdentity(id connector.Identity) connector.Identity {
+	id.UserID = tweakUserID(id)
 	id.Username = tweakName(id)
 	return id
 }
 
+func tweakUserID(id connector.Identity) string {
+	// If the UserID happens to be something that is not valid UTF8 (like
+	// Windows/AD SIDs), it gets mangled during JSON marshaling when saved to
+	// storage. Ensure it is UTF8.
+	return hex.EncodeToString([]byte(id.UserID))
+}
+
 func tweakName(id connector.Identity) string {
 	name := id.Username
 	if name == " " {
-- 
GitLab