Repository navigation
fix(frontend): handle 401 by clearing session, skip sending expired JWTs - #5392
Conversation
…JWTs Adds an UnauthorizedHttpInterceptor that, on a 401 response to a request that carried Authorization, clears the stored JWT, shows a notification, and routes to /about with returnUrl so the user can be sent back after re-login. 401s on anonymous requests pass through unchanged. Flips JwtModule.forRoot's skipWhenExpired from false to true so a stale localStorage token is no longer attached to public pre-login endpoints (/api/config/gui, /api/config/user-system) — the exact scenario that caused the revert of apache#4903 in apache#5025. Closes apache#5391.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #5392 +/- ##
============================================
- Coverage 51.62% 51.60% -0.02%
Complexity 2420 2420
============================================
Files 1056 1057 +1
Lines 41046 41140 +94
Branches 4407 4439 +32
============================================
+ Hits 21190 21231 +41
- Misses 18617 18669 +52
- Partials 1239 1240 +1
*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:
|
Two adversarial-review findings on the previous commit: 1. JwtModule blanket-attaches Authorization to every request, including POST /api/auth/login. A wrong-password 401 there carried the user's existing token and would be misread as "session invalid", kicking an already-authenticated user out the moment they fat-fingered a re-login. Add an allowlist regex /\/auth\/(login|register|refresh|google\/login)/ that short-circuits the interceptor for these URLs. 2. A burst of 8-10 parallel dashboard requests, all 401'd by a server-side revoke, would fire 8 toasts and 8 router.navigate calls. Route the logout through UserService.logout() so isLogin() flips to false on the first 401; subsequent 401s in the burst see isLogin() === false and skip their side effects. The same flag re-arms automatically after a successful re-login. UserService is resolved lazily via Injector because it transitively depends on HttpClient and direct injection would form a DI cycle through the interceptor chain.
|
I am testing it. also trying add more fix and tests. Please help test as well |
I was asking for the manual testing part in the PR description. I'm not sure whether changes to the PR description are considered changes or if only code changes are counted. |
xuang7
left a comment
There was a problem hiding this comment.
Tested locally with no issues so far. Please hold off on merging for now. The backport workflow is not working at the moment. I will merge it once the backport is ready, thank you.
|
Thanks, @xuang7 . The backport should be fixed. Please check. |
…WTs (#5392) ### What changes were proposed in this PR? Adds `UnauthorizedHttpInterceptor` that watches every HTTP response: when the server returns 401 to a request that carried an `Authorization` header, it routes the logout through `UserService.logout()` (which clears the JWT and broadcasts `userChanged(undefined)` so header / dashboard / in-memory state stay in sync), surfaces a "session expired" notification, and routes to `/about` with `returnUrl`. 401 responses to anonymous or auth-endpoint requests pass through unchanged so a 401 on a public endpoint never wipes a freshly-stored token, and a wrong-password 401 on `/auth/login` cannot kick an already-authenticated user out. Two adversarial-review findings (caught during self-review, fixed in commit 2): 1. **Auth-endpoint allowlist.** `JwtModule` blanket-attaches `Authorization` to every request, including `POST /api/auth/login`. A wrong-password 401 there carries the user's existing token and would be misread as "session invalid", kicking an already-authenticated user out the moment they fat-finger a re-login. Allowlist regex `\/auth\/(login|register|refresh|google\/login)` short-circuits the interceptor for these URLs. 2. **Concurrent 401 dedup.** A burst of 8-10 parallel dashboard requests, all 401'd by a server-side revoke, would fire 8 toasts and 8 `router.navigate` calls. Routing the logout through `UserService.logout()` (which flips `isLogin()` from true to false) gives natural dedup: only the first 401 sees `isLogin() === true` and fires side effects; the rest of the burst short-circuits. The flag re-arms automatically after a successful re-login. Flips `JwtModule.forRoot`'s `skipWhenExpired` from `false` to `true`, so a stale `localStorage` token is no longer auto-appended to public pre-login endpoints (`/api/config/gui`, `/api/config/user-system`). That auto-append is the exact mechanism that caused the revert of #4903 in #5025 — without it, an expired token reaches public endpoints, gets rejected, and breaks the login page before the user can re-authenticate. `UserService` is resolved lazily via `Injector` inside `catchError` because it transitively depends on `HttpClient`, and direct injection would form a DI cycle through the interceptor chain. ### Any related issues, documentation, discussions? Closes #5391. Prerequisite for a re-attempt of #4901 (whose first try, #4903, was reverted by #5025 because of #5026). Discussion: https://lists.apache.org/thread/w5jmczrffxd5doc5hnss2zm7dbhnbhyy ### How was this PR tested? Added `unauthorized-http-interceptor.service.spec.ts` with 12 cases covering: 401 with Authorization → logout + notify + navigate; 401 without Authorization → no-op; non-401 with Authorization → no-op; root path → omits `returnUrl`; auth-endpoint URLs (login / register / refresh / google/login, with and without query strings) → no-op; over-broad URL match guard (`recent-logins` still logs out); concurrent 401 burst → exactly one side-effect set; re-arms after re-login. Tested manually as well. ### Was this PR authored or co-authored using generative AI tooling? (backported from commit 749798d) Generated-by: Claude Code (Opus 4.7)
|
Backport to |
### What changes were proposed in this PR?
Replaces the lazy pass-through behavior in `common/auth/JwtAuthFilter`
with an RFC 6750 eager 401 + `WWW-Authenticate` challenge. Missing
`Authorization` throws the bare `Bearer` challenge; an invalid token
throws `error="invalid_token"` so a well-behaved client can distinguish
"please log in" from "your stored token is invalid, discard it". Valid
tokens populate a `SecurityContext` exactly as before.
Endpoints that need to serve anonymous traffic opt out with `@PermitAll`
(JSR-250). This PR audits every resource method in the 5 microservices
and applies `@PermitAll` where the lazy filter previously made it
implicit:
- 5x `HealthCheckResource` (liveness probes)
- `AccessControlResource` `/auth/*` (routing proxy that authenticates
itself via `parseToken` in the resource body)
- `LiteLLMProxyResource` `/chat/*`, `LiteLLMModelsResource` `/models`
(preserve current "gated only by `guiWorkflowWorkspaceCopilotEnabled`"
behavior; whether these should require an authenticated user is a
separate hardening decision)
- `DatasetResource`: 5 endpoints with `/public-*` or `/publicVersion`
paths, plus `/{did}/cover` and `/{did}/cover-url` which already take
`@Auth Optional[SessionUser]` for opt-in user context
`UnauthorizedException` + `UnauthorizedExceptionMapper` carry the
`WWW-Authenticate` challenge to the JAX-RS edge. The exception extends
`RuntimeException` (not `WebApplicationException`) so unit tests can run
without a Jersey `RuntimeDelegate` on the classpath, and is constructed
with `writableStackTrace=false` to avoid `fillInStackTrace` cost on the
auth hot path.
### Any related issues, documentation, discussions?
Closes #4901. The earlier attempt at this fix, #4903, was reverted in
#5025 because expired tokens from `localStorage` were piggy-backed onto
`/api/config/gui` and broke the login page (#5026). PR #5392 has since
fixed the frontend to drop expired tokens client-side (`skipWhenExpired:
true`) and clear the session reactively on 401, so this PR can now ship
safely.
### How was this PR tested?
Added `JwtAuthFilterSpec` (header-missing / non-Bearer / invalid-token /
valid-token; method- and class-level `@PermitAll`; resource-info-absent
fallback) and `UnauthorizedExceptionMapperSpec`. Updated existing
service specs to expect 401 (from the filter) instead of 403 (from the
role filter) for missing-Authorization scenarios, and `*ServiceRunSpec`
mocks verify the new `UnauthorizedExceptionMapper` registration. `sbt
Auth/test` + 4 service specs all green; `sbt scalafmtCheckAll` clean.
Manually tested end-to-end against a running `config-service` build with
`curl` (missing / bad / valid tokens, `@PermitAll` healthcheck and
pre-login) and in the browser with a forged JWT in localStorage to
confirm the eager 401 path interoperates cleanly with PR #5392's 401
interceptor.
### Was this PR authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Opus 4.7)
### What changes were proposed in this PR?
Replaces the lazy pass-through behavior in `common/auth/JwtAuthFilter`
with an RFC 6750 eager 401 + `WWW-Authenticate` challenge. Missing
`Authorization` throws the bare `Bearer` challenge; an invalid token
throws `error="invalid_token"` so a well-behaved client can distinguish
"please log in" from "your stored token is invalid, discard it". Valid
tokens populate a `SecurityContext` exactly as before.
Endpoints that need to serve anonymous traffic opt out with `@PermitAll`
(JSR-250). This PR audits every resource method in the 5 microservices
and applies `@PermitAll` where the lazy filter previously made it
implicit:
- 5x `HealthCheckResource` (liveness probes)
- `AccessControlResource` `/auth/*` (routing proxy that authenticates
itself via `parseToken` in the resource body)
- `LiteLLMProxyResource` `/chat/*`, `LiteLLMModelsResource` `/models`
(preserve current "gated only by `guiWorkflowWorkspaceCopilotEnabled`"
behavior; whether these should require an authenticated user is a
separate hardening decision)
- `DatasetResource`: 5 endpoints with `/public-*` or `/publicVersion`
paths, plus `/{did}/cover` and `/{did}/cover-url` which already take
`@Auth Optional[SessionUser]` for opt-in user context
`UnauthorizedException` + `UnauthorizedExceptionMapper` carry the
`WWW-Authenticate` challenge to the JAX-RS edge. The exception extends
`RuntimeException` (not `WebApplicationException`) so unit tests can run
without a Jersey `RuntimeDelegate` on the classpath, and is constructed
with `writableStackTrace=false` to avoid `fillInStackTrace` cost on the
auth hot path.
### Any related issues, documentation, discussions?
Closes #4901. The earlier attempt at this fix, #4903, was reverted in
#5025 because expired tokens from `localStorage` were piggy-backed onto
`/api/config/gui` and broke the login page (#5026). PR #5392 has since
fixed the frontend to drop expired tokens client-side (`skipWhenExpired:
true`) and clear the session reactively on 401, so this PR can now ship
safely.
### How was this PR tested?
Added `JwtAuthFilterSpec` (header-missing / non-Bearer / invalid-token /
valid-token; method- and class-level `@PermitAll`; resource-info-absent
fallback) and `UnauthorizedExceptionMapperSpec`. Updated existing
service specs to expect 401 (from the filter) instead of 403 (from the
role filter) for missing-Authorization scenarios, and `*ServiceRunSpec`
mocks verify the new `UnauthorizedExceptionMapper` registration. `sbt
Auth/test` + 4 service specs all green; `sbt scalafmtCheckAll` clean.
Manually tested end-to-end against a running `config-service` build with
`curl` (missing / bad / valid tokens, `@PermitAll` healthcheck and
pre-login) and in the browser with a forged JWT in localStorage to
confirm the eager 401 path interoperates cleanly with PR #5392's 401
interceptor.
### Was this PR authored or co-authored using generative AI tooling?
(backported from commit 5c2eaa2)
Generated-by: Claude Code (Opus 4.7)
…WTs (apache#5392) ### What changes were proposed in this PR? Adds `UnauthorizedHttpInterceptor` that watches every HTTP response: when the server returns 401 to a request that carried an `Authorization` header, it routes the logout through `UserService.logout()` (which clears the JWT and broadcasts `userChanged(undefined)` so header / dashboard / in-memory state stay in sync), surfaces a "session expired" notification, and routes to `/about` with `returnUrl`. 401 responses to anonymous or auth-endpoint requests pass through unchanged so a 401 on a public endpoint never wipes a freshly-stored token, and a wrong-password 401 on `/auth/login` cannot kick an already-authenticated user out. Two adversarial-review findings (caught during self-review, fixed in commit 2): 1. **Auth-endpoint allowlist.** `JwtModule` blanket-attaches `Authorization` to every request, including `POST /api/auth/login`. A wrong-password 401 there carries the user's existing token and would be misread as "session invalid", kicking an already-authenticated user out the moment they fat-finger a re-login. Allowlist regex `\/auth\/(login|register|refresh|google\/login)` short-circuits the interceptor for these URLs. 2. **Concurrent 401 dedup.** A burst of 8-10 parallel dashboard requests, all 401'd by a server-side revoke, would fire 8 toasts and 8 `router.navigate` calls. Routing the logout through `UserService.logout()` (which flips `isLogin()` from true to false) gives natural dedup: only the first 401 sees `isLogin() === true` and fires side effects; the rest of the burst short-circuits. The flag re-arms automatically after a successful re-login. Flips `JwtModule.forRoot`'s `skipWhenExpired` from `false` to `true`, so a stale `localStorage` token is no longer auto-appended to public pre-login endpoints (`/api/config/gui`, `/api/config/user-system`). That auto-append is the exact mechanism that caused the revert of apache#4903 in apache#5025 — without it, an expired token reaches public endpoints, gets rejected, and breaks the login page before the user can re-authenticate. `UserService` is resolved lazily via `Injector` inside `catchError` because it transitively depends on `HttpClient`, and direct injection would form a DI cycle through the interceptor chain. ### Any related issues, documentation, discussions? Closes apache#5391. Prerequisite for a re-attempt of apache#4901 (whose first try, apache#4903, was reverted by apache#5025 because of apache#5026). Discussion: https://lists.apache.org/thread/w5jmczrffxd5doc5hnss2zm7dbhnbhyy ### How was this PR tested? Added `unauthorized-http-interceptor.service.spec.ts` with 12 cases covering: 401 with Authorization → logout + notify + navigate; 401 without Authorization → no-op; non-401 with Authorization → no-op; root path → omits `returnUrl`; auth-endpoint URLs (login / register / refresh / google/login, with and without query strings) → no-op; over-broad URL match guard (`recent-logins` still logs out); concurrent 401 burst → exactly one side-effect set; re-arms after re-login. Tested manually as well. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (Opus 4.7)
…he#5404) ### What changes were proposed in this PR? Replaces the lazy pass-through behavior in `common/auth/JwtAuthFilter` with an RFC 6750 eager 401 + `WWW-Authenticate` challenge. Missing `Authorization` throws the bare `Bearer` challenge; an invalid token throws `error="invalid_token"` so a well-behaved client can distinguish "please log in" from "your stored token is invalid, discard it". Valid tokens populate a `SecurityContext` exactly as before. Endpoints that need to serve anonymous traffic opt out with `@PermitAll` (JSR-250). This PR audits every resource method in the 5 microservices and applies `@PermitAll` where the lazy filter previously made it implicit: - 5x `HealthCheckResource` (liveness probes) - `AccessControlResource` `/auth/*` (routing proxy that authenticates itself via `parseToken` in the resource body) - `LiteLLMProxyResource` `/chat/*`, `LiteLLMModelsResource` `/models` (preserve current "gated only by `guiWorkflowWorkspaceCopilotEnabled`" behavior; whether these should require an authenticated user is a separate hardening decision) - `DatasetResource`: 5 endpoints with `/public-*` or `/publicVersion` paths, plus `/{did}/cover` and `/{did}/cover-url` which already take `@Auth Optional[SessionUser]` for opt-in user context `UnauthorizedException` + `UnauthorizedExceptionMapper` carry the `WWW-Authenticate` challenge to the JAX-RS edge. The exception extends `RuntimeException` (not `WebApplicationException`) so unit tests can run without a Jersey `RuntimeDelegate` on the classpath, and is constructed with `writableStackTrace=false` to avoid `fillInStackTrace` cost on the auth hot path. ### Any related issues, documentation, discussions? Closes apache#4901. The earlier attempt at this fix, apache#4903, was reverted in apache#5025 because expired tokens from `localStorage` were piggy-backed onto `/api/config/gui` and broke the login page (apache#5026). PR apache#5392 has since fixed the frontend to drop expired tokens client-side (`skipWhenExpired: true`) and clear the session reactively on 401, so this PR can now ship safely. ### How was this PR tested? Added `JwtAuthFilterSpec` (header-missing / non-Bearer / invalid-token / valid-token; method- and class-level `@PermitAll`; resource-info-absent fallback) and `UnauthorizedExceptionMapperSpec`. Updated existing service specs to expect 401 (from the filter) instead of 403 (from the role filter) for missing-Authorization scenarios, and `*ServiceRunSpec` mocks verify the new `UnauthorizedExceptionMapper` registration. `sbt Auth/test` + 4 service specs all green; `sbt scalafmtCheckAll` clean. Manually tested end-to-end against a running `config-service` build with `curl` (missing / bad / valid tokens, `@PermitAll` healthcheck and pre-login) and in the browser with a forged JWT in localStorage to confirm the eager 401 path interoperates cleanly with PR apache#5392's 401 interceptor. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (Opus 4.7)
What changes were proposed in this PR?
Adds
UnauthorizedHttpInterceptorthat watches every HTTP response: when the server returns 401 to a request that carried anAuthorizationheader, it routes the logout throughUserService.logout()(which clears the JWT and broadcastsuserChanged(undefined)so header / dashboard / in-memory state stay in sync), surfaces a "session expired" notification, and routes to/aboutwithreturnUrl. 401 responses to anonymous or auth-endpoint requests pass through unchanged so a 401 on a public endpoint never wipes a freshly-stored token, and a wrong-password 401 on/auth/logincannot kick an already-authenticated user out.Two adversarial-review findings (caught during self-review, fixed in commit 2):
Auth-endpoint allowlist.
JwtModuleblanket-attachesAuthorizationto every request, includingPOST /api/auth/login. A wrong-password 401 there carries the user's existing token and would be misread as "session invalid", kicking an already-authenticated user out the moment they fat-finger a re-login. Allowlist regex\/auth\/(login|register|refresh|google\/login)short-circuits the interceptor for these URLs.Concurrent 401 dedup. A burst of 8-10 parallel dashboard requests, all 401'd by a server-side revoke, would fire 8 toasts and 8
router.navigatecalls. Routing the logout throughUserService.logout()(which flipsisLogin()from true to false) gives natural dedup: only the first 401 seesisLogin() === trueand fires side effects; the rest of the burst short-circuits. The flag re-arms automatically after a successful re-login.Flips
JwtModule.forRoot'sskipWhenExpiredfromfalsetotrue, so a stalelocalStoragetoken is no longer auto-appended to public pre-login endpoints (/api/config/gui,/api/config/user-system). That auto-append is the exact mechanism that caused the revert of #4903 in #5025 — without it, an expired token reaches public endpoints, gets rejected, and breaks the login page before the user can re-authenticate.UserServiceis resolved lazily viaInjectorinsidecatchErrorbecause it transitively depends onHttpClient, and direct injection would form a DI cycle through the interceptor chain.Any related issues, documentation, discussions?
Closes #5391. Prerequisite for a re-attempt of #4901 (whose first try, #4903, was reverted by #5025 because of #5026). Discussion: https://lists.apache.org/thread/w5jmczrffxd5doc5hnss2zm7dbhnbhyy
How was this PR tested?
Added
unauthorized-http-interceptor.service.spec.tswith 12 cases covering: 401 with Authorization → logout + notify + navigate; 401 without Authorization → no-op; non-401 with Authorization → no-op; root path → omitsreturnUrl; auth-endpoint URLs (login / register / refresh / google/login, with and without query strings) → no-op; over-broad URL match guard (recent-loginsstill logs out); concurrent 401 burst → exactly one side-effect set; re-arms after re-login.Tested manually as well.
Was this PR authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Opus 4.7)