bobbai00 commented on code in PR #9043:
URL: https://github.com/apache/texera/pull/9043#discussion_r4577143005
##########
agent-service/src/server.ts:
##########
@@ -169,6 +167,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 }) => {
+ const token = (request.headers.get("authorization") ??
"").replace(/^Bearer\s+/i, "").trim();
Review Comment:
**Must fix:**
This guard strips an optional `Bearer` with a regex. The POST handler reads
the token with
[`extractBearerToken(...)!`](https://github.com/apache/texera/blob/fb66377fb6a86e188e6d91d0d2957c0cba196311/agent-service/src/server.ts#L203),
which needs exactly `<scheme> <token>`. So `Authorization: <jwt>` passes here
and fails there, and `POST /api/agents` returns 500 where `main` returns 401.
My earlier note said those handler branches could not fire, which was wrong for
this header shape. With the helper used here too, every route returns 401 and
the suite passes.
```suggestion
const token = extractBearerToken(request.headers.get("authorization") ??
undefined);
```
##########
agent-service/src/config/jwt.ts:
##########
@@ -0,0 +1,130 @@
+/**
+ * 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.");
+ }
+ return secret.toLowerCase();
Review Comment:
**Advisory:**
`AuthConfig` maps the value `random` to a key generated per JVM
([`AuthConfig.scala:34`](https://github.com/apache/texera/blob/fb66377fb6a86e188e6d91d0d2957c0cba196311/common/config/src/main/scala/org/apache/texera/common/config/AuthConfig.scala#L34-L37)).
Here it stays the literal key. With `AUTH_JWT_SECRET=random`, a token signed
with the string `random` passed `verifyToken` in my probe. The comment below
calls the value unsupported, so I'd refuse to start with it.
```suggestion
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;
```
##########
agent-service/src/api/auth-api.ts:
##########
@@ -18,43 +18,29 @@
*/
import type { UserInfo } from "../types/agent";
+import { verifyToken } from "../config/jwt";
export type { UserInfo } from "../types/agent";
+export { verifyToken } from "../config/jwt";
-function decodeJWT(token: string): any {
- try {
- const parts = token.split(".");
- if (parts.length !== 3) {
- throw new Error("Invalid JWT format");
- }
- return JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
- } catch (error) {
- throw new Error(`Failed to decode JWT: ${error}`);
- }
-}
-
+/** Verify the token's signature + expiry and return its user claims. Throws on
+ * an invalid/expired/mis-signed token. */
export function extractUserFromToken(token: string): UserInfo {
- const payload = decodeJWT(token);
+ const user = verifyToken(token);
+ if (!user) {
+ throw new Error("Invalid or expired token");
+ }
return {
- uid: payload.userId,
- name: payload.sub,
- email: payload.email || "",
- role: payload.role || "REGULAR",
+ uid: user.uid,
+ name: user.name,
+ email: user.email,
+ role: user.role,
};
}
-function isTokenExpired(token: string): boolean {
- try {
- const payload = decodeJWT(token);
- if (!payload.exp) return false;
- return Date.now() >= payload.exp * 1000;
- } catch {
- return true;
- }
-}
-
+/** True only when the token is genuinely valid (signature + expiry verified).
*/
export function validateToken(token: string): boolean {
Review Comment:
**Advisory:**
`validateToken` lost its only production caller when the check in the POST
handler was removed. Only `auth-api.spec.ts` references it now. I'd delete it
together with its `describe("validateToken")` block. `jwt.spec.ts` already
covers the same cases through `verifyToken`.
##########
frontend/src/app/workspace/service/agent/agent.service.ts:
##########
@@ -235,13 +236,11 @@ export class AgentService {
* Build HTTP headers for agent-service requests.
* Includes X-Agent-Workflow-Id for consistent hash routing in k8s.
*/
- private agentHeaders(agentId?: string): { headers: HttpHeaders } {
+ private agentHeaders(agentId?: string, workflowId?: number): { headers:
HttpHeaders } {
Review Comment:
**Must fix:**
The PR description still describes the first revision, and the squash commit
copies it. Four statements no longer hold. `agentHeaders()` does not attach
`Authorization`. The secret has no "built-in defaults" fallback
([`jwt.ts:59`](https://github.com/apache/texera/blob/fb66377fb6a86e188e6d91d0d2957c0cba196311/agent-service/src/config/jwt.ts#L59)
throws). The matcher is anchored ([`line
51`](https://github.com/apache/texera/blob/fb66377fb6a86e188e6d91d0d2957c0cba196311/access-control-service/src/main/scala/org/apache/texera/service/resource/AccessControlResource.scala#L51)),
not `.*/api/agents.*`. The frontend spec has no test for the header. Please
also add the PATCH handler, the 403 for other roles and the 1008 close code.
##########
frontend/src/app/workspace/service/agent/agent.service.ts:
##########
@@ -253,7 +252,7 @@ export class AgentService {
*/
private syncAgentsWithBackend(): void {
this.http
- .get<ApiAgentListResponse>(`${this.AGENT_API_BASE}/agents`)
+ .get<ApiAgentListResponse>(`${this.AGENT_API_BASE}/agents`,
this.agentHeaders())
Review Comment:
**Advisory:**
`agentHeaders()` no longer adds `Authorization`, so with no arguments it
returns an empty header set. This call passes that. So do
[`getAllAgents`](https://github.com/apache/texera/blob/fb66377fb6a86e188e6d91d0d2957c0cba196311/frontend/src/app/workspace/service/agent/agent.service.ts#L753)
and
[`fetchModelTypes`](https://github.com/apache/texera/blob/fb66377fb6a86e188e6d91d0d2957c0cba196311/frontend/src/app/workspace/service/agent/agent.service.ts#L826),
and the last one calls `/api/models`, not agent-service. Reverting the three
removes about 30 changed lines. Keep the
[`createAgent`](https://github.com/apache/texera/blob/fb66377fb6a86e188e6d91d0d2957c0cba196311/frontend/src/app/workspace/service/agent/agent.service.ts#L672)
change, which sends `X-Agent-Workflow-Id`.
```suggestion
.get<ApiAgentListResponse>(`${this.AGENT_API_BASE}/agents`)
```
##########
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:
**Polish:**
The class comment at [`lines
319-322`](https://github.com/apache/texera/blob/fb66377fb6a86e188e6d91d0d2957c0cba196311/access-control-service/src/main/scala/org/apache/texera/service/resource/AccessControlResource.scala#L319)
still says "403 on missing/invalid tokens". This branch returns 401 for those.
I'd mention both codes there.
--
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]