This is an automated email from the ASF dual-hosted git repository.

coheigea pushed a commit to branch coheigea/ModelEncryptionSupport
in repository https://gitbox.apache.org/repos/asf/cxf.git

commit edcdb38f9b40a9b27d6c06ce4ecc415401617127
Author: Colm O hEigeartaigh <[email protected]>
AuthorDate: Tue Dec 1 08:20:48 2026 +0000

    Escape values in ModelEncryptionSupport serialization
---
 .../oauth2/provider/JoseSessionTokenProvider.java  |  25 ++-
 .../utils/crypto/ModelEncryptionSupport.java       | 192 +++++++++++++++------
 .../provider/JoseSessionTokenProviderTest.java     |  60 +++++++
 .../oauth2/utils/crypto/CryptoUtilsTest.java       | 109 ++++++++++++
 4 files changed, 324 insertions(+), 62 deletions(-)

diff --git 
a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/provider/JoseSessionTokenProvider.java
 
b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/provider/JoseSessionTokenProvider.java
index 3fa631f8abc..ee906509146 100644
--- 
a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/provider/JoseSessionTokenProvider.java
+++ 
b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/provider/JoseSessionTokenProvider.java
@@ -143,43 +143,42 @@ public class JoseSessionTokenProvider implements 
SessionAuthenticityTokenProvide
         return stateString;
     }
 
-    private OAuthRedirectionState convertStateStringToState(String 
stateString) {
-        String[] parts = ModelEncryptionSupport.getParts(stateString);
+    protected OAuthRedirectionState convertStateStringToState(String 
stateString) {
+        String[] parts = ModelEncryptionSupport.getParts(stateString, 10);
         OAuthRedirectionState state = new OAuthRedirectionState();
         if (!StringUtils.isEmpty(parts[0])) {
-            state.setClientId(parts[0]);
+            state.setClientId(ModelEncryptionSupport.getStringPart(parts[0]));
         }
         if (!StringUtils.isEmpty(parts[1])) {
-            state.setAudience(parts[1]);
+            state.setAudience(ModelEncryptionSupport.getStringPart(parts[1]));
         }
         if (!StringUtils.isEmpty(parts[2])) {
-            state.setClientCodeChallenge(parts[2]);
+            
state.setClientCodeChallenge(ModelEncryptionSupport.getStringPart(parts[2]));
         }
         if (!StringUtils.isEmpty(parts[3])) {
-            state.setState(parts[3]);
+            state.setState(ModelEncryptionSupport.getStringPart(parts[3]));
         }
         if (!StringUtils.isEmpty(parts[4])) {
-            state.setProposedScope(parts[4]);
+            
state.setProposedScope(ModelEncryptionSupport.getStringPart(parts[4]));
         }
         if (!StringUtils.isEmpty(parts[5])) {
-            state.setRedirectUri(parts[5]);
+            
state.setRedirectUri(ModelEncryptionSupport.getStringPart(parts[5]));
         }
         if (!StringUtils.isEmpty(parts[6])) {
-            state.setNonce(parts[6]);
+            state.setNonce(ModelEncryptionSupport.getStringPart(parts[6]));
         }
         if (!StringUtils.isEmpty(parts[7])) {
-            state.setResponseType(parts[7]);
+            
state.setResponseType(ModelEncryptionSupport.getStringPart(parts[7]));
         }
         if (!StringUtils.isEmpty(parts[8])) {
             
state.setExtraProperties(ModelEncryptionSupport.parseSimpleMap(parts[8]));
         }
         if (!StringUtils.isEmpty(parts[9])) {
-            state.setClientCodeChallengeMethod(parts[9]);
+            
state.setClientCodeChallengeMethod(ModelEncryptionSupport.getStringPart(parts[9]));
         }
         return state;
     }
     protected String convertStateToString(OAuthRedirectionState secData) {
-        //TODO: make it simpler, convert it to JwtClaims -> JSON
         StringBuilder state = new StringBuilder();
         // 0: client id
         
state.append(ModelEncryptionSupport.tokenizeString(secData.getClientId()));
@@ -206,7 +205,7 @@ public class JoseSessionTokenProvider implements 
SessionAuthenticityTokenProvide
         
state.append(ModelEncryptionSupport.tokenizeString(secData.getResponseType()));
         state.append(ModelEncryptionSupport.SEP);
         // 8: extra props
-        state.append(secData.getExtraProperties().toString());
+        
state.append(ModelEncryptionSupport.tokenizeMap(secData.getExtraProperties()));
         state.append(ModelEncryptionSupport.SEP);
         // 9: client code challenge method
         
state.append(ModelEncryptionSupport.tokenizeString(secData.getClientCodeChallengeMethod()));
diff --git 
a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/utils/crypto/ModelEncryptionSupport.java
 
b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/utils/crypto/ModelEncryptionSupport.java
index 8ae5403684f..373dd7017c1 100644
--- 
a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/utils/crypto/ModelEncryptionSupport.java
+++ 
b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/utils/crypto/ModelEncryptionSupport.java
@@ -22,7 +22,6 @@ package org.apache.cxf.rs.security.oauth2.utils.crypto;
 import java.nio.charset.StandardCharsets;
 import java.security.Key;
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
@@ -49,6 +48,12 @@ import org.apache.cxf.rt.security.crypto.KeyProperties;
 public final class ModelEncryptionSupport {
     public static final String SEP = "|";
 
+    private static final String ESCAPED_CHARS = "%|.,=[]{} ";
+    private static final String HEX_DIGITS = "0123456789ABCDEF";
+    private static final int ACCESS_TOKEN_PARTS = 13;
+    private static final int CLIENT_PARTS = 14;
+    private static final int CODE_GRANT_PARTS = 10;
+
     private static final String DEFAULT_TRANSFORMATION = "AES/GCM/NoPadding";
     private static final int DEFAULT_IV_SIZE = 12;
     private static final int DEFAULT_AUTH_TAG_LENGTH = 128;
@@ -296,13 +301,13 @@ public final class ModelEncryptionSupport {
     public static ServerAccessToken recreateAccessToken(OAuthDataProvider 
provider,
                                                   String newTokenKey,
                                                   String decryptedSequence) 
throws SecurityException {
-        return recreateAccessToken(provider, newTokenKey, 
getParts(decryptedSequence));
+        return recreateAccessToken(provider, newTokenKey, 
getParts(decryptedSequence, ACCESS_TOKEN_PARTS));
     }
 
     public static RefreshToken recreateRefreshToken(OAuthDataProvider provider,
                                                     String newTokenKey,
                                                     String decryptedSequence) 
throws SecurityException {
-        String[] parts = getParts(decryptedSequence);
+        String[] parts = getParts(decryptedSequence, ACCESS_TOKEN_PARTS + 1);
         ServerAccessToken token = recreateAccessToken(provider, newTokenKey, 
parts);
         return new RefreshToken(token,
                                 newTokenKey,
@@ -324,9 +329,10 @@ public final class ModelEncryptionSupport {
 
 
         @SuppressWarnings("serial")
-        final ServerAccessToken newToken = new 
ServerAccessToken(provider.getClient(parts[4]),
-                                                                 parts[1],
-                                                                 newTokenKey 
== null ? parts[0] : newTokenKey,
+        final ServerAccessToken newToken = new 
ServerAccessToken(provider.getClient(getStringPart(parts[4])),
+                                                                 
getStringPart(parts[1]),
+                                                                 newTokenKey 
== null
+                                                                     ? 
getStringPart(parts[0]) : newTokenKey,
                                                                  
Long.parseLong(parts[2]),
                                                                  
Long.parseLong(parts[3])) {
         };
@@ -339,9 +345,10 @@ public final class ModelEncryptionSupport {
         // Permissions
         if (!parts[9].trim().isEmpty()) {
             List<OAuthPermission> perms = new LinkedList<>();
-            String[] allPermParts = parts[9].split("\\.");
+            String[] allPermParts = parts[9].split("\\.", -1);
             for (int i = 0; i + 4 < allPermParts.length; i = i + 5) {
-                OAuthPermission perm = new OAuthPermission(allPermParts[i], 
allPermParts[i + 1]);
+                OAuthPermission perm = new 
OAuthPermission(getStringPart(allPermParts[i]),
+                                                           
getStringPart(allPermParts[i + 1]));
                 perm.setDefaultPermission(Boolean.parseBoolean(allPermParts[i 
+ 2]));
                 perm.setHttpVerbs(parseSimpleList(allPermParts[i + 3]));
                 perm.setUris(parseSimpleList(allPermParts[i + 4]));
@@ -350,7 +357,7 @@ public final class ModelEncryptionSupport {
             newToken.setScopes(perms);
         }
         //Client verifier:
-        newToken.setClientCodeVerifier(parts[10]);
+        newToken.setClientCodeVerifier(getStringPart(parts[10]));
         //UserSubject:
         newToken.setSubject(recreateUserSubject(parts[11]));
 
@@ -361,7 +368,7 @@ public final class ModelEncryptionSupport {
 
     private static String tokenizeRefreshToken(RefreshToken token) {
         String seq = tokenizeServerToken(token);
-        return seq + SEP + token.getAccessTokens().toString();
+        return seq + SEP + tokenizeList(token.getAccessTokens());
     }
 
     private static String tokenizeServerToken(ServerAccessToken token) {
@@ -388,17 +395,21 @@ public final class ModelEncryptionSupport {
         state.append(tokenizeString(token.getGrantType()));
         // 7: audience
         state.append(SEP);
-        state.append(token.getAudiences().toString());
+        state.append(tokenizeList(token.getAudiences()));
         // 8: other parameters
         state.append(SEP);
-        // {key=value, key=value}
-        state.append(token.getParameters().toString());
+        state.append(tokenizeMap(token.getParameters()));
         // 9: permissions
         state.append(SEP);
         if (token.getScopes().isEmpty()) {
             state.append(' ');
         } else {
+            boolean first = true;
             for (OAuthPermission p : token.getScopes()) {
+                if (!first) {
+                    state.append('.');
+                }
+                first = false;
                 // 9.1
                 state.append(tokenizeString(p.getPermission()));
                 state.append('.');
@@ -409,10 +420,10 @@ public final class ModelEncryptionSupport {
                 state.append(p.isDefaultPermission());
                 state.append('.');
                 // 9.4
-                state.append(p.getHttpVerbs().toString());
+                state.append(tokenizeList(p.getHttpVerbs()));
                 state.append('.');
                 // 9.5
-                state.append(p.getUris().toString());
+                state.append(tokenizeList(p.getUris()));
             }
         }
         state.append(SEP);
@@ -423,16 +434,15 @@ public final class ModelEncryptionSupport {
         tokenizeUserSubject(state, token.getSubject());
         // 13: extra properties
         state.append(SEP);
-        // {key=value, key=value}
-        state.append(token.getExtraProperties().toString());
+        state.append(tokenizeMap(token.getExtraProperties()));
         return state.toString();
     }
 
 
     private static Client recreateClientInternal(String sequence) {
-        String[] parts = getParts(sequence);
-        Client c = new Client(parts[0],
-                              parts[1],
+        String[] parts = getParts(sequence, CLIENT_PARTS);
+        Client c = new Client(getStringPart(parts[0]),
+                              getStringPart(parts[1]),
                               Boolean.parseBoolean(parts[2]),
                               getStringPart(parts[3]), 
getStringPart(parts[4]));
         c.setApplicationDescription(getStringPart(parts[5]));
@@ -470,22 +480,22 @@ public final class ModelEncryptionSupport {
         state.append(tokenizeString(client.getApplicationLogoUri()));
         state.append(SEP);
         // 7: app certificates
-        state.append(client.getApplicationCertificates());
+        state.append(tokenizeList(client.getApplicationCertificates()));
         state.append(SEP);
         // 8: grants
-        state.append(client.getAllowedGrantTypes().toString());
+        state.append(tokenizeList(client.getAllowedGrantTypes()));
         state.append(SEP);
         // 9: redirect URIs
-        state.append(client.getRedirectUris().toString());
+        state.append(tokenizeList(client.getRedirectUris()));
         state.append(SEP);
         // 10: registered scopes
-        state.append(client.getRegisteredScopes().toString());
+        state.append(tokenizeList(client.getRegisteredScopes()));
         state.append(SEP);
         // 11: registered audiences
-        state.append(client.getRegisteredAudiences().toString());
+        state.append(tokenizeList(client.getRegisteredAudiences()));
         state.append(SEP);
         // 12: properties
-        state.append(client.getProperties().toString());
+        state.append(tokenizeMap(client.getProperties()));
         state.append(SEP);
         // 13: subject
         tokenizeUserSubject(state, client.getSubject());
@@ -494,11 +504,12 @@ public final class ModelEncryptionSupport {
     }
     private static ServerAuthorizationCodeGrant 
recreateCodeGrantInternal(OAuthDataProvider provider,
                                                                           
String sequence) {
-        String[] parts = getParts(sequence);
-        ServerAuthorizationCodeGrant grant = new 
ServerAuthorizationCodeGrant(provider.getClient(parts[0]),
-                                                                              
parts[1],
-                                                                              
Long.parseLong(parts[2]),
-                                                                              
Long.parseLong(parts[3]));
+        String[] parts = getParts(sequence, CODE_GRANT_PARTS);
+        ServerAuthorizationCodeGrant grant =
+            new 
ServerAuthorizationCodeGrant(provider.getClient(getStringPart(parts[0])),
+                                             getStringPart(parts[1]),
+                                             Long.parseLong(parts[2]),
+                                             Long.parseLong(parts[3]));
         grant.setRedirectUri(getStringPart(parts[4]));
         grant.setAudience(getStringPart(parts[5]));
         grant.setClientCodeChallenge(getStringPart(parts[6]));
@@ -510,7 +521,7 @@ public final class ModelEncryptionSupport {
     private static String tokenizeCodeGrant(ServerAuthorizationCodeGrant 
grant) {
         StringBuilder state = new StringBuilder();
         // 0: client id
-        state.append(grant.getClient().getClientId());
+        state.append(tokenizeString(grant.getClient().getClientId()));
         state.append(SEP);
         // 1: code
         state.append(tokenizeString(grant.getCode()));
@@ -531,19 +542,18 @@ public final class ModelEncryptionSupport {
         state.append(tokenizeString(grant.getClientCodeChallenge()));
         state.append(SEP);
         // 7: approved scopes
-        state.append(grant.getApprovedScopes().toString());
+        state.append(tokenizeList(grant.getApprovedScopes()));
         state.append(SEP);
         // 8: subject
         tokenizeUserSubject(state, grant.getSubject());
         // 9: extra properties
         state.append(SEP);
-        // {key=value, key=value}
-        state.append(grant.getExtraProperties().toString());
+        state.append(tokenizeMap(grant.getExtraProperties()));
         return state.toString();
     }
 
     public static String getStringPart(String str) {
-        return " ".equals(str) ? null : str;
+        return " ".equals(str) ? null : unescape(str);
     }
 
     private static String prepareSimpleString(String str) {
@@ -551,31 +561,49 @@ public final class ModelEncryptionSupport {
     }
 
     private static List<String> parseSimpleList(String listStr) {
-        String pureStringList = prepareSimpleString(listStr);
-        if (pureStringList.isEmpty()) {
-            return Collections.emptyList();
+        List<String> list = new LinkedList<>();
+        for (String value : splitSimpleList(listStr)) {
+            list.add(getStringPart(value));
         }
-        return Arrays.asList(pureStringList.split(","));
+        return list;
+    }
+
+    private static String[] splitSimpleList(String listStr) {
+        String pureStringList = prepareSimpleString(listStr);
+        return pureStringList.isEmpty() ? new String[0] : 
pureStringList.split(",", -1);
     }
 
     public static Map<String, String> parseSimpleMap(String mapStr) {
         Map<String, String> props = new HashMap<>();
-        List<String> entries = parseSimpleList(mapStr);
-        for (String entry : entries) {
-            String[] pair = entry.split("=");
-            props.put(pair[0], pair[1]);
+        for (String entry : splitSimpleList(mapStr)) {
+            String[] pair = entry.split("=", -1);
+            if (pair.length != 2) {
+                throw new SecurityException("Invalid map entry");
+            }
+            props.put(getStringPart(pair[0]), getStringPart(pair[1]));
         }
         return props;
     }
 
     public static String[] getParts(String sequence) {
-        return sequence.split("\\" + SEP);
+        return sequence.split("\\" + SEP, -1);
+    }
+
+    public static String[] getParts(String sequence, int expectedParts) {
+        String[] parts = getParts(sequence);
+        if (parts.length != expectedParts) {
+            throw new SecurityException("Unexpected number of sequence parts");
+        }
+        return parts;
     }
 
     private static UserSubject recreateUserSubject(String sequence) {
         UserSubject subject = null;
         if (!sequence.trim().isEmpty()) {
-            String[] subjectParts = sequence.split("\\.");
+            String[] subjectParts = sequence.split("\\.", -1);
+            if (subjectParts.length != 4) {
+                throw new SecurityException("Invalid subject");
+            }
             subject = new UserSubject(getStringPart(subjectParts[0]), 
getStringPart(subjectParts[1]));
             subject.setRoles(parseSimpleList(subjectParts[2]));
             subject.setProperties(parseSimpleMap(subjectParts[3]));
@@ -594,16 +622,82 @@ public final class ModelEncryptionSupport {
             state.append(tokenizeString(subject.getId()));
             state.append('.');
             // 3
-            state.append(subject.getRoles().toString());
+            state.append(tokenizeList(subject.getRoles()));
             state.append('.');
             // 4
-            state.append(subject.getProperties().toString());
+            state.append(tokenizeMap(subject.getProperties()));
         } else {
             state.append(' ');
         }
     }
 
+    /**
+     * Writes a single value. A null value is written as a single space, and 
the separator
+     * characters {@code % | . , = [ ] { }} and the space character are 
percent-encoded so
+     * that a value can never be confused with the structure around it.
+     */
     public static String tokenizeString(String str) {
-        return str != null ? str : " ";
+        if (str == null) {
+            return " ";
+        }
+        StringBuilder sb = new StringBuilder(str.length());
+        for (int i = 0; i < str.length(); i++) {
+            char c = str.charAt(i);
+            if (ESCAPED_CHARS.indexOf(c) >= 0) {
+                sb.append('%').append(HEX_DIGITS.charAt(c >> 
4)).append(HEX_DIGITS.charAt(c & 0xF));
+            } else {
+                sb.append(c);
+            }
+        }
+        return sb.toString();
+    }
+
+    private static String unescape(String str) {
+        if (str.indexOf('%') < 0) {
+            return str;
+        }
+        StringBuilder sb = new StringBuilder(str.length());
+        for (int i = 0; i < str.length(); i++) {
+            char c = str.charAt(i);
+            if (c == '%') {
+                int hi = i + 2 < str.length() ? 
HEX_DIGITS.indexOf(str.charAt(i + 1)) : -1;
+                int lo = hi >= 0 ? HEX_DIGITS.indexOf(str.charAt(i + 2)) : -1;
+                if (lo < 0) {
+                    throw new SecurityException("Invalid escape sequence");
+                }
+                c = (char)((hi << 4) | lo);
+                i += 2;
+            }
+            sb.append(c);
+        }
+        return sb.toString();
+    }
+
+    private static String tokenizeList(List<String> list) {
+        StringBuilder sb = new StringBuilder("[");
+        boolean first = true;
+        for (String value : list) {
+            if (!first) {
+                sb.append(',');
+            }
+            first = false;
+            sb.append(tokenizeString(value));
+        }
+        return sb.append(']').toString();
+    }
+
+    /**
+     * Writes a map as {@code {key=value,key=value}}, with each key and value 
written by
+     * {@link #tokenizeString(String)}.
+     */
+    public static String tokenizeMap(Map<String, String> map) {
+        StringBuilder sb = new StringBuilder("{");
+        for (Map.Entry<String, String> entry : map.entrySet()) {
+            if (sb.length() > 1) {
+                sb.append(',');
+            }
+            
sb.append(tokenizeString(entry.getKey())).append('=').append(tokenizeString(entry.getValue()));
+        }
+        return sb.append('}').toString();
     }
 }
diff --git 
a/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/provider/JoseSessionTokenProviderTest.java
 
b/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/provider/JoseSessionTokenProviderTest.java
new file mode 100644
index 00000000000..1d9db9d918d
--- /dev/null
+++ 
b/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/provider/JoseSessionTokenProviderTest.java
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.cxf.rs.security.oauth2.provider;
+
+import java.util.Collections;
+
+import org.apache.cxf.rs.security.oauth2.common.OAuthRedirectionState;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+public class JoseSessionTokenProviderTest {
+
+    private final JoseSessionTokenProvider provider = new 
JoseSessionTokenProvider();
+
+    @Test
+    public void testStateRoundTripWithSeparatorCharacters() {
+        OAuthRedirectionState state = new OAuthRedirectionState();
+        state.setClientId("client");
+        state.setClientCodeChallenge("x|evil-scope|https://evil";);
+        state.setState("a|b.c,d=e{f}[g]%h");
+        state.setProposedScope("read");
+        state.setRedirectUri("https://client/cb?a=1,2";);
+        state.setResponseType("code");
+        state.setExtraProperties(Collections.singletonMap("k=1", "v|2"));
+        state.setClientCodeChallengeMethod("plain");
+
+        OAuthRedirectionState state2 =
+            
provider.convertStateStringToState(provider.convertStateToString(state));
+
+        assertEquals("client", state2.getClientId());
+        assertNull(state2.getAudience());
+        assertEquals("x|evil-scope|https://evil";, 
state2.getClientCodeChallenge());
+        assertEquals("a|b.c,d=e{f}[g]%h", state2.getState());
+        assertEquals("read", state2.getProposedScope());
+        assertEquals("https://client/cb?a=1,2";, state2.getRedirectUri());
+        assertNull(state2.getNonce());
+        assertEquals("code", state2.getResponseType());
+        assertEquals(Collections.singletonMap("k=1", "v|2"), 
state2.getExtraProperties());
+        assertEquals("plain", state2.getClientCodeChallengeMethod());
+    }
+}
diff --git 
a/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/utils/crypto/CryptoUtilsTest.java
 
b/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/utils/crypto/CryptoUtilsTest.java
index d457079b9d6..2f4be184ead 100644
--- 
a/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/utils/crypto/CryptoUtilsTest.java
+++ 
b/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/utils/crypto/CryptoUtilsTest.java
@@ -25,6 +25,7 @@ import java.security.KeyPair;
 import java.security.KeyPairGenerator;
 import java.security.PrivateKey;
 import java.security.PublicKey;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 
@@ -162,6 +163,114 @@ public class CryptoUtilsTest {
         compareAccessTokens(token, decryptedWithEncodedKey);
     }
 
+    @Test
+    public void testSubjectWithSeparatorCharactersRoundTrip() throws Exception 
{
+        String[] logins = {"admin.x", "[email protected]", "bob. .[admin]", 
"a|b", "100%", "c=d,e{f}", " ", ""};
+        for (String login : logins) {
+            AccessTokenRegistration atr = prepareTokenRegistration();
+            UserSubject subject = new UserSubject(login, "id.1|2");
+            subject.setRoles(Arrays.asList("role,1", "role.2"));
+            subject.setProperties(Collections.singletonMap("k=1", "v,2"));
+            atr.setSubject(subject);
+
+            ServerAccessToken token = p.createAccessToken(atr);
+            ServerAccessToken token2 = p.getAccessToken(token.getTokenKey());
+
+            assertEquals(login, token2.getSubject().getLogin());
+            assertEquals("id.1|2", token2.getSubject().getId());
+            assertEquals(Arrays.asList("role,1", "role.2"), 
token2.getSubject().getRoles());
+            assertEquals(Collections.singletonMap("k=1", "v,2"), 
token2.getSubject().getProperties());
+        }
+    }
+
+    @Test
+    public void testCodeGrantChallengeCannotReplaceSubject() throws Exception {
+        Client c = p.getClient("1");
+        ServerAuthorizationCodeGrant grant = new 
ServerAuthorizationCodeGrant(c, "code", 60, 100);
+        grant.setSubject(new UserSubject("alice", "aliceId"));
+        grant.setClientCodeChallenge("x|[]|admin. .[admin].{}|{}");
+        grant.setRedirectUri("https://client/cb?a=1&b=%20,|");
+        grant.setApprovedScopes(Arrays.asList("read", "a,b"));
+
+        String encrypted = ModelEncryptionSupport.encryptCodeGrant(grant, 
p.key);
+        ServerAuthorizationCodeGrant grant2 = 
ModelEncryptionSupport.decryptCodeGrant(p, encrypted, p.key);
+
+        assertEquals("alice", grant2.getSubject().getLogin());
+        assertEquals("aliceId", grant2.getSubject().getId());
+        assertTrue(grant2.getSubject().getRoles().isEmpty());
+        assertEquals("x|[]|admin. .[admin].{}|{}", 
grant2.getClientCodeChallenge());
+        assertEquals("https://client/cb?a=1&b=%20,|", grant2.getRedirectUri());
+        assertEquals(Arrays.asList("read", "a,b"), grant2.getApprovedScopes());
+        assertTrue(grant2.getExtraProperties().isEmpty());
+    }
+
+    @Test
+    public void testClientWithSeparatorCharactersRoundTrip() throws Exception {
+        Client c = new Client("client.1", "secret|x", true, "My App, v1", 
"https://app/?q=%41";);
+        c.setRedirectUris(Arrays.asList("https://app/cb?a=1,2";, 
"https://app/cb2";));
+        c.setRegisteredScopes(Arrays.asList("read", "write"));
+        c.setProperties(Collections.singletonMap("key", "a=b"));
+        c.setSubject(new UserSubject("owner.name", "ownerId"));
+
+        Client c2 = 
ModelEncryptionSupport.decryptClient(ModelEncryptionSupport.encryptClient(c, 
p.key), p.key);
+
+        assertEquals("client.1", c2.getClientId());
+        assertEquals("secret|x", c2.getClientSecret());
+        assertEquals("My App, v1", c2.getApplicationName());
+        assertEquals("https://app/?q=%41";, c2.getApplicationWebUri());
+        assertEquals(Arrays.asList("https://app/cb?a=1,2";, "https://app/cb2";), 
c2.getRedirectUris());
+        assertEquals(Arrays.asList("read", "write"), c2.getRegisteredScopes());
+        assertEquals(Collections.singletonMap("key", "a=b"), 
c2.getProperties());
+        assertEquals("owner.name", c2.getSubject().getLogin());
+    }
+
+    @Test
+    public void testMultiplePermissionsRoundTrip() throws Exception {
+        AccessTokenRegistration atr = prepareTokenRegistration();
+        BearerAccessToken token = p.createAccessTokenInternal(atr);
+        OAuthPermission read = new OAuthPermission("read", "read. permission");
+        read.setHttpVerbs(Collections.singletonList("GET"));
+        OAuthPermission write = new OAuthPermission("write", "write 
permission");
+        write.setDefaultPermission(true);
+        write.setUris(Arrays.asList("/a", "/b,c"));
+        token.setScopes(Arrays.asList(read, write));
+
+        String encrypted = ModelEncryptionSupport.encryptAccessToken(token, 
p.key);
+        List<OAuthPermission> perms = 
ModelEncryptionSupport.decryptAccessToken(p, encrypted, p.key).getScopes();
+
+        assertEquals(2, perms.size());
+        assertEquals("read", perms.get(0).getPermission());
+        assertEquals("read. permission", perms.get(0).getDescription());
+        assertEquals(Collections.singletonList("GET"), 
perms.get(0).getHttpVerbs());
+        assertEquals("write", perms.get(1).getPermission());
+        assertTrue(perms.get(1).isDefaultPermission());
+        assertEquals(Arrays.asList("/a", "/b,c"), perms.get(1).getUris());
+    }
+
+    @Test
+    public void testTokenizeString() {
+        assertEquals("admin%2Ex", 
ModelEncryptionSupport.tokenizeString("admin.x"));
+        assertEquals("%25%7C%2E%2C%3D%5B%5D%7B%7D%20", 
ModelEncryptionSupport.tokenizeString("%|.,=[]{} "));
+        assertEquals(" ", ModelEncryptionSupport.tokenizeString(null));
+        assertNull(ModelEncryptionSupport.getStringPart(" "));
+        assertEquals("%|.,=[]{} ", 
ModelEncryptionSupport.getStringPart("%25%7C%2E%2C%3D%5B%5D%7B%7D%20"));
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testInvalidEscapeSequenceIsRejected() {
+        ModelEncryptionSupport.getStringPart("admin%2");
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testUnexpectedPartCountIsRejected() {
+        ModelEncryptionSupport.recreateCodeGrant(p, "1|code|60|100| | | 
|[]|alice.aliceId.[].{}|{}|extra");
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testInvalidSubjectIsRejected() {
+        ModelEncryptionSupport.recreateCodeGrant(p, "1|code|60|100| | | 
|[]|admin.x.aliceId.[].{}|{}");
+    }
+
     @Test
     public void testBearerTokenJSON() throws Exception {
         AccessTokenRegistration atr = prepareTokenRegistration();

Reply via email to