bobbai00 commented on code in PR #9043:
URL: https://github.com/apache/texera/pull/9043#discussion_r4645786041
##########
access-control-service/src/main/scala/org/apache/texera/service/resource/AccessControlResource.scala:
##########
@@ -125,6 +129,60 @@ object AccessControlResource extends LazyLogging {
}
}
+ // Extract the bearer token from the access-token query param, the
+ // Authorization header, or a "token" field in the body (in that order).
+ private def extractBearerToken(
+ uriInfo: UriInfo,
+ headers: HttpHeaders,
+ bodyOpt: Option[String]
+ ): String = {
+ val qToken = Option(uriInfo.getQueryParameters().getFirst("access-token"))
+ .map(_.trim)
+ .filter(_.nonEmpty)
+ val hToken = Option(headers.getRequestHeader("Authorization"))
+ .flatMap(_.asScala.headOption)
+ .map(_.replaceFirst("(?i)^Bearer\\s+", "")) // case-insensitive "Bearer "
+ .map(_.trim)
+ .filter(_.nonEmpty)
+ val bToken = bodyOpt.flatMap(extractTokenFromBody)
+ qToken.orElse(hToken).orElse(bToken).getOrElse("")
+ }
+
+ // Phase 1 agent authorization: authenticate the JWT and require a
+ // REGULAR/ADMIN role. Any such user may reach any agent for now; per-agent
+ // ownership is deferred (see #5302 / #5561). On success, return the user
+ // identity headers for future per-agent authorization in agent-service.
+ private def checkAgentAccess(
+ uriInfo: UriInfo,
+ headers: HttpHeaders,
+ bodyOpt: Option[String]
+ ): Response = {
+ val token = extractBearerToken(uriInfo, headers, bodyOpt)
+ val userSession: Optional[SessionUser] =
+ try parseToken(token)
+ catch {
+ case e: Exception =>
+ logger.error(s"Failed parsing token for agent request: $e")
+ Optional.empty()
+ }
+
+ if (userSession.isEmpty) {
+ return Response.status(Response.Status.UNAUTHORIZED).build()
Review Comment:
Verified: lines 319-323 now give 401 and 403 for the `/api/agents` branch
and 403 for the computing-unit branches, which matches `checkAgentAccess` and
`checkComputingUnitAccess`.
##########
frontend/src/app/workspace/service/agent/agent.service.ts:
##########
@@ -825,21 +830,23 @@ export class AgentService {
*/
public fetchModelTypes(): Observable<ModelType[]> {
if (!this.modelTypes$) {
- this.modelTypes$ =
this.http.get<LiteLLMModelsResponse>(`${AppSettings.getApiEndpoint()}/models`).pipe(
- map(response =>
- response.data.map((model: LiteLLMModel) => ({
- id: model.id,
- name: this.formatModelName(model.id),
- description: `Model: ${model.id}`,
- icon: "robot",
- }))
- ),
- catchError((error: unknown) => {
- console.error("Failed to fetch models from API:", error);
- return of([]);
- }),
- shareReplay(1)
- );
+ this.modelTypes$ = this.http
+ .get<LiteLLMModelsResponse>(`${AppSettings.getApiEndpoint()}/models`)
+ .pipe(
+ map(response =>
+ response.data.map((model: LiteLLMModel) => ({
+ id: model.id,
+ name: this.formatModelName(model.id),
+ description: `Model: ${model.id}`,
+ icon: "robot",
+ }))
+ ),
+ catchError((error: unknown) => {
+ console.error("Failed to fetch models from API:", error);
+ return of([]);
+ }),
+ shareReplay(1)
+ );
Review Comment:
Verified: `fetchModelTypes` is identical to main again, and `format:ci`
passes in all three frontend jobs at 6e43673. The macOS job's only failure is a
`code-editor` spec timeout that this PR does not touch.
##########
agent-service/src/server.ts:
##########
@@ -168,6 +166,22 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
set.status = ERROR_STATUS[errorMessage] ?? 500;
return { error: errorMessage || "Internal server error" };
})
+ // Authenticate every agent request by verifying the Bearer JWT ourselves
+ // (defense in depth — the gateway ext_authz also checks it, but this also
+ // covers direct access, e.g. bare-metal dev). The WebSocket route is guarded
+ // separately in its open() handler via the access-token query param.
+ .onBeforeHandle(({ request, set }) => {
Review Comment:
Verified: the guard now throws from `onTransform` (server.ts:177-186), and
`ERROR_STATUS` maps the two messages to 401 and 403. Probing this tree, an
unauthenticated `POST /api/agents` with `{}` gets 401 and an INACTIVE token
gets 403. A valid token with `{}` still gets the validation 400.
##########
agent-service/src/config/jwt.ts:
##########
@@ -0,0 +1,134 @@
+/**
+ * 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.
+ */
+
+import { createHmac, timingSafeEqual } from "node:crypto";
+import { existsSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { env } from "./env";
+import { createLogger } from "../logger";
+
+const log = createLogger("Jwt");
+
+// Token issuance lives in the Scala services (org.apache.texera.auth.JwtAuth):
Review Comment:
Verified: the `jwtClaims` doc now names `agent-service/src/config/jwt.ts`
(JwtAuth.scala:56-58).
##########
agent-service/src/config/jwt.ts:
##########
@@ -0,0 +1,134 @@
+/**
+ * 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.
+ */
+
+import { createHmac, timingSafeEqual } from "node:crypto";
+import { existsSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { env } from "./env";
+import { createLogger } from "../logger";
+
+const log = createLogger("Jwt");
+
+// Token issuance lives in the Scala services (org.apache.texera.auth.JwtAuth):
+// HS256 over the UTF-8 bytes of the secret, with a required `exp` and `sub`
+// and a 30s allowed clock skew. This module mirrors the verification so the
+// agent service can validate the same tokens without a gateway.
+const CLOCK_SKEW_SECONDS = 30;
+
+/** Read the `256-bit-secret` default out of auth.conf, if the file is found.
*/
+function readSecretFromAuthConf(): string | undefined {
+ const candidates = [
+ env.AUTH_CONF_PATH, // explicit override
+ "auth.conf", // bundled next to the app in the container image
+ "../common/config/src/main/resources/auth.conf", // repo layout in local
dev
+ ].filter((p): p is string => typeof p === "string" && p.length > 0);
+
+ for (const candidate of candidates) {
+ const path = resolve(process.cwd(), candidate);
+ if (!existsSync(path)) continue;
+ // The first quoted `256-bit-secret = "..."` is the literal default; the
+ // second line is the `${?AUTH_JWT_SECRET}` env override (handled below).
+ const match = readFileSync(path,
"utf-8").match(/256-bit-secret\s*=\s*"([^"]*)"/);
+ if (match) {
+ log.info({ path }, "loaded JWT secret default from auth.conf");
+ return match[1];
+ }
+ }
+ return undefined;
+}
+
+function resolveSecret(): string {
+ const secret = env.AUTH_JWT_SECRET || readSecretFromAuthConf();
+ if (!secret) {
+ throw new Error("JWT secret not found: neither AUTH_JWT_SECRET environment
variable nor auth.conf was found.");
Review Comment:
Verified: jwt.ts:59-61 now has the new wording, and the agent-service format
check passes.
##########
frontend/src/app/workspace/service/agent/agent.service.ts:
##########
@@ -718,26 +721,28 @@ export class AgentService {
body.computingUnitId = selectedUnit.computingUnit.cuid;
}
- return this.http.post<ApiAgentInfo>(`${this.AGENT_API_BASE}/agents`,
body).pipe(
- map(response => {
- const agentInfo = this.mapApiAgentInfo(response);
-
- this.agents.set(response.id, agentInfo);
- // Pass workflowId to enable workflow polling from backend database
- const tracking = this.getOrCreateStateTracking(response.id,
workflowId);
- // Set the initial state from the API response (agent is AVAILABLE
after creation)
- tracking.stateSubject.next(agentInfo.state || AgentState.AVAILABLE);
- this.agentChangeSubject.next();
+ return this.http
+ .post<ApiAgentInfo>(`${this.AGENT_API_BASE}/agents`, body,
this.agentHeaders(undefined, workflowId))
Review Comment:
Verified: both `createAgent` specs now pin the header. It is absent without
a workflow (agent.service.spec.ts:155) and `"42"` with one (:170).
--
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]