From f128c4bc92a7fdfe3948e89acfc45678a10cd7a2 Mon Sep 17 00:00:00 2001 From: acx10 Date: Sat, 15 Aug 2026 08:00:00 -0600 Subject: [PATCH] Prevent token refresh deadlocks --- .../security/auth-interceptor.service.spec.ts | 59 +++++++++++++++++++ .../core/security/auth-interceptor.service.ts | 25 ++++---- 2 files changed, 69 insertions(+), 15 deletions(-) create mode 100644 booklore-ui/src/app/core/security/auth-interceptor.service.spec.ts diff --git a/booklore-ui/src/app/core/security/auth-interceptor.service.spec.ts b/booklore-ui/src/app/core/security/auth-interceptor.service.spec.ts new file mode 100644 index 000000000..3b688c187 --- /dev/null +++ b/booklore-ui/src/app/core/security/auth-interceptor.service.spec.ts @@ -0,0 +1,59 @@ +import {HttpErrorResponse, HttpHandlerFn, HttpRequest} from '@angular/common/http'; +import {TestBed} from '@angular/core/testing'; +import {Subject, firstValueFrom, throwError} from 'rxjs'; +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {AuthService} from '../../shared/service/auth.service'; +import {API_CONFIG} from '../config/api-config'; +import {AuthInterceptorService} from './auth-interceptor.service'; + +describe('AuthInterceptorService', () => { + const getInternalAccessToken = vi.fn(() => 'expired-access-token'); + const internalRefreshToken = vi.fn(); + const saveInternalTokens = vi.fn(); + const forceLogout = vi.fn(); + + beforeEach(() => { + vi.clearAllMocks(); + TestBed.configureTestingModule({ + providers: [{ + provide: AuthService, + useValue: {getInternalAccessToken, internalRefreshToken, saveInternalTokens, forceLogout} + }] + }); + }); + + it('does not retry a 401 response from the refresh endpoint', async () => { + const request = new HttpRequest('POST', `${API_CONFIG.BASE_URL}/api/v1/auth/refresh`, null); + const unauthorized = new HttpErrorResponse({status: 401}); + + const response = TestBed.runInInjectionContext(() => + AuthInterceptorService(request, () => throwError(() => unauthorized)) + ); + + await expect(firstValueFrom(response)).rejects.toBe(unauthorized); + expect(internalRefreshToken).not.toHaveBeenCalled(); + }); + + it('fails every queued request when token refresh fails', async () => { + const refreshResult = new Subject<{accessToken: string; refreshToken: string}>(); + internalRefreshToken.mockReturnValue(refreshResult); + const unauthorized = new HttpErrorResponse({status: 401}); + const next: HttpHandlerFn = vi.fn(() => throwError(() => unauthorized)); + + const firstRequest = interceptProtectedRequest('/api/v1/books', next); + const secondRequest = interceptProtectedRequest('/api/v1/users/me', next); + const firstResult = firstValueFrom(firstRequest); + const secondResult = firstValueFrom(secondRequest); + + refreshResult.error(unauthorized); + + await expect(firstResult).rejects.toBe(unauthorized); + await expect(secondResult).rejects.toBe(unauthorized); + expect(forceLogout).toHaveBeenCalledOnce(); + }); + + function interceptProtectedRequest(path: string, next: HttpHandlerFn) { + const request = new HttpRequest('GET', `${API_CONFIG.BASE_URL}${path}`); + return TestBed.runInInjectionContext(() => AuthInterceptorService(request, next)); + } +}); diff --git a/booklore-ui/src/app/core/security/auth-interceptor.service.ts b/booklore-ui/src/app/core/security/auth-interceptor.service.ts index 6a78e02e9..be3c04648 100644 --- a/booklore-ui/src/app/core/security/auth-interceptor.service.ts +++ b/booklore-ui/src/app/core/security/auth-interceptor.service.ts @@ -1,24 +1,23 @@ import {HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest} from '@angular/common/http'; import {inject} from '@angular/core'; -import {Router} from '@angular/router'; -import {catchError, filter, switchMap, take} from 'rxjs/operators'; -import {BehaviorSubject, Observable, throwError} from 'rxjs'; +import {catchError, switchMap, take} from 'rxjs/operators'; +import {Observable, ReplaySubject, throwError} from 'rxjs'; import {AuthService} from '../../shared/service/auth.service'; import {API_CONFIG} from '../config/api-config'; export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => { const authService = inject(AuthService); - const router = inject(Router); const token = authService.getInternalAccessToken(); const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`); + const isRefreshRequest = req.url === `${API_CONFIG.BASE_URL}/api/v1/auth/refresh`; const authReq = (token && isApiRequest) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req; return next(authReq).pipe( catchError((error: HttpErrorResponse) => { - if (error.status === 401) { - return handle401Error(authService, authReq, next, router); + if (error.status === 401 && !isRefreshRequest) { + return handle401Error(authService, authReq, next); } return throwError(() => error); }) @@ -26,12 +25,12 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler }; let isRefreshing = false; -const refreshTokenSubject = new BehaviorSubject(null); +let refreshTokenSubject = new ReplaySubject(1); -function handle401Error(authService: AuthService, request: HttpRequest, next: HttpHandlerFn, router: Router): Observable> { +function handle401Error(authService: AuthService, request: HttpRequest, next: HttpHandlerFn): Observable> { if (!isRefreshing) { isRefreshing = true; - refreshTokenSubject.next(null); + refreshTokenSubject = new ReplaySubject(1); return authService.internalRefreshToken().pipe( switchMap(response => { @@ -47,14 +46,14 @@ function handle401Error(authService: AuthService, request: HttpRequest, }), catchError(err => { isRefreshing = false; - forceLogout(authService, router); + refreshTokenSubject.error(err); + authService.forceLogout('session_expired'); return throwError(() => err); }) ); } return refreshTokenSubject.pipe( - filter(token => token !== null), take(1), switchMap(token => next(request.clone({ @@ -63,7 +62,3 @@ function handle401Error(authService: AuthService, request: HttpRequest, ) ); } - -function forceLogout(authService: AuthService, router: Router): void { - authService.logout(); -}