Copilot commented on code in PR #9219: URL: https://github.com/apache/texera/pull/9219#discussion_r4417598238
########## common/auth/src/main/scala/org/apache/texera/auth/util/WorkflowAccess.scala: ########## @@ -0,0 +1,110 @@ +// 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.util + +import org.apache.texera.dao.SqlServer +import org.apache.texera.dao.jooq.generated.Tables._ +import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum +import org.jooq.impl.DSL +import org.jooq.{DSLContext, Record1, Select} + +object WorkflowAccess { + private def context: DSLContext = + SqlServer + .getInstance() + .createDSLContext() + + /** + * Identifies whether the given user has read-only access over the given workflow + * + * @param wid workflow id + * @param uid user id, works with workflow id as primary keys in database + * @return boolean value indicating yes/no + */ + def hasReadAccess(wid: Integer, uid: Integer): Boolean = { + isPublic(wid) || !getPrivilege(wid, uid).eq(PrivilegeEnum.NONE) + } + + /** + * Identifies whether the given user has write access over the given workflow + * + * @param wid workflow id + * @param uid user id, works with workflow id as primary keys in database + * @return boolean value indicating yes/no + */ + def hasWriteAccess(wid: Integer, uid: Integer): Boolean = { + getPrivilege(wid, uid).eq(PrivilegeEnum.WRITE) + } + + /** + * @param wid workflow id + * @param uid user id, works with workflow id as primary keys in database + * @return PrivilegeEnum value indicating NONE/READ/WRITE + */ + def getPrivilege(wid: Integer, uid: Integer): PrivilegeEnum = { + // One round trip: the caller's own ownership row and grant, read together. Both joins are + // narrowed to the caller, so a workflow with several owners still yields one row. + val row = context + .select(WORKFLOW_OF_USER.UID, WORKFLOW_USER_ACCESS.PRIVILEGE) + .from(WORKFLOW) + .leftJoin(WORKFLOW_OF_USER) + .on(WORKFLOW_OF_USER.WID.eq(WORKFLOW.WID).and(WORKFLOW_OF_USER.UID.eq(uid))) + .leftJoin(WORKFLOW_USER_ACCESS) + .on(WORKFLOW_USER_ACCESS.WID.eq(WORKFLOW.WID).and(WORKFLOW_USER_ACCESS.UID.eq(uid))) + .where(WORKFLOW.WID.eq(wid)) + .fetchOne() + if (row == null) PrivilegeEnum.NONE + else OwnerAccess.privilege(row.value1() != null, row.value2()) + } + + def isOwner(wid: Integer, uid: Integer): Boolean = + context.fetchExists( + WORKFLOW_OF_USER, + WORKFLOW_OF_USER.WID.eq(wid).and(WORKFLOW_OF_USER.UID.eq(uid)) + ) + + /** Ids of the workflows `uid` owns or was granted. */ + def accessibleWids(uid: Integer): Select[Record1[Integer]] = + DSL + .select(WORKFLOW_OF_USER.WID) + .from(WORKFLOW_OF_USER) + .where(WORKFLOW_OF_USER.UID.eq(uid)) + .union( + DSL + .select(WORKFLOW_USER_ACCESS.WID) + .from(WORKFLOW_USER_ACCESS) + .where(WORKFLOW_USER_ACCESS.UID.eq(uid)) + ) + + /** + * Whether the user was granted access to the workflow itself, rather than merely being able to + * read it because it is public. Granted access sees the author's working copy; public access is + * held at the pinned copy while one is pinned. + */ + def hasGrantedAccess(wid: Integer, uid: Integer): Boolean = { + !getPrivilege(wid, uid).eq(PrivilegeEnum.NONE) + } + + def isPublic(wid: Integer): Boolean = { + context + .select(WORKFLOW.IS_PUBLIC) + .from(WORKFLOW) + .where(WORKFLOW.WID.eq(wid)) + .fetchOneInto(classOf[Boolean]) Review Comment: `fetchOneInto(classOf[Boolean])` can return null when the workflow row doesn't exist, which can lead to null-unboxing issues when the method returns `Boolean`. Consider returning `Option(...)` with a safe default (e.g., `false`) or using a fetchOptional-style API to avoid nulls. ########## common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/ExecutionResultUris.scala: ########## @@ -0,0 +1,85 @@ +/* + * 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.amber.core.storage + +import org.apache.texera.amber.core.virtualidentity.{ExecutionIdentity, OperatorIdentity} +import org.apache.texera.amber.core.workflow.PortIdentity +import org.apache.texera.dao.SqlServer +import org.apache.texera.dao.jooq.generated.Tables.OPERATOR_PORT_EXECUTIONS +import org.jooq.DSLContext + +import java.net.URI +import scala.jdk.CollectionConverters._ + +/** + * The result URIs an execution recorded in operator_port_executions. + */ +object ExecutionResultUris { + private def context: DSLContext = + SqlServer + .getInstance() + .createDSLContext() + + def getResultUrisByExecutionId(eid: ExecutionIdentity): List[URI] = { + context + .select(OPERATOR_PORT_EXECUTIONS.RESULT_URI) + .from(OPERATOR_PORT_EXECUTIONS) + .where(OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(eid.id.toInt)) + .fetchInto(classOf[String]) + .asScala + .toList + .filter(uri => uri != null && uri.nonEmpty) + .map(URI.create) + } + + /** + * This method is mainly used for frontend requests. Given a logicalOpId and an outputPortId of an execution, + * this method finds the URI for a globalPortId that both: 1. matches the logicalOpId and outputPortId, and + * 2. is an external port. Currently the lookup is O(n), where n is the number of globalPortIds for this execution. + * TODO: Optimize the lookup once the frontend also has information about physical operators. + */ + def getResultUriByLogicalPortId( + eid: ExecutionIdentity, + opId: OperatorIdentity, + portId: PortIdentity + ): Option[URI] = { + def isMatchingExternalPortURI(uri: URI): Boolean = { + val components = VFSURIFactory.decodeURI(uri) + components.globalPortId.exists { globalPortId => + !globalPortId.portId.internal && + globalPortId.opId.logicalOpId == opId && + globalPortId.portId == portId && + components.resourceType == VFSResourceType.RESULT + } + } + + val urisOfEid: List[URI] = + context + .select(OPERATOR_PORT_EXECUTIONS.RESULT_URI) + .from(OPERATOR_PORT_EXECUTIONS) + .where(OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(eid.id.toInt)) + .fetchInto(classOf[String]) + .asScala + .toList Review Comment: This path will throw if `RESULT_URI` is NULL or an empty string (both can exist in DB, and `getResultUrisByExecutionId` explicitly filters them). To make behavior consistent and avoid `URI.create` exceptions, filter out null/empty strings here as well before mapping to `URI`. ########## common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/TupleUtils.scala: ########## @@ -35,4 +37,86 @@ object TupleUtils { objectNode } + private val binaryPreviewLeadingBits: Int = 10 + private val binaryPreviewTrailingBits: Int = 3 + + private def bytesToBinaryString(bytes: Array[Byte]): String = + bytes + .map(b => + String.format(s"%${BitsPerByte}s", Integer.toBinaryString(b & 0xff)).replace(' ', '0') + ) + .mkString("") + + /** + * Converts a collection of Tuples to a list of JSON ObjectNodes. + * + * This function takes a collection of Tuples and converts each tuple into a JSON ObjectNode. + * For binary data, it formats the bytes into a readable hex string representation with length info. + * For string values longer than maxStringLength (100), it truncates them. + * NULL values are converted to the string "NULL". + * + * @param tuples The collection of Tuples to convert + * @param isVisualization Whether this is for visualization rendering (affects string truncation) + * @return A List of ObjectNodes containing the JSON representation of the tuples + */ Review Comment: The Scaladoc says binary values are rendered as a hex string, but the implementation now renders a binary bit-string preview (leading/trailing bits with ellipsis). Please update the comment to match the actual output format so callers/tests don’t encode the wrong expectation. ########## common/auth/src/test/scala/org/apache/texera/auth/util/WorkflowAccessSpec.scala: ########## @@ -0,0 +1,202 @@ +/* + * 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.util + +import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.jooq.generated.Tables._ +import org.apache.texera.dao.jooq.generated.enums.PrivilegeEnum +import org.apache.texera.dao.jooq.generated.tables.daos.{ + UserDao, + WorkflowDao, + WorkflowOfUserDao, + WorkflowUserAccessDao +} +import org.apache.texera.dao.jooq.generated.tables.pojos.{ + User, + Workflow, + WorkflowOfUser, + WorkflowUserAccess +} +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} + +import java.sql.Timestamp +import scala.jdk.CollectionConverters._ + +class WorkflowAccessSpec + extends AnyFlatSpec + with BeforeAndAfterAll + with BeforeAndAfterEach + with MockTexeraDB { + + private val ownerUid = 1000 + scala.util.Random.nextInt(1000) + private val userWithWriteUid = 2000 + scala.util.Random.nextInt(1000) + private val userWithReadUid = 3000 + scala.util.Random.nextInt(1000) + private val testWorkflowWid = 5000 + scala.util.Random.nextInt(1000) + private val newGranteeUid = 6000 + scala.util.Random.nextInt(1000) Review Comment: Same concern as other DB tests in this PR: random ids can collide with other suites and lead to intermittent failures. Prefer deterministic ids or a UUID-based derivation to reduce the chance of cross-suite collisions in shared test DB state. ########## common/workflow-core/src/main/scala/org/apache/texera/amber/core/tuple/TupleUtils.scala: ########## @@ -35,4 +37,86 @@ object TupleUtils { objectNode } + private val binaryPreviewLeadingBits: Int = 10 + private val binaryPreviewTrailingBits: Int = 3 + + private def bytesToBinaryString(bytes: Array[Byte]): String = + bytes + .map(b => + String.format(s"%${BitsPerByte}s", Integer.toBinaryString(b & 0xff)).replace(' ', '0') + ) + .mkString("") + + /** + * Converts a collection of Tuples to a list of JSON ObjectNodes. + * + * This function takes a collection of Tuples and converts each tuple into a JSON ObjectNode. + * For binary data, it formats the bytes into a readable hex string representation with length info. + * For string values longer than maxStringLength (100), it truncates them. + * NULL values are converted to the string "NULL". + * + * @param tuples The collection of Tuples to convert + * @param isVisualization Whether this is for visualization rendering (affects string truncation) + * @return A List of ObjectNodes containing the JSON representation of the tuples + */ + def convertTuplesToJson( + tuples: Iterable[Tuple], + isVisualization: Boolean = false + ): List[ObjectNode] = { + val maxStringLength = 100 + + tuples.map { tuple => + val processedFields = tuple.schema.getAttributes.zipWithIndex + .map { + case (attr, idx) => + val fieldValue = tuple.getField[AnyRef](idx) + + Option(fieldValue) match { + case None => "NULL" + case Some(value) => + attr.getType match { + case AttributeType.BINARY => + value match { + case byteArray: Array[Byte] => + val totalSize = byteArray.length + val sizeFormatted = f"$totalSize%,d" + val totalBits = totalSize * BitsPerByte + val preview = + if (totalBits <= binaryPreviewLeadingBits + binaryPreviewTrailingBits) + bytesToBinaryString(byteArray) + else { + val leadingBytesNeeded = + math.ceil(binaryPreviewLeadingBits.toDouble / BitsPerByte).toInt + val trailingBytesNeeded = + math.ceil(binaryPreviewTrailingBits.toDouble / BitsPerByte).toInt + val leading = bytesToBinaryString(byteArray.take(leadingBytesNeeded)) + .take(binaryPreviewLeadingBits) + val trailing = bytesToBinaryString( + byteArray.takeRight(trailingBytesNeeded) + ).takeRight(binaryPreviewTrailingBits) + s"$leading...$trailing" + } + s"<binary $preview, size = $sizeFormatted bytes>" + + case _ => + throw new RuntimeException( Review Comment: Throwing `RuntimeException` makes it harder for callers to distinguish input/type errors from system failures. Prefer `IllegalArgumentException` (or a domain-specific exception) for an unexpected field type to better communicate the failure mode. ########## common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/ExecutionResultUrisSpec.scala: ########## @@ -0,0 +1,237 @@ +/* + * 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.amber.core.storage + +import org.apache.texera.amber.core.virtualidentity.{ + ExecutionIdentity, + OperatorIdentity, + PhysicalOpIdentity, + WorkflowIdentity +} +import org.apache.texera.amber.core.workflow.{GlobalPortIdentity, PortIdentity} +import org.apache.texera.amber.util.serde.GlobalPortIdentitySerde.SerdeOps +import org.apache.texera.dao.MockTexeraDB +import org.apache.texera.dao.jooq.generated.Tables._ +import org.apache.texera.dao.jooq.generated.tables.daos.{ + UserDao, + WorkflowDao, + WorkflowExecutionsDao, + WorkflowVersionDao +} +import org.apache.texera.dao.jooq.generated.tables.pojos.{ + User, + Workflow, + WorkflowExecutions, + WorkflowVersion +} +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} + +import java.net.URI +import java.sql.Timestamp +import java.util.UUID + +class ExecutionResultUrisSpec + extends AnyFlatSpec + with BeforeAndAfterAll + with BeforeAndAfterEach + with MockTexeraDB { + + private val testWorkflowWid = 3000 + scala.util.Random.nextInt(1000) + private val testUserId = 1000 + scala.util.Random.nextInt(1000) Review Comment: Using `Random.nextInt` for primary keys in DB-backed tests can introduce rare but painful flakiness (collisions across suites, especially under parallel test execution). Consider deriving ids from a UUID hash (with a wide range) or using deterministic constants that are guaranteed not to overlap across suites. -- 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]
