From fc40907a5866310f620d22c7f76ba5c148fafc07 Mon Sep 17 00:00:00 2001
From: Jacek Kowalski <Jacek@jacekk.info>
Date: Tue, 03 Nov 2026 21:04:42 +0000
Subject: [PATCH] Return CAS error instead of HTTP 500 on malformed tickets

---
 integrationTest/suite.sh                                                        |   14 ++++++++++++++
 src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java |    9 +++++++--
 2 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/integrationTest/suite.sh b/integrationTest/suite.sh
index b2f2b24..ca556c1 100755
--- a/integrationTest/suite.sh
+++ b/integrationTest/suite.sh
@@ -80,6 +80,20 @@
 fi
 echo
 
+echo "Testing CAS 2.0 - malformed ticket..."
+response=$(curl --silent --write-out '%{http_code}' --output /dev/null "${keycloak_cas_url}/serviceValidate?service=http://localhost&ticket=ST-x--zz--y")
+if [ "$response" != "400" ]; then
+    echo "Malformed ticket returned HTTP ${response} instead of 400"
+    exit 1
+fi
+
+echo "Testing CAS 2.0 - proxyValidate without ticket..."
+response=$(curl --silent --write-out '%{http_code}' --output /dev/null "${keycloak_cas_url}/proxyValidate?service=http://localhost")
+if [ "$response" != "400" ]; then
+    echo "Missing ticket returned HTTP ${response} instead of 400"
+    exit 1
+fi
+
 # SAML 1.1
 echo "Testing SAML 1.1..."
 ticket=$(get_ticket SAML)
diff --git a/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java b/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java
index 6a93fac..c517572 100644
--- a/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java
+++ b/src/main/java/org/keycloak/protocol/cas/endpoints/AbstractValidateEndpoint.java
@@ -330,7 +330,12 @@
     }
 
     private String hexDecode(String hex) {
-        byte[] bytes = HexFormat.of().parseHex(hex);
-        return new String(bytes, StandardCharsets.US_ASCII);
+        try {
+            byte[] bytes = HexFormat.of().parseHex(hex);
+            return new String(bytes, StandardCharsets.US_ASCII);
+        } catch (IllegalArgumentException e) {
+            event.error(Errors.INVALID_CODE);
+            throw new CASValidationException(CASErrorCode.INVALID_TICKET_SPEC, "Invalid format of the code", Response.Status.BAD_REQUEST);
+        }
     }
 }

--
Gitblit v1.10.0