PG1204 commented on code in PR #5124: URL: https://github.com/apache/texera/pull/5124#discussion_r3318437407
########## amber/src/main/scala/org/apache/texera/web/resource/HuggingFaceModelResource.scala: ########## @@ -0,0 +1,672 @@ +/* + * 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 + +import com.fasterxml.jackson.core.`type`.TypeReference +import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} +import com.google.common.cache.{Cache, CacheBuilder} +import kong.unirest.Unirest +import org.slf4j.{Logger, LoggerFactory} + +import java.io.InputStream +import java.net.URI +import java.nio.file.{Files, Path => NioPath, Paths} +import java.util.concurrent.{Callable, ForkJoinPool, TimeUnit} +import java.util.stream.Collectors +import javax.ws.rs._ +import javax.ws.rs.core.{MediaType, Response} +import scala.jdk.CollectionConverters._ + +/** + * REST resource that proxies the Hugging Face Hub API for the HuggingFace operator. + * + * - GET /api/huggingface/models?task=…[&search=…] browse or search HF models + * - GET /api/huggingface/tasks list HF pipeline tags with hosted inference + * - POST /api/huggingface/upload-audio?filename=… stream-upload an audio file + * - GET /api/huggingface/audio-preview?path=… stream back an uploaded audio file + * - GET /api/huggingface/media-proxy?url=… proxy an allowlisted remote media URL + * + * Token sourcing: the user supplies their own HF token via the `X-HF-Token` + * request header (forwarded by the frontend from the operator's property + * panel). If the header is absent, requests go to HF Hub anonymously — + * HF serves public model/task lists at public rate limits without auth. + * The browse cache is bypassed whenever a user token is supplied, so one + * user's private-model visibility never leaks into another user's response. + */ +@Path("/huggingface") +@Produces(Array(MediaType.APPLICATION_JSON)) +class HuggingFaceModelResource { + + import HuggingFaceModelResource._ + + @GET + @Path("/models") + def listModels( + @QueryParam("task") @DefaultValue("text-generation") task: String, + @QueryParam("search") search: String, + @HeaderParam("X-HF-Token") userToken: String + ): Response = { + try { + val hfToken = sanitizeToken(userToken) + val isUserToken = hfToken.nonEmpty + + // ── Search mode: forward query to HF Hub, return results directly ── + if (search != null && search.trim.nonEmpty) { + return fetchSearchResults(task, search.trim, hfToken) + } + + // ── Browse mode: return ALL models for this task ── + // Only cache anonymous results, so a user with private-model visibility + // can't have their token-scoped list served to a different user. + if (!isUserToken) { + val cached = modelCache.getIfPresent(task) + if (cached != null) { + return Response.ok(cached).build() + } + } + + val pageResult = fetchAllModelsForTask(task, hfToken) + val json = objectMapper.writeValueAsString(pageResult.models) + if (!isUserToken) modelCache.put(task, json) + + val builder = Response.ok(json) + if (pageResult.truncated) builder.header(TRUNCATED_HEADER, "true") + builder.build() + } catch { + case e: Exception => + logger.error(s"Failed to fetch HF models for task '$task'", e) + errorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Failed to fetch models.") + } + } + + /** + * Streams an audio file from the request body to a temp file under + * `${java.io.tmpdir}/texera-hf-audio`. Enforces an extension allowlist + * and a max payload size (rejected with 413 once exceeded). Old files + * in the temp dir are best-effort cleaned on each upload. + */ + @POST + @Path("/upload-audio") + @Consumes(Array(MediaType.WILDCARD)) + def uploadAudioReference( + @QueryParam("filename") filename: String, + stream: InputStream + ): Response = { + try { + if (stream == null) { + return errorResponse(Response.Status.BAD_REQUEST, "Audio payload is required.") + } + + val safeFileName = Option(filename) + .map(_.trim) + .filter(_.nonEmpty) + .map(name => Paths.get(name).getFileName.toString) + .getOrElse("audio.bin") + val extension = { + val idx = safeFileName.lastIndexOf('.') + if (idx >= 0 && idx < safeFileName.length - 1) + safeFileName.substring(idx).toLowerCase + else "" + } + if (!ALLOWED_AUDIO_EXTENSIONS.contains(extension)) { + return errorResponse( + Response.Status.BAD_REQUEST, + "Unsupported audio file extension." + ) + } + + val tempDir = audioTempDir + Files.createDirectories(tempDir) + sweepOldAudioFiles(tempDir) + + val tempFile: NioPath = Files.createTempFile(tempDir, "hf-audio-", extension) + tempFile.toFile.deleteOnExit() + + val out = Files.newOutputStream(tempFile) + var totalBytes = 0L + try { + val buf = new Array[Byte](8 * 1024) + var read = stream.read(buf) + while (read != -1) { + totalBytes += read + if (totalBytes > MAX_AUDIO_BYTES) { + out.close() + Files.deleteIfExists(tempFile) + return errorResponse( + Response.Status.REQUEST_ENTITY_TOO_LARGE, + "Audio payload exceeds the size limit." + ) + } + out.write(buf, 0, read) + read = stream.read(buf) + } + } finally { + out.close() + } + + if (totalBytes == 0L) { + Files.deleteIfExists(tempFile) + return errorResponse(Response.Status.BAD_REQUEST, "Audio payload is empty.") + } + + val json = objectMapper.writeValueAsString( + Map( + "path" -> tempFile.toAbsolutePath.toString, + "fileName" -> safeFileName + ).asJava + ) + Response.ok(json).build() + } catch { + case e: Exception => + logger.error("Failed to upload audio", e) + errorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Failed to upload audio.") + } + } + + @GET + @Path("/audio-preview") + def previewUploadedAudio(@QueryParam("path") path: String): Response = { + try { + val trimmedPath = Option(path).map(_.trim).getOrElse("") + if (trimmedPath.isEmpty) { + return errorResponse(Response.Status.BAD_REQUEST, "Audio path is required.") + } + + val tempDir = audioTempDir.toAbsolutePath.normalize() + val requestedPath = Paths.get(trimmedPath).toAbsolutePath.normalize() + if (!requestedPath.startsWith(tempDir)) { + return errorResponse( + Response.Status.FORBIDDEN, + "Audio path is outside the allowed preview directory." + ) + } + if (!Files.exists(requestedPath) || !Files.isRegularFile(requestedPath)) { + return errorResponse(Response.Status.NOT_FOUND, "Uploaded audio file was not found.") + } + + val contentType = Option(Files.probeContentType(requestedPath)) + .filter(_.trim.nonEmpty) + .getOrElse(inferAudioContentType(requestedPath)) + Response.ok(Files.readAllBytes(requestedPath), contentType).build() + } catch { + case e: Exception => + logger.error("Failed to read uploaded audio", e) + errorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Failed to read uploaded audio.") + } + } + + /** + * Proxies a remote media URL to bypass browser CORS for HF inference responses. + * Only http(s) URLs whose host is in ALLOWED_MEDIA_HOST_SUFFIXES are accepted, + * blocking SSRF probes against internal services. + */ + @GET + @Path("/media-proxy") Review Comment: Fixed in 309ac5428. /media-proxy now streams the upstream body via Unirest.asObject(Function<RawResponse, T>) with a 50 MiB cap (pre-check on Content-Length + mid-read counter for missing/lying Content-Length); /audio-preview adds a Files.size() defense-in-depth check before readAllBytes. Both return 413 on cap violation. Test added for the audio-preview path. -- 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]
