Repository navigation
feat(agent-service): authenticate requests via JWT and gateway ext_authz - #9043
Alwaysgaurav1 wants to merge 15 commits into
Conversation
…t_authz (apache#5561) Authorize requests reaching the agent service using JWT signature verification and gateway external authorization, providing defense in depth: 1. agent-service: - Added real HS256 signature verification in config/jwt.ts using crypto.createHmac and timingSafeEqual. - Resolves shared secret from AUTH_JWT_SECRET env or auth.conf with 30-second clock skew tolerance. - Added .onBeforeHandle guard on agentsRouter rejecting unauthenticated, expired, or invalid tokens with 401. - Added access-token query param check in WebSocket open() handler. 2. access-control-service: - Added /api/agents routing branch in AccessControlResource. - Verifies JWT validity and enforces REGULAR or ADMIN role. - Forwards trusted identity headers (x-user-id, x-user-name, x-user-email). 3. Gateways & Deployment: - bin/single-node/nginx.conf: Added auth_request /_agent_auth subrequest on /api/agents routing to access-control-service. - bin/k8s/templates/base/gateway/gateway-agent-security-policy.yaml: Added Envoy SecurityPolicy for agent-service-route. - bin/k8s/templates/base/agent-service/agent-service-deployment.yaml: Passed texeraEnvVars into agent-service container. - bin/dockerfiles/agent-service.dockerfile: Bundled auth.conf for container runtime. 4. Frontend: - Attaches Authorization Bearer token via agentHeaders() to REST requests. - Appends ?access-token= query param to WebSocket connection in startStatePolling(). - Added unit tests in agent.service.spec.ts.
Automated Reviewer SuggestionsBased on the
|
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #9043 +/- ##
============================================
- Coverage 91.61% 91.59% -0.02%
- Complexity 5047 5070 +23
============================================
Files 1284 1288 +4
Lines 57036 57215 +179
Branches 7420 7433 +13
============================================
+ Hits 52251 52405 +154
- Misses 2914 2936 +22
- Partials 1871 1874 +3
*This pull request uses carry forward flags. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
| config | throughput | MB/s | latency | max Δ latest / 7d | |
|---|---|---|---|---|---|
| 🔴 | bs=10 sw=10 sl=64 | 392 | 0.239 | 25,460/31,791/31,791 us | 🟢 -41.9% / 🔴 +170.9% |
| 🟢 | bs=100 sw=10 sl=64 | 860 | 0.525 | 115,986/122,819/122,819 us | 🟢 -17.3% / 🔴 +59.9% |
| ⚪ | bs=1000 sw=10 sl=64 | 985 | 0.601 | 1,012,471/1,092,669/1,092,669 us | ⚪ within ±5% / 🔴 +45.8% |
Baseline details
Latest main 7adc729 from same runner
| config | metric | PR | latest main | 7d avg | Δ latest | Δ 7d |
|---|---|---|---|---|---|---|
| bs=10 sw=10 sl=64 | throughput | 392 tuples/sec | 393 tuples/sec | 1,092 tuples/sec | -0.3% | -64.1% |
| bs=10 sw=10 sl=64 | MB/s | 0.239 MB/s | 0.24 MB/s | 0.666 MB/s | -0.4% | -64.1% |
| bs=10 sw=10 sl=64 | p50 | 25,460 us | 22,679 us | 9,398 us | +12.3% | +170.9% |
| bs=10 sw=10 sl=64 | p95 | 31,791 us | 54,684 us | 12,941 us | -41.9% | +145.7% |
| bs=10 sw=10 sl=64 | p99 | 31,791 us | 54,684 us | 15,496 us | -41.9% | +105.2% |
| bs=100 sw=10 sl=64 | throughput | 860 tuples/sec | 881 tuples/sec | 1,486 tuples/sec | -2.4% | -42.1% |
| bs=100 sw=10 sl=64 | MB/s | 0.525 MB/s | 0.538 MB/s | 0.907 MB/s | -2.4% | -42.1% |
| bs=100 sw=10 sl=64 | p50 | 115,986 us | 111,611 us | 72,544 us | +3.9% | +59.9% |
| bs=100 sw=10 sl=64 | p95 | 122,819 us | 148,561 us | 80,069 us | -17.3% | +53.4% |
| bs=100 sw=10 sl=64 | p99 | 122,819 us | 148,561 us | 101,531 us | -17.3% | +21.0% |
| bs=1000 sw=10 sl=64 | throughput | 985 tuples/sec | 972 tuples/sec | 1,533 tuples/sec | +1.3% | -35.8% |
| bs=1000 sw=10 sl=64 | MB/s | 0.601 MB/s | 0.594 MB/s | 0.936 MB/s | +1.2% | -35.8% |
| bs=1000 sw=10 sl=64 | p50 | 1,012,471 us | 1,029,214 us | 711,170 us | -1.6% | +42.4% |
| bs=1000 sw=10 sl=64 | p95 | 1,092,669 us | 1,095,713 us | 749,276 us | -0.3% | +45.8% |
| bs=1000 sw=10 sl=64 | p99 | 1,092,669 us | 1,095,713 us | 794,786 us | -0.3% | +37.5% |
Raw CSV
config_idx,batch_size,schema_width,string_len,num_batches,total_ms,total_tuples,total_bytes,tuples_per_sec,mb_per_sec,lat_p50_us,lat_p95_us,lat_p99_us
0,10,10,64,20,510.52,200,128000,392,0.239,25459.98,31791.35,31791.35
1,100,10,64,20,2325.62,2000,1280000,860,0.525,115985.75,122819.26,122819.26
2,1000,10,64,20,20312.84,20000,12800000,985,0.601,1012471.42,1092668.82,1092668.82
bobbai00
left a comment
There was a problem hiding this comment.
🔴 4 must-fix · 7 advisory · 2 polish: the auth design matches #5561 and works end to end on single-node; CI, k8s PATCH and the path regex need fixes.
Design & architecture (2)
server.ts:177: in-service guard accepts INACTIVE users (advisory, see inline)jwt.ts:36: hard-coded fallback copy of the JWT secret (advisory, see inline)
Correctness (4)
AccessControlResource.scala:89: no PATCH handler, so settings saves get 405 behind Envoy (must-fix, see inline)AccessControlResource.scala:51: unanchored regex authorizes unrelated dynamic-route paths (must-fix, see inline)AgentAccessAuthSpec.scala:46: spec does not compile, failing CI (must-fix, see inline)server.ts:466: rejected socket closes with the normal close code (advisory, see inline)
Simplifications (3)
agent.service.ts:244: duplicates the JwtModule interceptor header (advisory, see inline)agent-service-deployment.yaml:62: injects every texeraEnvVars secret into agent-service (advisory, see inline)server.ts:175: POST /agents token checks are now unreachable (advisory, see inline)
Conventions (2)
jwt.ts:89: title scope is not a module name, and the title is over length (must-fix, see inline)build.yml:249: unrelated sbt bump duplicates #9064 (advisory, see inline)
Polish: 2 quick touch-ups (see inline comments).
Verification trace
Ran this branch end to end on single-node (PR builds of access-control-service, agent-service and frontend, the PR's nginx.conf, a real login token). /api/agents returned 401 without a token, 403 for an INACTIVE user and 200 for REGULAR. The WebSocket upgrade was refused without a token, and an agent created from the UI built and executed a TextInput to Filter workflow. Behind a standalone Envoy ext_authz pointed at this branch's access-control-service, GET/POST/DELETE returned 200 and PATCH /api/agents/:id/settings returned 405. Unit suites: agent-service 327 pass, frontend agent.service.spec 89 pass. The access-control-service tests fail to compile, and pass 30/30 after the two-line fix noted inline.
|
Thanks for the thorough review and verification trace! I have addressed all items in commit 🔴 Must-Fix
🟡 Advisory & Simplifications
🟢 Polish
Verification:
Please take another look when you get a chance! |
|
@bobbai00 could you plss review it again. |
|
@dzueck Do you want to take a look at this PR as well? |
|
@dzueck Please check. |
bobbai00
left a comment
There was a problem hiding this comment.
🔴 13 resolved · 0 open · 6 new (6 new = 4 newly introduced · 2 late catches)
All 13 findings from the last round are fixed in the code. The branch also needs main merged in: the two conflicts are adjacent import lines from #6009, and keeping both sides is enough.
Design & architecture (1)
jwt.ts:61:AUTH_JWT_SECRET=randomis used as the literal key (advisory, see inline)
Correctness (1)
server.ts:175: the guard and the POST handler parse the Authorization header differently, giving a 500 (must-fix, see inline)
Simplifications (2)
auth-api.ts:42:validateTokenhas no production caller left (advisory, see inline)agent.service.ts:255: threeagentHeaders()calls now pass empty headers (advisory, see inline)
Conventions (1)
agent.service.ts:239: the PR description still describes the first revision (must-fix, see inline)
Polish: 1 quick touch-up (see inline comments).
Verification trace
Checked each of the 13 earlier findings against fb66377 instead of the reply. Ran the agent-service suite (346 pass) and probed the app with signed tokens. Authorization: <jwt> returns 500 on POST /api/agents and 200 on GET. With extractBearerToken in the guard, both return 401. With AUTH_JWT_SECRET=RANDOM, a token signed with the string random is accepted. Merged main in a scratch copy keeping both import lines: typecheck and 357 tests pass. The red macOS frontend job is a 20 s timeout in a spec this PR does not touch.
Alwaysgaurav1
left a comment
There was a problem hiding this comment.
Thanks for the thorough review, @bobbai00! All findings from this round have been addressed in commit ff51a5d:
- Merge
main: Merged upstreammainand resolved the import conflicts from #6009 by keeping both sets of imports. - Server guard parsing (
server.ts): Switched.onBeforeHandleto useextractBearerToken(request.headers.get("authorization") ?? undefined), ensuring missing/malformedBearerprefixes consistently return401 Unauthorizedinstead of slipping through to the POST handler. - Reject
AUTH_JWT_SECRET="random"(jwt.ts): Added an explicit check inresolveSecret()to throw if the normalized secret is"random". - Clean up
validateToken(auth-api.ts): Removed the unusedvalidateTokenhelper and its corresponding test block inauth-api.spec.ts. - Frontend headers (
agent.service.ts): Removed redundant emptyagentHeaders()calls onsyncAgentsWithBackend,getAllAgents, andfetchModelTypes, while retainingX-Agent-Workflow-IdoncreateAgent. - Comment accuracy (
AccessControlResource.scala): Updated the doc comment to reflect returning401on missing/invalid tokens and403for unauthorized roles. - PR Description: Updated the description to accurately reflect the latest revision (including the
PATCHhandler, anchored regex,403role rejections, and1008WebSocket close code).
All 357 agent-service tests pass, and TypeScript typechecking is clean. Ready for another look!
|
👋 Thanks for opening this pull request, @Alwaysgaurav1! It looks like the pull request description doesn't quite follow our template yet:
Filling out the template helps reviewers understand and triage your contribution faster. Please edit the description to complete it. This message will disappear automatically once the template is followed. You can find the template prompts by editing the description, or see CONTRIBUTING.md for the full contribution flow. |
bobbai00
left a comment
There was a problem hiding this comment.
🔴 5 resolved · 1 open · 6 new (6 new = 2 newly introduced · 4 late catches)
The five round-2 code and description findings are fixed, and their threads are resolved. The class-comment polish is only partly fixed, so I replied on its thread. Both new blockers are mechanical. The four late catches are my own misses from earlier rounds.
Design & architecture (2)
server.ts:173: the guard runs after body validation, so unauthenticated bad bodies get 400, not 401 (advisory, see inline)jwt.ts:28:JwtAuthhas no pointer back to this verifier (advisory, see inline)
Correctness (1)
agent.service.ts:833: this layout failsyarn format:ci, so all three frontend jobs are red (must-fix, see inline)
Conventions (1)
jwt.ts:92: the description lost its generative-AI tooling section (must-fix, see inline)
Polish: 2 quick touch-ups (see inline comments).
Verification trace
I checked each round-2 thread against ff51a5d instead of trusting the reply, by probing buildApp() from this tree. A raw Authorization: <jwt> gets 401 on GET and POST. An unauthenticated POST /api/agents with {} gets 400 with the schema, and 401 with a valid body. On elysia 1.4.32, throwing from onTransform gives 401 for both bodies. Prettier rewrites exactly lines 833-849, and ESLint is clean. The agent-service and access-control-service CI jobs pass, but the frontend tests never ran because format:ci fails first.
| * 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 { |
There was a problem hiding this 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 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.
bobbai00
left a comment
There was a problem hiding this comment.
🔴 6 resolved · 1 open · 2 new (2 new = 2 newly introduced · 0 late catches)
All six round-3 findings and the round-2 class-comment polish are fixed, and I resolved their threads. The one open item is still the description's missing generative-AI tooling section.
Conventions (2)
jwt.ts:94: the description still lacks the generative-AI tooling section (must-fix, open thread)server.ts:177: the description still calls this an.onBeforeHandleguard (advisory, see inline)
Polish: 1 quick touch-up (see inline comments).
Verification trace
I checked each round-3 thread against 6e43673 instead of the commit message. Probing buildApp() from this tree, an unauthenticated POST /api/agents gets 401 for both {} and a valid body, and an INACTIVE token gets 403. A valid token with {} still gets the validation 400, and malformed JSON gets a plain 400 because parsing runs first. fetchModelTypes is identical to main, and format:ci passes in the frontend jobs on all three OSes. The red checks are unrelated: an amber-integration Parquet export timeout and a code-editor spec timeout, both on macOS.
| // separately in its open() handler via the access-token query param. | ||
| // Using onTransform ensures authentication runs before body schema validation, | ||
| // so unauthenticated requests receive 401/403 rather than validation 400s. | ||
| .onTransform(({ request }) => { |
There was a problem hiding this comment.
Advisory:
Item 1 of the PR description still calls this an .onBeforeHandle guard. Running in onTransform is what puts authentication ahead of body validation, so the squash commit should name the hook that does it. It can change in the same edit that restores the generative-AI section.
| * The `avatar` claim was `googleAvatar` until the column and the value stopped being | ||
| * Google-specific; the TypeScript reader was renamed in the same change, and both sides | ||
| * still accept the old name so tokens issued before it keep working (see [[JwtParser]] | ||
| * for when that can go). |
There was a problem hiding this comment.
Polish:
Now that the doc names two TypeScript readers, "the TypeScript reader was renamed ... both sides" no longer points at one, and agent-service reads no avatar claim. The [[JwtParser]] pointer is stale too, since #8314 removed that note. The removal condition now lives in auth.service.ts:261-263, so the suggestion states it inline.
| * The `avatar` claim was `googleAvatar` until the column and the value stopped being | |
| * Google-specific; the TypeScript reader was renamed in the same change, and both sides | |
| * still accept the old name so tokens issued before it keep working (see [[JwtParser]] | |
| * for when that can go). | |
| * The `avatar` claim was `googleAvatar` until the column and the value stopped being | |
| * Google-specific. The frontend reader and [[JwtParser]] still accept the old name, because | |
| * tokens issued before the rename stay valid for a week; the fallback can go once they have | |
| * all expired. |
### What changes were proposed in this PR? Each user now sees and opens only their own agents, and a login token needs a valid signature. | | Before | After | | --- | --- | --- | | Agent list (`GET /api/agents`) | Every user's agents | The caller's only | | Another user's agent, by id or websocket | Opens: its chat is readable, and prompts use the owner's token | 404 "Agent not found", as for an unknown id | | No token, or a forged one | Accepted: the only check read the expiry | 401 | **Another user's agent.** e2e-reader opens "Penguin species comparison", which texera shared read-only. Before, the panel lists texera's "Penguin analyst" and shows its chat, texera's question marked "You": <img width="1120" height="760" alt="Before: e2e-reader's panel shows texera's Penguin analyst and its chat" src="https://github.com/user-attachments/assets/79e3599d-c2a5-46a2-bffd-6062ff8ea4c6" /> After, it lists only e2e-reader's own agent: <img width="1120" height="760" alt="After: e2e-reader's panel shows only Plot helper" src="https://github.com/user-attachments/assets/9be5e65c-f078-459c-9642-26d59679ccd6" /> - The agent service checks the HS256 signature with `AUTH_JWT_SECRET`, read as the dashboard service reads it (`auth.conf`'s default, lowercased, never `random`). Kubernetes passes it in. - Each agent records its creator, and every route and the websocket check the caller against it. - The frontend puts the token in the agent websocket's query, like the workflow websocket. apache#9043 adds a gateway check and will follow this PR, taking over the token check. ### Any related issues, documentation, discussions? Closes apache#5268 Agent ids stay sequential: a guessed id gets the same 404 as a missing one. ### How was this PR tested? Agent-service tests cover every route and the websocket with another user's token, no token and forged tokens, and how the secret is read. Also tested in headless Chromium as two users with a real model. The second sees none of the first's agents or chat, and the owner's agent still builds and executes a workflow. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (Claude Fable 5.2, Claude Opus 5.5)
What changes were proposed in this PR?
This PR implements Phase 1 authorization for requests reaching
agent-service, providing defense-in-depth across the API gateways,access-control-service, andagent-service:agent-serviceDirect JWT Verification (config/jwt.ts,server.ts):node:crypto(createHmac,timingSafeEqual).AUTH_JWT_SECRET(falling back to candidateauth.conflocations and throwing if not found, explicitly rejecting"random"), with a 30-second clock skew tolerance..onBeforeHandleguard acrossagentsRouterinserver.tsthat enforces Bearer token extraction, rejecting missing/invalid tokens with401 Unauthorizedand inactive roles with403 Forbidden(preserving unauthenticated access to/api/healthcheck)./api/agents/:id/reactWebSocket during theopen(ws)handshake viaaccess-tokenquery parameter, closing unauthorized sockets with code1008(Policy Violation).access-control-serviceExt-Authz Route (AccessControlResource.scala):^/api/agents(/.*)?$toAccessControlResource.authorize()coveringGET,POST,PATCH, andDELETE.parseToken()and requiresREGULARorADMINuser roles (returning401for missing/invalid tokens and403for inactive/unauthorized roles).x-user-id,x-user-name,x-user-email) on HTTP 200.Gateway & Kubernetes Deployment:
bin/single-node/nginx.conf: Configuredupstream access_control_authz, internal/_agent_authsubrequest location, andauth_request /_agent_auth;on/api/agents.bin/k8s/templates/base/gateway/gateway-agent-security-policy.yaml: Added Envoy GatewaySecurityPolicypointing extAuth toaccess-control-service.bin/k8s/templates/base/agent-service/agent-service-deployment.yaml: InjectedAUTH_JWT_SECRETviatexeraEnvVars.bin/dockerfiles/agent-service.dockerfile: Bundledauth.confinto the container image.Frontend (
agent.service.ts):?access-token=${encodeURIComponent(token)}to the WebSocket connection URL instartStatePolling().X-Agent-Workflow-Idheader forwarding oncreateAgentfor consistent hash routing in Kubernetes (HTTP authorization headers are managed globally viaJwtModule).Any related issues, documentation, discussions?
Resolves #5561
How was this PR tested?
agent-serviceUnit & Integration Tests:agent-service/src/config/jwt.spec.ts: Unit tests verifying HS256 signature verification, secret resolution, clock skew tolerance, expiration, and algorithm tampering.agent-service/src/server.spec.ts: Integration tests verifying 401 on missing/invalid/expired tokens, 403 on inactive roles, 200 pass-through for valid tokens, and/api/healthcheckbypass.agent-service/src/server.ws.spec.ts: Verified WebSocket rejection with close code 1008 on missing or invalid tokens.tsc --noEmit) passes with 0 errors.access-control-serviceUnit Tests:AgentAccessAuthSpec.scala: Verified 200 OK forREGULARandADMINroles across GET/POST/PATCH/DELETE, header forwarding, 401 on missing tokens, and 403 onINACTIVErole.End-to-End Verification: