bobbai00 commented on code in PR #9043:
URL: https://github.com/apache/texera/pull/9043#discussion_r4619552367


##########
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:
   **Must fix:**
   
   This block differs from main only in layout. The layout is left over from 
dropping `this.agentHeaders()`, and prettier rejects it. `yarn --cwd frontend 
format:ci` fails on this file in all three frontend jobs ([ubuntu 
log](https://github.com/apache/texera/actions/runs/43888959868/job/133379335922)),
 so Required Checks is red and the new WebSocket spec has not run. The 
suggestion is prettier's output, which matches main.
   ```suggestion
         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)
         );
   ```



##########
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:
   **Polish:**
   
   `readSecretFromAuthConf` also returns undefined when a candidate file exists 
but the regex on line 47 finds no quoted `256-bit-secret`. In that case this 
message sends the operator looking for a file that is present. The wording 
below covers both cases and passes prettier.
   ```suggestion
       throw new Error(
         "JWT secret not found: AUTH_JWT_SECRET is unset and no auth.conf with 
a quoted 256-bit-secret was found."
       );
   ```



##########
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:
   **Advisory:**
   
   Elysia validates the body before `onBeforeHandle`. So an unauthenticated 
`POST /api/agents` with `{}` gets a 400 carrying the route's schema, not 401, 
and so do `PATCH /:id/settings` and `steps-by-operators`. No handler runs, but 
direct access is what this layer is for. Throwing from `.onTransform(...)` runs 
before validation. With `Unauthorized: 401` and `Forbidden: 403` added to 
`ERROR_STATUS`, the response bodies stay the same (I checked on elysia 1.4.32).



##########
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.");
+  }
+  const normalized = secret.toLowerCase();
+  if (normalized === "random") {
+    throw new Error('AUTH_JWT_SECRET="random" is not supported here; all 
services must share one fixed secret.');
+  }
+  return normalized;
+}
+
+// Resolution order mirrors HOCON's `256-bit-secret = "<default>"; 
256-bit-secret
+// = ${?AUTH_JWT_SECRET}`, and the `.toLowerCase()` normalization AuthConfig
+// applies. ("random" is intentionally unsupported here — it cannot match 
across
+// processes, so deployments share a fixed secret.)
+export const JWT_SECRET: string = resolveSecret();
+
+const SECRET_BYTES = new TextEncoder().encode(JWT_SECRET);
+
+export interface JwtUser {
+  uid: number;
+  name: string;
+  email: string;
+  role: string;
+}
+
+function decodeSegment(segment: string): unknown {
+  return JSON.parse(Buffer.from(segment, "base64url").toString("utf-8"));
+}
+
+/**
+ * Verify an HS256 JWT issued by the Scala services and return its claims, or
+ * null if the token is missing, malformed, mis-signed, expired, or uses a
+ * different algorithm. Mirrors org.apache.texera.auth.JwtParser.parseToken.
+ */
+export function verifyToken(token: string | undefined | null): JwtUser | null {

Review Comment:
   **Must fix:**
   
   The 2026-11-16 description rewrite dropped the template's "Was this PR 
authored or co-authored using generative AI tooling?" section, and the 
[template 
check](https://github.com/apache/texera/pull/9043#issuecomment-6919885761) 
still flags it. The first version of the description answered `Generated-by: 
Antigravity 2.0 (Gemini 2.5 Pro)`, so restoring that heading with a current 
`Generated-by:` line is enough. This comment is on this line only because the 
description has no line in the diff.



##########
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:
   **Polish:**
   
   No test pins this header: both `createAgent` specs check only the body 
([spec lines 
161-171](https://github.com/apache/texera/blob/ff51a5d02f9c41e2f08394427ac4d387717d860a/frontend/src/app/workspace/service/agent/agent.service.spec.ts#L161-L171)).
 Asserting `X-Agent-Workflow-Id` is `"42"` in the workflowId case would keep 
agent creation on the replica that the [hash 
policy](https://github.com/apache/texera/blob/ff51a5d02f9c41e2f08394427ac4d387717d860a/bin/k8s/templates/base/gateway/gateway-agent-traffic-policy.yaml#L18-L37)
 uses for that agent's later requests.



##########
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:
   **Advisory:**
   
   Nothing points back here: the `jwtClaims` doc names only the frontend's 
`auth.service.ts` as the reader to update on a claim rename 
([JwtAuth.scala:55-57](https://github.com/apache/texera/blob/ff51a5d02f9c41e2f08394427ac4d387717d860a/common/auth/src/main/scala/org/apache/texera/auth/JwtAuth.scala#L55-L57)).
 If `sub` or `userId` is renamed by following that doc, `verifyToken` rejects 
every token (lines 119-120). If `role` is renamed, everyone silently becomes 
REGULAR (line 129). One sentence there that names this file would fix it.



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