Skip to content

feat(agent-service): authenticate requests via JWT and gateway ext_authz - #9043

Open
Alwaysgaurav1 wants to merge 15 commits into
apache:mainfrom
Alwaysgaurav1:feat/5561-agent-service-auth
Open

Alwaysgaurav1 wants to merge 15 commits into
apache:mainfrom
Alwaysgaurav1:feat/5561-agent-service-auth

Conversation

@Alwaysgaurav1

@Alwaysgaurav1 Alwaysgaurav1 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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, and agent-service:

  1. agent-service Direct JWT Verification (config/jwt.ts, server.ts):

    • Replaced non-cryptographic JWT decoding with cryptographic HS256 signature verification using node:crypto (createHmac, timingSafeEqual).
    • Resolves the shared secret from AUTH_JWT_SECRET (falling back to candidate auth.conf locations and throwing if not found, explicitly rejecting "random"), with a 30-second clock skew tolerance.
    • Added an .onBeforeHandle guard across agentsRouter in server.ts that enforces Bearer token extraction, rejecting missing/invalid tokens with 401 Unauthorized and inactive roles with 403 Forbidden (preserving unauthenticated access to /api/healthcheck).
    • Enforced authentication on /api/agents/:id/react WebSocket during the open(ws) handshake via access-token query parameter, closing unauthorized sockets with code 1008 (Policy Violation).
  2. access-control-service Ext-Authz Route (AccessControlResource.scala):

    • Added an anchored route matcher ^/api/agents(/.*)?$ to AccessControlResource.authorize() covering GET, POST, PATCH, and DELETE.
    • Validates tokens using parseToken() and requires REGULAR or ADMIN user roles (returning 401 for missing/invalid tokens and 403 for inactive/unauthorized roles).
    • Forwards trusted user identity headers (x-user-id, x-user-name, x-user-email) on HTTP 200.
  3. Gateway & Kubernetes Deployment:

    • bin/single-node/nginx.conf: Configured upstream access_control_authz, internal /_agent_auth subrequest location, and auth_request /_agent_auth; on /api/agents.
    • bin/k8s/templates/base/gateway/gateway-agent-security-policy.yaml: Added Envoy Gateway SecurityPolicy pointing extAuth to access-control-service.
    • bin/k8s/templates/base/agent-service/agent-service-deployment.yaml: Injected AUTH_JWT_SECRET via texeraEnvVars.
    • bin/dockerfiles/agent-service.dockerfile: Bundled auth.conf into the container image.
  4. Frontend (agent.service.ts):

    • Attached ?access-token=${encodeURIComponent(token)} to the WebSocket connection URL in startStatePolling().
    • Retained X-Agent-Workflow-Id header forwarding on createAgent for consistent hash routing in Kubernetes (HTTP authorization headers are managed globally via JwtModule).

Any related issues, documentation, discussions?

Resolves #5561

How was this PR tested?

  • agent-service Unit & 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/healthcheck bypass.
    • agent-service/src/server.ws.spec.ts: Verified WebSocket rejection with close code 1008 on missing or invalid tokens.
    • Ran Bun test suite: 357 tests pass, 0 fail; TypeScript check (tsc --noEmit) passes with 0 errors.
  • access-control-service Unit Tests:

    • AgentAccessAuthSpec.scala: Verified 200 OK for REGULAR and ADMIN roles across GET/POST/PATCH/DELETE, header forwarding, 401 on missing tokens, and 403 on INACTIVE role.
  • End-to-End Verification:

    • Tested single-node stack behind Envoy and Nginx with valid, inactive, and absent tokens.

…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.
@github-actions github-actions Bot added feature frontend Changes related to the frontend GUI infra platform Non-amber Scala service paths agent-service labels Oct 20, 2026
@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Automated Reviewer Suggestions

Based on the git blame history of the changed files, we recommend the following reviewers:

  • Committers with relevant context: @parshimers
    You can request their reviews formally with /request-review @parshimers.

  • Contributors with relevant context: @bobbai00, @zyratlo, @aglinxinyuan
    You can notify them by mentioning @bobbai00, @zyratlo, @aglinxinyuan in a comment.

@codecov-commenter

codecov-commenter commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.91339% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.59%. Comparing base (7adc729) to head (6e43673).
⚠️ Report is 33 commits behind head on main.

Files with missing lines Patch % Lines
agent-service/src/config/jwt.ts 89.39% 7 Missing ⚠️
...exera/service/resource/AccessControlResource.scala 92.85% 1 Missing and 1 partial ⚠️
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     
Flag Coverage Δ *Carryforward flag
access-control-service 78.15% <92.85%> (+0.70%) ⬆️
agent-service 99.34% <92.92%> (-0.22%) ⬇️
amber 85.34% <ø> (ø) Carriedforward from ff51a5d
computing-unit-managing-service 63.88% <ø> (-0.18%) ⬇️
config-service 87.50% <ø> (-0.24%) ⬇️
file-service 82.16% <ø> (ø)
frontend 96.41% <ø> (-0.01%) ⬇️ Carriedforward from ff51a5d
notebook-migration-service 83.77% <ø> (ø)
pyamber 98.50% <ø> (ø) Carriedforward from ff51a5d
result-service 85.71% <ø> (?)
workflow-compiling-service 78.30% <ø> (ø)

*This pull request uses carry forward flags. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions github-actions Bot added the ci changes related to CI label Oct 20, 2026
@github-actions

github-actions Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Benchmark changes need a look

🟢 4 better · 🔴 1 worse · ⚪ 10 noise (<±5%) · 0 without baseline

Compared against main 7adc729 benchmarked on this same runner, so the delta is largely free of cross-runner hardware noise. The "7d avg" column still reflects the gh-pages dashboard. Treat <±5% as noise unless repeated.

Dashboard · Run

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
bobbai00 self-requested a review October 21, 2026 08:40

@bobbai00 bobbai00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread agent-service/src/server.ts Resolved
Comment thread agent-service/src/config/jwt.ts Resolved
Comment thread agent-service/src/server.ts Resolved
Comment thread agent-service/src/config/jwt.ts Resolved
Comment thread .github/workflows/build.yml Resolved
Comment thread bin/single-node/nginx.conf Resolved
@Alwaysgaurav1 Alwaysgaurav1 changed the title feat(agent): authenticate agent-service requests via JWT + gateway ext_authz (#5561) feat(agent-service): authenticate requests via JWT and gateway ext_authz Oct 22, 2026
@Alwaysgaurav1

Copy link
Copy Markdown
Contributor Author

@bobbai00

Thanks for the thorough review and verification trace! I have addressed all items in commit 7eadccc:

🔴 Must-Fix

  • Compilation in AgentAccessAuthSpec.scala: Removed u.setGoogleId(null) (removed since refactor(common/auth): move login credentials to auth_provider #7055) and called JwtAuth.jwtClaims(u) without the invalid parameter.
  • Added @PATCH to AccessControlResource.scala: Added the @PATCH annotation/handler mirroring authorizePut so settings saves behind Envoy ext_authz no longer 405. Added a corresponding unit test in AgentAccessAuthSpec.scala.
  • Anchored apiAgents Regex: Anchored to ^/?(?:auth/)?api/agents(?:/.*)?$ so dynamic routes like auth/wsapi/x/api/agents are not inadvertently matched. Added a negative test for /wsapi.
  • PR Title: Updated title to feat(agent-service): authenticate requests via JWT and gateway ext_authz to follow module scoping and length conventions.

🟡 Advisory & Simplifications

  • In-Service Role Guard: .onBeforeHandle in server.ts now enforces REGULAR or ADMIN roles, rejecting INACTIVE users with 403 to match gateway behavior (with tests added for 403 INACTIVE and 200 ADMIN).
  • Fail-Fast Secret Resolution: Dropped the hardcoded fallback secret in jwt.ts; the service now throws on startup if neither AUTH_JWT_SECRET nor auth.conf is found.
  • WebSocket Rejection Code: Rejected sockets in open(ws) now close with code 1008 (Policy Violation) so the frontend detects denied access rather than normal completion.
  • Frontend Authorization Header: Dropped redundant manual Authorization header addition in agentHeaders() (letting Angular's JwtModule handle it automatically), while keeping X-Agent-Workflow-Id and the WebSocket ?access-token= query param.
  • K8s Secret Scoping: Filtered texeraEnvVars in agent-service-deployment.yaml to inject only AUTH_JWT_SECRET.
  • Dead Code Cleanup: Removed redundant token validation logic and unused ERROR_STATUS entries in server.ts.
  • Workflow / sbt Bump: Noted; will rebase out the setup-sbt workflow commits once fix(deps, ci): bump sbt/setup-sbt to v1.5.12 to restore CI #9064 merges.

🟢 Polish

  • Corrected the routing comment in bin/single-node/nginx.conf.
  • Clarified the header forwarding comment in AccessControlResource.scala.

Verification:

  • Formatted all touched files with Prettier.
  • All 330 unit & WebSocket integration tests in agent-service pass (bun test).

Please take another look when you get a chance!

@github-actions github-actions Bot removed the ci changes related to CI label Oct 25, 2026
@Alwaysgaurav1

Copy link
Copy Markdown
Contributor Author

@bobbai00 could you plss review it again.

@chenlica

Copy link
Copy Markdown
Contributor

@dzueck Do you want to take a look at this PR as well?

@chenlica

chenlica commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

@dzueck Please check.

@bobbai00 bobbai00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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=random is 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: validateToken has no production caller left (advisory, see inline)
  • agent.service.ts:255: three agentHeaders() 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.

Comment thread agent-service/src/server.ts Resolved
Comment thread agent-service/src/config/jwt.ts Resolved
Comment thread agent-service/src/api/auth-api.ts Resolved

@Alwaysgaurav1 Alwaysgaurav1 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough review, @bobbai00! All findings from this round have been addressed in commit ff51a5d:

  • Merge main: Merged upstream main and resolved the import conflicts from #6009 by keeping both sets of imports.
  • Server guard parsing (server.ts): Switched .onBeforeHandle to use extractBearerToken(request.headers.get("authorization") ?? undefined), ensuring missing/malformed Bearer prefixes consistently return 401 Unauthorized instead of slipping through to the POST handler.
  • Reject AUTH_JWT_SECRET="random" (jwt.ts): Added an explicit check in resolveSecret() to throw if the normalized secret is "random".
  • Clean up validateToken (auth-api.ts): Removed the unused validateToken helper and its corresponding test block in auth-api.spec.ts.
  • Frontend headers (agent.service.ts): Removed redundant empty agentHeaders() calls on syncAgentsWithBackend, getAllAgents, and fetchModelTypes, while retaining X-Agent-Workflow-Id on createAgent.
  • Comment accuracy (AccessControlResource.scala): Updated the doc comment to reflect returning 401 on missing/invalid tokens and 403 for unauthorized roles.
  • PR Description: Updated the description to accurately reflect the latest revision (including the PATCH handler, anchored regex, 403 role rejections, and 1008 WebSocket close code).

All 357 agent-service tests pass, and TypeScript typechecking is clean. Ready for another look!

@github-actions

Copy link
Copy Markdown
Contributor

👋 Thanks for opening this pull request, @Alwaysgaurav1!

It looks like the pull request description doesn't quite follow our template yet:

  • The Was this PR authored or co-authored using generative AI tooling? section is missing; please keep the template's headings.

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 bobbai00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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: JwtAuth has no pointer back to this verifier (advisory, see inline)

Correctness (1)

  • agent.service.ts:833: this layout fails yarn 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread agent-service/src/server.ts Resolved
Comment thread agent-service/src/config/jwt.ts Resolved
Comment thread agent-service/src/config/jwt.ts Resolved

@bobbai00 bobbai00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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 .onBeforeHandle guard (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 }) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +59 to +62
* 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).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
* 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.

renovate-bot pushed a commit to renovate-bot/apache-_-texera that referenced this pull request Nov 25, 2026
### 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)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-service common feature frontend Changes related to the frontend GUI infra platform Non-amber Scala service paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Authorize agent-service requests in the access-control-service (JWT authn + per-agent authz)

4 participants