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


##########
amber/src/main/scala/org/apache/texera/web/resource/auth/ExternalAuthProvisioner.scala:
##########
@@ -0,0 +1,185 @@
+/*
+ * 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.web.resource.auth
+
+import com.typesafe.scalalogging.LazyLogging
+import org.apache.texera.dao.SqlServer
+import org.apache.texera.dao.jooq.generated.Tables.{AUTH_PROVIDER, USER}
+import org.apache.texera.dao.jooq.generated.enums.{ProviderTypeEnum, 
UserRoleEnum}
+import org.apache.texera.dao.jooq.generated.tables.daos.{AuthProviderDao, 
UserDao}
+import org.apache.texera.dao.jooq.generated.tables.pojos.{AuthProvider, User}
+import org.jooq.DSLContext
+
+import java.time.OffsetDateTime
+import javax.ws.rs.NotAuthorizedException
+import scala.util.chaining.scalaUtilChainingOps
+
+/**
+  * A verified external identity (Google, Facebook, ...) reduced to the fields 
we
+  * persist. `avatar` is optional: `None` means the provider supplies no 
avatar, so
+  * the user's existing avatar column is left untouched rather than 
overwritten.
+  *
+  * `emailVerified` reports whether the provider itself vouches for `email`. 
It has no
+  * default on purpose: an email address is what links an external identity to 
an
+  * existing account, so treating an unverified one as trusted is an 
account-takeover
+  * path, and a defaulted flag is how that mistake comes back.
+  */
+final case class ExternalProfile(
+    providerType: ProviderTypeEnum,
+    providerId: String,
+    name: String,
+    email: String,
+    emailVerified: Boolean,
+    avatar: Option[String] = None
+)
+
+object ExternalAuthProvisioner extends LazyLogging {
+
+  /**
+    * Resolve the user behind an external identity, creating one if necessary, 
and
+    * ensure its auth-provider row is present and up to date. Runs in a single
+    * transaction and returns the (possibly newly created) user.
+    */
+  def loginOrProvision(profile: ExternalProfile): User =
+    SqlServer.withTransaction(SqlServer.getInstance().createDSLContext()) { 
ctx =>
+      val txUserDao = new UserDao(ctx.configuration())
+      val txAuthDao = new AuthProviderDao(ctx.configuration())
+
+      Option(
+        ctx
+          .select()
+          .from(USER)
+          .join(AUTH_PROVIDER)
+          .on(USER.UID.eq(AUTH_PROVIDER.UID))
+          .where(AUTH_PROVIDER.PROVIDER_TYPE.eq(profile.providerType))
+          .and(AUTH_PROVIDER.PROVIDER_ID.eq(profile.providerId))
+          .fetchOne()
+      ) match {
+        case Some(record) =>
+          // known identity: refresh the profile fields if they drifted
+          txUserDao.fetchOneByUid(record.get(USER.UID)).tap { user =>
+            if (refresh(user, profile)) txUserDao.update(user)
+          }
+
+        case None =>
+          // First time we have seen this identity, so the email address is 
the only thing
+          // tying it to an account. It is either an existing one to link 
onto, or a new row that
+          // claims the address. Trusting an unverified address for that lets 
anyone who can
+          // mint an `email` claim take over, or squat on, someone else's 
account. The error
+          // is deliberately the same one a bad credential yields, so this 
does not become an
+          // oracle for which addresses are registered.
+          if (!profile.emailVerified) {
+            logger.warn(
+              s"Refusing to provision ${profile.providerType} identity 
${profile.providerId}: " +
+                "the provider did not verify its email address."
+            )
+            throw new NotAuthorizedException("Login credentials are 
incorrect.")
+          }
+
+          val user = Option(txUserDao.fetchOneByEmail(profile.email)) match {
+            case Some(existing) =>
+              existing.tap { user =>
+                if (refresh(user, profile)) txUserDao.update(user)
+              }
+            case None =>
+              new User().tap { user =>
+                user.setName(profile.name)
+                user.setEmail(profile.email)
+                profile.avatar.foreach(user.setAvatar)
+                user.setRole(UserRoleEnum.INACTIVE)
+                txUserDao.insert(user)
+              }

Review Comment:
   Concurrent first-time external logins for the same email can race here: both 
transactions can observe no existing user by email and then attempt 
txUserDao.insert(user), which will hit the USER.EMAIL unique constraint and 
currently bubble up as a 500. Consider catching SQLSTATE 23505 and re-fetching 
by email so the second request links onto the already-created account instead 
of failing.



##########
amber/src/main/scala/org/apache/texera/web/resource/auth/GoogleAuthResource.scala:
##########
@@ -53,64 +63,36 @@ class GoogleAuthResource {
   @Path("/clientid")
   def getClientId: String = clientId
 
-  @POST
-  @Consumes(Array(MediaType.TEXT_PLAIN))
-  @Produces(Array(MediaType.APPLICATION_JSON))
-  @Path("/login")
-  def login(credential: String): TokenIssueResponse = {
-    val idToken =
+  /**
+    * Verify `credential` against Google, yielding its payload, or None if it 
is not a valid
+    * token for this client. The only seam that reaches the network, so tests 
override it
+    * instead of signing a token; kept a method rather than a constructor 
parameter because
+    * Jersey instantiates this resource from `classOf[GoogleAuthResource]`.
+    */
+  protected def verifiedPayload(credential: String): 
Option[GoogleIdToken.Payload] =
+    Option(
       new GoogleIdTokenVerifier.Builder(new NetHttpTransport, 
GsonFactory.getDefaultInstance)
         .setAudience(
           Collections.singletonList(clientId)

Review Comment:
   `GoogleIdTokenVerifier.verify(credential)` can throw (e.g., for a malformed 
JWT like "not-a-jwt"). Right now that exception propagates and becomes a 500, 
even though it is an authentication failure case. Consider catching 
IllegalArgumentException (and similar parsing exceptions) in verifiedPayload 
and returning None so the endpoint consistently responds with 401 for invalid 
credentials.



##########
amber/src/main/scala/org/apache/texera/web/resource/auth/GoogleAuthResource.scala:
##########
@@ -19,30 +19,40 @@
 
 package org.apache.texera.web.resource.auth
 
-import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier
+import com.google.api.client.googleapis.auth.oauth2.{GoogleIdToken, 
GoogleIdTokenVerifier}
 import com.google.api.client.http.javanet.NetHttpTransport
 import com.google.api.client.json.gson.GsonFactory
 import org.apache.texera.auth.JwtAuth.{TOKEN_EXPIRE_TIME_IN_MINUTES, 
jwtClaims, jwtToken}
 import org.apache.texera.common.config.UserSystemConfig
-import org.apache.texera.dao.SqlServer
-import org.apache.texera.dao.jooq.generated.enums.UserRoleEnum
-import org.apache.texera.dao.jooq.generated.tables.daos.UserDao
-import org.apache.texera.dao.jooq.generated.tables.pojos.User
+import org.apache.texera.dao.jooq.generated.enums.ProviderTypeEnum
 import org.apache.texera.web.model.http.response.TokenIssueResponse
-import org.apache.texera.web.resource.auth.GoogleAuthResource.userDao
 
 import java.util.Collections
 import javax.ws.rs._
 import javax.ws.rs.core.MediaType
 
 object GoogleAuthResource {
-  private def userDao =
-    new UserDao(
-      SqlServer
-        .getInstance()
-        .createDSLContext()
-        .configuration
+
+  /**
+    * Reduce a verified Google id-token payload to the fields we persist. 
Google omits `name`
+    * for accounts with no profile name, and the provisioner writes `name` 
straight to a NOT
+    * NULL column, so the address stands in for it. Only the last path segment 
of `picture` is
+    * kept. The frontend rebuilds the full `lh3.googleusercontent.com` URL 
around it.
+    */
+  private[auth] def profileOf(payload: GoogleIdToken.Payload): ExternalProfile 
= {
+    val googleEmail = payload.getEmail
+    ExternalProfile(
+      ProviderTypeEnum.GOOGLE,
+      payload.getSubject,
+      
Option(payload.get("name").asInstanceOf[String]).filter(_.nonEmpty).getOrElse(googleEmail),
+      googleEmail,
+      // getEmailVerified boxes to null when the claim is absent; absent means 
unverified.
+      emailVerified = 
Option(payload.getEmailVerified).exists(_.booleanValue()),
+      avatar = Option(payload.get("picture").asInstanceOf[String])
+        .filter(_.nonEmpty)
+        .map(_.split("/").last)

Review Comment:
   `picture` URLs that end with a trailing slash (or otherwise yield an empty 
last segment) will currently store an empty-string avatar. That makes it harder 
for downstream code to distinguish "no avatar" from "present avatar" and can 
generate broken image URLs. Filtering out empty last segments keeps the column 
null when no usable id is present.



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