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

roryqi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new a67ec11df7 [#14427] fix(auth): Activate non-ASCII role names via 
X-Gravitino-Active-Roles (#14515)
a67ec11df7 is described below

commit a67ec11df75b356bfc364bf584b538a5037a5dd4
Author: Bharath Krishna <[email protected]>
AuthorDate: Sun Nov 8 17:58:35 2026 -0800

    [#14427] fix(auth): Activate non-ASCII role names via 
X-Gravitino-Active-Roles (#14515)
    
    ### What changes were proposed in this pull request?
    
    `ActiveRolesParser` decodes role names in `X-Gravitino-Active-Roles`:
    
    - Re-reads the header bytes as UTF-8, so raw UTF-8 names match.
    - Percent-decodes each role name (`vrf_%E8%A7%92%E8%89%B2` → `vrf_角色`),
    after splitting and keyword matching.
    - Rejects malformed escapes, invalid UTF-8, and blank or
    control-character names with 400.
    
    Docs updated in `docs/security/access-control.md`.
    
    ### Why are the changes needed?
    
    Jetty decodes header bytes as ISO-8859-1, so non-Latin-1 role names
    never matched. Common clients (Apache HttpClient 5, used by Spark/Trino
    and the Java client; Python `http.client`) cannot send such values raw,
    so an ASCII-only form is needed.
    
    Fixes #14427
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for the unreleased header: role names may be percent-encoded UTF-8
    (a literal `%` is `%25`), and non-UTF-8 values return 400.
    
    ### How was this patch tested?
    
    Unit tests in `TestActiveRolesParser` and `TestAuthenticationFilter`; a
    new case in `RoleAssumptionAuthorizationIT`.
---
 .../RoleAssumptionAuthorizationIT.java             |  19 ++-
 .../apache/gravitino/auth/ActiveRolesParser.java   | 138 ++++++++++++++++++---
 .../gravitino/auth/TestActiveRolesParser.java      | 107 ++++++++++++++++
 design-docs/gravitino-role-assumption.md           |   9 +-
 docs/lance-rest-service.md                         |   4 +-
 docs/security/access-control.md                    |  22 ++++
 .../authentication/TestAuthenticationFilter.java   |  50 ++++++++
 7 files changed, 327 insertions(+), 22 deletions(-)

diff --git 
a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/RoleAssumptionAuthorizationIT.java
 
b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/RoleAssumptionAuthorizationIT.java
index 31b4a03075..9a941a4f15 100644
--- 
a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/RoleAssumptionAuthorizationIT.java
+++ 
b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/authorization/RoleAssumptionAuthorizationIT.java
@@ -48,8 +48,8 @@ import org.junit.jupiter.api.Test;
  * Integration test for role assumption via the {@code 
X-Gravitino-Active-Roles} header. The test
  * user holds two roles, each granting {@code USE_CATALOG} on a different 
catalog, and the header
  * activates a subset of them per request. Covers the default {@code ALL}, a 
narrowed {@code NAMED}
- * subset (one role and several), {@code NONE}, a {@code 403} for an unheld 
role, and a {@code 400}
- * for a malformed header.
+ * subset (one role and several), a non-ASCII role name sent percent-encoded, 
{@code NONE}, a {@code
+ * 403} for an unheld role, and a {@code 400} for a malformed header.
  */
 @Tag("gravitino-docker-test")
 public class RoleAssumptionAuthorizationIT extends BaseRestApiAuthorizationIT {
@@ -59,6 +59,9 @@ public class RoleAssumptionAuthorizationIT extends 
BaseRestApiAuthorizationIT {
   private static final String ROLE_CATALOG1 = "role_catalog1";
   private static final String ROLE_CATALOG2 = "role_catalog2";
   private static final String UNHELD_ROLE = "role_not_held";
+  // A CJK role name; the Java client cannot send it raw, so it is activated 
percent-encoded.
+  private static final String ROLE_NON_ASCII = "role_角色";
+  private static final String ROLE_NON_ASCII_ENCODED = 
"role_%E8%A7%92%E8%89%B2";
 
   @BeforeAll
   public void startIntegrationTest() throws Exception {
@@ -75,7 +78,9 @@ public class RoleAssumptionAuthorizationIT extends 
BaseRestApiAuthorizationIT {
         SecurableObjects.ofCatalog(CATALOG2, 
ImmutableList.of(Privileges.UseCatalog.allow()));
     admin.createRole(ROLE_CATALOG1, new HashMap<>(), 
ImmutableList.of(useCatalog1));
     admin.createRole(ROLE_CATALOG2, new HashMap<>(), 
ImmutableList.of(useCatalog2));
-    admin.grantRolesToUser(ImmutableList.of(ROLE_CATALOG1, ROLE_CATALOG2), 
NORMAL_USER);
+    admin.createRole(ROLE_NON_ASCII, new HashMap<>(), 
ImmutableList.of(useCatalog1));
+    admin.grantRolesToUser(
+        ImmutableList.of(ROLE_CATALOG1, ROLE_CATALOG2, ROLE_NON_ASCII), 
NORMAL_USER);
   }
 
   /** Builds a client for {@link #NORMAL_USER} that sends the given 
active-roles header value. */
@@ -121,6 +126,14 @@ public class RoleAssumptionAuthorizationIT extends 
BaseRestApiAuthorizationIT {
     }
   }
 
+  @Test
+  public void testNarrowToPercentEncodedNonAsciiRole() {
+    // A percent-encoded UTF-8 role name activates the role with the decoded 
name.
+    try (GravitinoAdminClient nonAscii = 
userClientWithActiveRoles(ROLE_NON_ASCII_ENCODED)) {
+      assertArrayEquals(new String[] {CATALOG1}, sortedCatalogs(nonAscii));
+    }
+  }
+
   @Test
   public void testNoneActivatesNothing() {
     // NONE activates no role, so no catalog is visible.
diff --git 
a/common/src/main/java/org/apache/gravitino/auth/ActiveRolesParser.java 
b/common/src/main/java/org/apache/gravitino/auth/ActiveRolesParser.java
index 8268321142..41acb5cf52 100644
--- a/common/src/main/java/org/apache/gravitino/auth/ActiveRolesParser.java
+++ b/common/src/main/java/org/apache/gravitino/auth/ActiveRolesParser.java
@@ -19,9 +19,15 @@
 
 package org.apache.gravitino.auth;
 
+import java.io.ByteArrayOutputStream;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
 import java.util.LinkedHashSet;
 import java.util.Set;
 import javax.annotation.Nullable;
+import org.apache.commons.lang3.StringUtils;
 
 /**
  * Parses the {@link AuthConstants#X_GRAVITINO_ACTIVE_ROLES_HEADER} header 
value into an {@link
@@ -38,7 +44,14 @@ import javax.annotation.Nullable;
  *
  * <p>Entries are trimmed and de-duplicated, and role names are 
case-sensitive. {@code ALL} and
  * {@code NONE} are reserved keywords, matched exactly in upper case, and each 
must appear on its
- * own, so a role literally named {@code ALL} or {@code NONE} cannot be 
activated by name.
+ * own.
+ *
+ * <p>The value is read as UTF-8, and each role name may be percent-encoded 
({@code %XX} over its
+ * UTF-8 bytes), because many HTTP clients cannot send non-ASCII header 
values. Entries are split
+ * and keywords matched before decoding, so {@code a%2Cb} names the single 
role {@code a,b} and
+ * {@code %41LL} names a role literally called {@code ALL}. {@code +} is not 
decoded as a space, and
+ * trimming happens before decoding, so an encoded space is part of the name. 
A name that is blank
+ * or contains a control character after decoding is rejected.
  *
  * <p>This performs syntactic validation only. Checking that the caller 
actually holds a named role
  * happens later on the server.
@@ -56,16 +69,19 @@ public final class ActiveRolesParser {
   /**
    * Parses a raw header value into an {@link ActiveRoles} declaration.
    *
-   * @param rawValue the raw header value, or {@code null} when the header is 
absent
+   * @param rawValue the raw header value as exposed by the servlet container, 
or {@code null} when
+   *     the header is absent
    * @return the parsed declaration
-   * @throws IllegalActiveRolesException if the value is syntactically invalid 
(an empty entry, or a
-   *     reserved keyword combined with any other value)
+   * @throws IllegalActiveRolesException if the value is syntactically invalid 
(an empty entry, a
+   *     reserved keyword combined with any other value, a malformed 
percent-escape, bytes that are
+   *     not valid UTF-8, or a role name that is blank or has a control 
character after decoding)
    */
   public static ActiveRoles parse(@Nullable String rawValue) {
     if (rawValue == null) {
       return ActiveRoles.all();
     }
-    String trimmed = rawValue.trim();
+    String value = recoverUtf8(rawValue);
+    String trimmed = value.trim();
     if (trimmed.isEmpty()) {
       return ActiveRoles.all();
     }
@@ -79,19 +95,14 @@ public final class ActiveRolesParser {
     for (String part : parts) {
       String token = part.trim();
       if (token.isEmpty()) {
-        throw new IllegalActiveRolesException(
-            "Invalid '"
-                + AuthConstants.X_GRAVITINO_ACTIVE_ROLES_HEADER
-                + "' header: empty role entry in value '"
-                + rawValue
-                + "'");
+        throw invalid("empty role entry in value '" + value + "'");
       }
       if (ALL_KEYWORD.equals(token)) {
         sawAll = true;
       } else if (NONE_KEYWORD.equals(token)) {
         sawNone = true;
       } else {
-        names.add(token);
+        names.add(checkRoleName(decodeRoleName(token, value), value));
       }
     }
 
@@ -99,15 +110,13 @@ public final class ActiveRolesParser {
     // keyword is valid only when it is the single entry.
     boolean sawReserved = sawAll || sawNone;
     if (sawReserved && parts.length > 1) {
-      throw new IllegalActiveRolesException(
-          "Invalid '"
-              + AuthConstants.X_GRAVITINO_ACTIVE_ROLES_HEADER
-              + "' header: reserved keyword "
+      throw invalid(
+          "reserved keyword "
               + ALL_KEYWORD
               + "/"
               + NONE_KEYWORD
               + " must appear alone in value '"
-              + rawValue
+              + value
               + "'");
     }
 
@@ -119,4 +128,99 @@ public final class ActiveRolesParser {
     }
     return ActiveRoles.of(names);
   }
+
+  // Servlet containers such as Jetty expose each header byte as one 
ISO-8859-1 char. Re-read those
+  // bytes as UTF-8 so a role name sent as raw UTF-8 matches. A value holding 
a char above U+00FF
+  // was already decoded by the container and is kept as is.
+  private static String recoverUtf8(String rawValue) {
+    boolean hasNonAscii = false;
+    for (int i = 0; i < rawValue.length(); i++) {
+      char c = rawValue.charAt(i);
+      if (c > 0xFF) {
+        return rawValue;
+      }
+      hasNonAscii |= c >= 0x80;
+    }
+    return hasNonAscii
+        ? decodeUtf8(rawValue.getBytes(StandardCharsets.ISO_8859_1), rawValue)
+        : rawValue;
+  }
+
+  private static String decodeRoleName(String token, String value) {
+    if (token.indexOf('%') < 0) {
+      return token;
+    }
+    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+    int i = 0;
+    while (i < token.length()) {
+      if (token.charAt(i) == '%') {
+        bytes.write(decodeEscape(token, i, value));
+        i += 3;
+        continue;
+      }
+      int next = token.indexOf('%', i);
+      int end = next < 0 ? token.length() : next;
+      byte[] literal = token.substring(i, 
end).getBytes(StandardCharsets.UTF_8);
+      bytes.write(literal, 0, literal.length);
+      i = end;
+    }
+    return decodeUtf8(bytes.toByteArray(), value);
+  }
+
+  // Decoding can produce names the raw header could not carry: reject blank 
names (e.g. "%20" or
+  // Unicode spaces, matching role creation) here so they get a 400, and 
control characters so a
+  // name cannot forge lines in logs.
+  private static String checkRoleName(String name, String value) {
+    if (StringUtils.isBlank(name)) {
+      throw invalid("empty role entry in value '" + value + "'");
+    }
+    if (name.chars().anyMatch(Character::isISOControl)) {
+      throw invalid("control character in a role name in value '" + value + 
"'");
+    }
+    return name;
+  }
+
+  private static int decodeEscape(String token, int index, String value) {
+    int high = index + 2 < token.length() ? hexValue(token.charAt(index + 1)) 
: -1;
+    int low = high >= 0 ? hexValue(token.charAt(index + 2)) : -1;
+    if (low < 0) {
+      throw invalid("malformed percent-escape in value '" + value + "'");
+    }
+    return (high << 4) | low;
+  }
+
+  // Only ASCII hex digits are accepted; Character.digit would also accept 
non-ASCII digits.
+  private static int hexValue(char c) {
+    if (c >= '0' && c <= '9') {
+      return c - '0';
+    }
+    if (c >= 'a' && c <= 'f') {
+      return c - 'a' + 10;
+    }
+    if (c >= 'A' && c <= 'F') {
+      return c - 'A' + 10;
+    }
+    return -1;
+  }
+
+  private static String decodeUtf8(byte[] bytes, String value) {
+    try {
+      return StandardCharsets.UTF_8
+          .newDecoder()
+          .onMalformedInput(CodingErrorAction.REPORT)
+          .onUnmappableCharacter(CodingErrorAction.REPORT)
+          .decode(ByteBuffer.wrap(bytes))
+          .toString();
+    } catch (CharacterCodingException e) {
+      throw invalid(
+          "value '"
+              + value
+              + "' is not valid UTF-8; percent-encode the UTF-8 bytes of 
non-ASCII role names");
+    }
+  }
+
+  private static IllegalActiveRolesException invalid(String detail) {
+    return new IllegalActiveRolesException(
+        "Invalid '" + AuthConstants.X_GRAVITINO_ACTIVE_ROLES_HEADER + "' 
header: " + detail);
+  }
 }
diff --git 
a/common/src/test/java/org/apache/gravitino/auth/TestActiveRolesParser.java 
b/common/src/test/java/org/apache/gravitino/auth/TestActiveRolesParser.java
index 6e1716966a..1fbb45089e 100644
--- a/common/src/test/java/org/apache/gravitino/auth/TestActiveRolesParser.java
+++ b/common/src/test/java/org/apache/gravitino/auth/TestActiveRolesParser.java
@@ -24,6 +24,7 @@ import static 
org.junit.jupiter.api.Assertions.assertIterableEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import java.util.Collections;
 import org.apache.gravitino.auth.ActiveRoles.Mode;
@@ -119,4 +120,110 @@ public class TestActiveRolesParser {
     // The server maps this to 400 Bad Request, so it must remain an 
IllegalArgumentException.
     assertThrows(IllegalArgumentException.class, () -> 
ActiveRolesParser.parse("analyst,"));
   }
+
+  @Test
+  public void testPercentEncodedUtf8RoleName() {
+    ActiveRoles roles = ActiveRolesParser.parse("vrf_%E8%A7%92%E8%89%B2");
+    assertIterableEquals(Collections.singletonList("vrf_\u89d2\u8272"), 
roles.roleNames());
+  }
+
+  @Test
+  public void testPercentEncodingIsCaseInsensitiveAndAppliesPerEntry() {
+    ActiveRoles roles = ActiveRolesParser.parse("vrf_%e8%a7%92%e8%89%b2, 
r%C3%B4le");
+    assertIterableEquals(Arrays.asList("vrf_\u89d2\u8272", "r\u00f4le"), 
roles.roleNames());
+  }
+
+  @Test
+  public void testEncodedCommaAndPercentAreLiteral() {
+    // Entries are split before decoding, so %2C is part of a single role name.
+    ActiveRoles roles = ActiveRolesParser.parse("a%2Cb,100%25");
+    assertIterableEquals(Arrays.asList("a,b", "100%"), roles.roleNames());
+  }
+
+  @Test
+  public void testPlusIsNotDecodedAsSpace() {
+    ActiveRoles roles = ActiveRolesParser.parse("a+b");
+    assertIterableEquals(Collections.singletonList("a+b"), roles.roleNames());
+  }
+
+  @Test
+  public void testEncodedKeywordIsARoleName() {
+    // Keywords are matched before decoding, so an encoded form names a role 
literally called ALL.
+    ActiveRoles roles = ActiveRolesParser.parse("%41LL");
+    assertEquals(Mode.NAMED, roles.mode());
+    assertIterableEquals(Collections.singletonList("ALL"), roles.roleNames());
+  }
+
+  @Test
+  public void testDuplicatesCollapseAfterDecoding() {
+    ActiveRoles roles = ActiveRolesParser.parse("a, %61");
+    assertIterableEquals(Collections.singletonList("a"), roles.roleNames());
+  }
+
+  @Test
+  public void testEncodedWhitespaceIsPartOfTheName() {
+    // Trimming happens before decoding, so an encoded space is significant.
+    ActiveRoles roles = ActiveRolesParser.parse(" %20a ");
+    assertIterableEquals(Collections.singletonList(" a"), roles.roleNames());
+  }
+
+  @Test
+  public void testEncodedNoneIsARoleNameAndKeywordsStillMustBeAlone() {
+    assertIterableEquals(
+        Collections.singletonList("NONE"), 
ActiveRolesParser.parse("%4EONE").roleNames());
+    assertThrows(IllegalActiveRolesException.class, () -> 
ActiveRolesParser.parse("ALL,%41LL"));
+  }
+
+  @Test
+  public void testRawUtf8BytesDecodedAsLatin1AreRecovered() {
+    // Jetty exposes each header byte as one ISO-8859-1 char; raw UTF-8 must 
still resolve.
+    String asReceived =
+        new String(
+            "vrf_\u89d2\u8272".getBytes(StandardCharsets.UTF_8), 
StandardCharsets.ISO_8859_1);
+    ActiveRoles roles = ActiveRolesParser.parse(asReceived);
+    assertIterableEquals(Collections.singletonList("vrf_\u89d2\u8272"), 
roles.roleNames());
+  }
+
+  @Test
+  public void testSupplementaryCharacterInRawAndPercentForms() {
+    String name = "r\ud83d\ude00"; // U+1F600, four UTF-8 bytes
+    String raw = new String(name.getBytes(StandardCharsets.UTF_8), 
StandardCharsets.ISO_8859_1);
+    assertIterableEquals(Collections.singletonList(name), 
ActiveRolesParser.parse(raw).roleNames());
+    assertIterableEquals(
+        Collections.singletonList(name), 
ActiveRolesParser.parse("r%F0%9F%98%80").roleNames());
+  }
+
+  @Test
+  public void testControlCharacterFromRawUtf8IsRejected() {
+    // U+0085 (NEL) sent as raw UTF-8 bytes C2 85 is a control character, like 
%0A.
+    String raw =
+        new String(new byte[] {'x', (byte) 0xC2, (byte) 0x85}, 
StandardCharsets.ISO_8859_1);
+    assertThrows(IllegalActiveRolesException.class, () -> 
ActiveRolesParser.parse(raw));
+  }
+
+  @Test
+  public void testAlreadyDecodedUnicodeIsKeptAsIs() {
+    ActiveRoles roles = ActiveRolesParser.parse("vrf_\u89d2\u8272");
+    assertIterableEquals(Collections.singletonList("vrf_\u89d2\u8272"), 
roles.roleNames());
+  }
+
+  @ParameterizedTest
+  @ValueSource(
+      strings = {
+        "a%", // truncated escape
+        "a%4", // truncated escape
+        "a%G1", // non-hex escape
+        "vrf_%E8%A7", // truncated UTF-8 sequence
+        "%FF", // invalid UTF-8 byte
+        "vrf_r\u00f4le", // raw Latin-1 byte 0xF4 is not valid UTF-8
+        "%20", // blank after decoding
+        "a,%09", // blank after decoding
+        "%E2%80%83", // Unicode whitespace (U+2003) only after decoding
+        "%00", // control character
+        "x%0Aforged", // control character
+        "x%7F" // control character
+      })
+  public void testInvalidEncodingThrows(String value) {
+    assertThrows(IllegalActiveRolesException.class, () -> 
ActiveRolesParser.parse(value));
+  }
 }
diff --git a/design-docs/gravitino-role-assumption.md 
b/design-docs/gravitino-role-assumption.md
index 1f8d39cce7..a4b6f014ec 100644
--- a/design-docs/gravitino-role-assumption.md
+++ b/design-docs/gravitino-role-assumption.md
@@ -117,6 +117,11 @@ Here `analyst` and `reader` are example role names, not 
keywords; only `ALL` and
 This mirrors the vocabulary users already know from Hive (`SET ROLE role | ALL 
| NONE`) and Snowflake
 (`USE SECONDARY ROLES ALL | NONE`).
 
+The value is read as UTF-8, and each comma-separated role name may be 
percent-encoded (`%XX` over its
+UTF-8 bytes). Common clients such as Apache HttpClient cannot send non-ASCII 
header values, so
+percent-encoding is the portable way to name a role containing non-ASCII 
characters, a comma, or `%`.
+Keywords are matched before decoding.
+
 `NONE` is the only way to express the *empty* active set. An absent header 
already means `ALL`, so
 without an explicit keyword there is no way to declare "use none of my roles" 
— running with only
 ownership/baseline access. That mode is genuinely useful: owner-only execution 
for a job or agent that
@@ -155,7 +160,9 @@ classes:
 
 - **Malformed value → `400 Bad Request`.** The value is syntactically invalid 
— an empty entry (e.g. a
   trailing comma `analyst,`), a reserved keyword combined with anything else 
(`ALL,analyst`,
-  `NONE,reader`, `ALL,NONE`), or an unrecognized keyword. `ALL` and `NONE` are 
exclusive: each must
+  `NONE,reader`, `ALL,NONE`), a malformed percent-escape or bytes that are not 
UTF-8, a role name
+  that is blank or has a control character after decoding, or an unrecognized 
keyword. `ALL` and
+  `NONE` are exclusive: each must
   appear alone. Surrounding whitespace is trimmed and duplicate names 
collapse, so `analyst, analyst `
   is fine; role names are matched exactly (case-sensitive), since that's how 
they're stored.
 - **Unauthorized role → `403 Forbidden`.** The value is well-formed but names 
a role the caller does not
diff --git a/docs/lance-rest-service.md b/docs/lance-rest-service.md
index 8e0dba3fb6..e67be78e35 100644
--- a/docs/lance-rest-service.md
+++ b/docs/lance-rest-service.md
@@ -365,7 +365,9 @@ a one-level namespace identifies a catalog, a two-level 
namespace identifies a s
 three-level table identifier identifies a table.
 
 Requests may set `X-Gravitino-Active-Roles` to `ALL` (also the default when 
omitted), `NONE`, or
-a comma-separated list of assigned role names. This selection reaches both 
operation checks
+a comma-separated list of assigned role names; see
+[Role Names Outside 
ASCII](./security/access-control.md#role-names-outside-ascii) for names with
+non-ASCII characters. This selection reaches both operation checks
 and listing filters. Malformed selections return `400`; selecting an 
unassigned role is forbidden.
 Ownership is independent of role selection, so `NONE` does not remove 
ownership privileges.
 
diff --git a/docs/security/access-control.md b/docs/security/access-control.md
index d1f1725539..bff258eba8 100755
--- a/docs/security/access-control.md
+++ b/docs/security/access-control.md
@@ -459,6 +459,26 @@ X-Gravitino-Active-Roles: analyst,reader
 Role names are matched exactly, and `ALL` and `NONE` are recognized only in 
upper case, so `all` is
 read as the name of a role. Surrounding whitespace is trimmed and repeated 
names collapse.
 
+### Role Names Outside ASCII
+
+Many HTTP clients cannot send non-ASCII header values: the Apache HttpClient 
used by Spark, Trino and
+the Gravitino Java client replaces such characters with `?`. To activate a 
role whose name contains
+non-ASCII characters, a comma, or `%`, percent-encode the UTF-8 bytes of the 
name:
+
+```text
+X-Gravitino-Active-Roles: vrf_%E8%A7%92%E8%89%B2
+```
+
+This activates the role `vrf_角色`. Each comma-separated entry is decoded on its 
own, so `a%2Cb`
+names the single role `a,b`, and a literal `%` is sent as `%25`. `+` is not 
decoded as a space, and
+whitespace is trimmed before decoding, so an encoded space such as `%20` is 
part of the name. `ALL`
+and `NONE` are matched before decoding, so `%41LL` and `%4EONE` name roles 
literally called `ALL` and
+`NONE`.
+
+A client that sends raw UTF-8 bytes, such as `curl`, can also send the name 
unencoded, as long as it
+contains no `,` or `%`. A header value is always read as UTF-8, so bytes in 
another encoding, such as
+ISO-8859-1, are rejected.
+
 ### What Narrowing Changes
 
 Narrowing only ever subtracts. The server validates the declaration against 
the roles the caller
@@ -480,6 +500,8 @@ as before.
 
|--------------------------------------------------------------------|-------------------|
 | An empty entry, such as the trailing comma in `analyst,`           | `400 
Bad Request` |
 | `ALL` or `NONE` combined with anything else, such as `ALL,analyst` | `400 
Bad Request` |
+| A malformed escape, such as `%G1`, or a value that is not UTF-8    | `400 
Bad Request` |
+| A name that is blank or has a control character after decoding     | `400 
Bad Request` |
 | A well-formed value naming a role the caller does not hold         | `403 
Forbidden`   |
 
 A role that does not exist and a role the caller was never granted both return 
`403`, so the response
diff --git 
a/server-common/src/test/java/org/apache/gravitino/server/authentication/TestAuthenticationFilter.java
 
b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestAuthenticationFilter.java
index 7aaa9fcc99..7ad14bb5fb 100644
--- 
a/server-common/src/test/java/org/apache/gravitino/server/authentication/TestAuthenticationFilter.java
+++ 
b/server-common/src/test/java/org/apache/gravitino/server/authentication/TestAuthenticationFilter.java
@@ -33,6 +33,7 @@ import com.google.common.collect.Lists;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
 import java.security.Principal;
 import java.util.Arrays;
 import java.util.Collections;
@@ -111,6 +112,55 @@ public class TestAuthenticationFilter {
         ((UserPrincipal) seenDuringChain.get()).getActiveRoles());
   }
 
+  @Test
+  public void testDoFilterRejectsBlankEncodedActiveRoleWith400() throws 
Exception {
+    Authenticator authenticator = mock(Authenticator.class);
+    AuthenticationFilter filter = new 
AuthenticationFilter(Lists.newArrayList(authenticator));
+    FilterChain mockChain = mock(FilterChain.class);
+    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
+    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
+    when(mockRequest.getHeaders(AuthConstants.HTTP_HEADER_AUTHORIZATION))
+        .thenReturn(new 
Vector<>(Collections.singletonList("user")).elements());
+    
when(mockRequest.getHeader(AuthConstants.X_GRAVITINO_ACTIVE_ROLES_HEADER)).thenReturn("%20");
+    when(authenticator.supportsToken(any())).thenReturn(true);
+    when(authenticator.isDataFromToken()).thenReturn(true);
+    when(authenticator.authenticateToken(any())).thenReturn(new 
UserPrincipal("user"));
+    StringWriter body = new StringWriter();
+    when(mockResponse.getWriter()).thenReturn(new PrintWriter(body));
+
+    filter.doFilter(mockRequest, mockResponse, mockChain);
+
+    verify(mockResponse).setStatus(HttpServletResponse.SC_BAD_REQUEST);
+    verify(mockChain, never()).doFilter(any(), any());
+  }
+
+  @Test
+  public void testDoFilterDecodesNonAsciiActiveRoles() throws 
ServletException, IOException {
+    Authenticator authenticator = mock(Authenticator.class);
+    AuthenticationFilter filter = new 
AuthenticationFilter(Lists.newArrayList(authenticator));
+    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
+    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
+    when(mockRequest.getHeaders(AuthConstants.HTTP_HEADER_AUTHORIZATION))
+        .thenReturn(new 
Vector<>(Collections.singletonList("user")).elements());
+    // Jetty exposes raw UTF-8 header bytes as ISO-8859-1 chars.
+    String rawUtf8 =
+        new String("vrf_角色".getBytes(StandardCharsets.UTF_8), 
StandardCharsets.ISO_8859_1);
+    when(mockRequest.getHeader(AuthConstants.X_GRAVITINO_ACTIVE_ROLES_HEADER))
+        .thenReturn(rawUtf8 + ",r%C3%B4le");
+    when(authenticator.supportsToken(any())).thenReturn(true);
+    when(authenticator.isDataFromToken()).thenReturn(true);
+    when(authenticator.authenticateToken(any())).thenReturn(new 
UserPrincipal("user"));
+
+    AtomicReference<Principal> seenDuringChain = new AtomicReference<>();
+    FilterChain capturingChain =
+        (req, resp) -> 
seenDuringChain.set(PrincipalUtils.getCurrentPrincipal());
+    filter.doFilter(mockRequest, mockResponse, capturingChain);
+
+    Assertions.assertEquals(
+        ActiveRoles.of(Arrays.asList("vrf_角色", "rôle")),
+        ((UserPrincipal) seenDuringChain.get()).getActiveRoles());
+  }
+
   @Test
   public void testDoFilterDefaultsToAllWhenHeaderAbsent() throws 
ServletException, IOException {
     Authenticator authenticator = mock(Authenticator.class);

Reply via email to