Yicong-Huang commented on code in PR #4903:
URL: https://github.com/apache/texera/pull/4903#discussion_r3214126640


##########
common/auth/src/main/scala/org/apache/texera/auth/JwtAuthFilter.scala:
##########
@@ -20,35 +20,80 @@
 package org.apache.texera.auth
 
 import com.typesafe.scalalogging.LazyLogging
-import jakarta.ws.rs.container.{ContainerRequestContext, 
ContainerRequestFilter}
-import jakarta.ws.rs.core.{HttpHeaders, SecurityContext}
+import jakarta.annotation.security.PermitAll
+import jakarta.ws.rs.container.{ContainerRequestContext, 
ContainerRequestFilter, ResourceInfo}
+import jakarta.ws.rs.core.{Context, HttpHeaders, SecurityContext}
 import jakarta.ws.rs.ext.Provider
 import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum
 
 import java.security.Principal
 
+/** JAX-RS request filter that authenticates a Bearer JWT and installs a
+  * [[SessionUser]] security context.
+  *
+  * Failure semantics (RFC 6750 §3):
+  *   - No `Authorization: Bearer …` header: throw [[UnauthorizedException]]
+  *     carrying a bare `Bearer realm="texera"` challenge — unless the
+  *     resource method or class is annotated with `@PermitAll`, in which
+  *     case the request continues with no security context. This supports
+  *     the `@Auth Optional[SessionUser]` pattern for endpoints that need
+  *     to serve anonymous users.
+  *   - Header present but token verification / claim extraction fails:
+  *     throw [[UnauthorizedException]] with `error="invalid_token"`
+  *     always, even on `@PermitAll` endpoints — a tampered or stale token
+  *     is never silently treated as anonymous.
+  *   - Header present and valid: install a `SecurityContext` whose
+  *     principal is the parsed [[SessionUser]].
+  *
+  * HTTP translation (status 401, `WWW-Authenticate` header) is done by
+  * [[UnauthorizedExceptionMapper]], registered alongside this filter in
+  * each service.
+  */
 @Provider
 class JwtAuthFilter extends ContainerRequestFilter with LazyLogging {
 
+  @Context
+  private var resourceInfo: ResourceInfo = _
+
   override def filter(requestContext: ContainerRequestContext): Unit = {
     val authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)
 
-    if (authHeader != null && authHeader.startsWith("Bearer ")) {
-      val token = authHeader.substring(7) // Remove "Bearer " prefix
-      val userOpt = JwtParser.parseToken(token)
-
-      if (userOpt.isPresent) {
-        val user = userOpt.get()
-        requestContext.setSecurityContext(new SecurityContext {
-          override def getUserPrincipal: Principal = user
-          override def isUserInRole(role: String): Boolean =
-            user.isRoleOf(UserRoleEnum.valueOf(role))
-          override def isSecure: Boolean = false
-          override def getAuthenticationScheme: String = "Bearer"
-        })
-      } else {
-        logger.warn("Invalid JWT: Unable to parse token")
-      }
+    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
+      if (isPermitAll) return
+      throw new UnauthorizedException(JwtAuthFilter.BearerChallenge)
+    }
+
+    val token = authHeader.substring(7) // Remove "Bearer " prefix

Review Comment:
   Good catch — fixed in 35d6f23e. The header parsing now follows RFC 7235 
§2.1: trim → split on `\s+` → `equalsIgnoreCase("Bearer")` → trim the 
credentials. So `bearer <jwt>`, `BEARER <jwt>`, mixed case, leading/trailing 
whitespace, and multiple spaces between scheme and token are all accepted. 
Added 7 new `JwtAuthFilterSpec` cases covering each variant plus a `Bearer   ` 
(no token) reject case.



##########
common/auth/src/main/scala/org/apache/texera/auth/UnauthorizedException.scala:
##########
@@ -0,0 +1,46 @@
+/*
+ * 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.texera.auth
+
+import jakarta.ws.rs.core.{HttpHeaders, Response}
+import jakarta.ws.rs.ext.{ExceptionMapper, Provider}
+
+/** Carries an RFC 6750 §3 `WWW-Authenticate: Bearer …` challenge to be
+  * returned alongside a `401 Unauthorized` response.
+  *
+  * Extends `RuntimeException` (not `WebApplicationException`) so it can be
+  * constructed without a JAX-RS `RuntimeDelegate` on the classpath, which
+  * keeps unit tests for [[JwtAuthFilter]] independent of any Jersey
+  * implementation. The companion [[UnauthorizedExceptionMapper]] converts
+  * the exception to the actual HTTP response at the JAX-RS edge.
+  */
+class UnauthorizedException(val challenge: String) extends 
RuntimeException(challenge)

Review Comment:
   Agreed — fixed in 35d6f23e. `UnauthorizedException` now uses the 4-arg 
`RuntimeException(message, cause, enableSuppression, writableStackTrace)` ctor 
with `writableStackTrace = false`, so `fillInStackTrace` is a no-op and the 
auth hot path no longer pays per-request stack capture cost. Added a regression 
test (`UnauthorizedException should carry no stack trace`) asserting 
`getStackTrace.length == 0`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to