Copilot commented on code in PR #4903:
URL: https://github.com/apache/texera/pull/4903#discussion_r3209725171


##########
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:
   `UnauthorizedException` will be thrown on every missing/invalid token, and 
generating stack traces for these expected auth failures can be a noticeable 
CPU cost under load. Consider making this exception stacktrace-less (override 
`fillInStackTrace()` / use the `RuntimeException(..., false, false)` ctor 
pattern), or avoid exceptions for the hot-path by aborting the request directly 
from the filter once a JAX-RS runtime is available.
   



##########
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:
   RFC 6750/7235 defines the Authorization scheme token as case-insensitive. 
`startsWith("Bearer ")` will reject valid headers like `authorization: bearer 
<jwt>` (and any extra leading whitespace), returning a 401 even though the 
token is present. Consider parsing the scheme in a case-insensitive + 
whitespace-tolerant way (e.g., split on whitespace and compare lowercased 
scheme), then extracting the token from the remainder.



-- 
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