From 7f38de817bed76d198a9790b34fabf0620c34af7 Mon Sep 17 00:00:00 2001 From: Zach Date: Thu, 11 Jun 2026 20:29:54 -0400 Subject: [PATCH] fix(download): stream book downloads instead of buffering in browser (#1718) --- .../config/security/SecurityConfig.java | 21 ++- .../service/file-download.service.spec.ts | 126 ++++++------------ .../shared/service/file-download.service.ts | 46 +++---- 3 files changed, 76 insertions(+), 117 deletions(-) diff --git a/backend/src/main/java/org/booklore/config/security/SecurityConfig.java b/backend/src/main/java/org/booklore/config/security/SecurityConfig.java index 60988fea3..944007aa7 100644 --- a/backend/src/main/java/org/booklore/config/security/SecurityConfig.java +++ b/backend/src/main/java/org/booklore/config/security/SecurityConfig.java @@ -219,6 +219,23 @@ public class SecurityConfig { @Bean @Order(8) + public SecurityFilterChain bookDownloadSecurityChain(HttpSecurity http, QueryParameterJwtFilter queryParameterJwtFilter) throws Exception { + http + .securityMatcher("/api/v1/books/*/download", "/api/v1/books/*/download-all", "/api/v1/books/*/files/*/download") + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .anyRequest().permitAll() + ) + .addFilterBefore(queryParameterJwtFilter, UsernamePasswordAuthenticationFilter.class) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) + .addFilterAfter(authenticationCheckFilter, UsernamePasswordAuthenticationFilter.class); + return http.build(); + } + + @Bean + @Order(9) public SecurityFilterChain wsSecurityChain(HttpSecurity http) throws Exception { http .securityMatcher("/ws/**") @@ -238,7 +255,7 @@ public class SecurityConfig { } @Bean - @Order(9) + @Order(10) public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception { var parser = new PathPatternParser(); final List matchPatterns = Stream.of( @@ -289,7 +306,7 @@ public class SecurityConfig { } @Bean - @Order(10) + @Order(11) public SecurityFilterChain staticResourcesSecurityChain(HttpSecurity http) throws Exception { http .csrf(AbstractHttpConfigurer::disable) diff --git a/frontend/src/app/shared/service/file-download.service.spec.ts b/frontend/src/app/shared/service/file-download.service.spec.ts index 0efd841ce..601766654 100644 --- a/frontend/src/app/shared/service/file-download.service.spec.ts +++ b/frontend/src/app/shared/service/file-download.service.spec.ts @@ -1,135 +1,85 @@ -import {HttpHeaders, provideHttpClient} from '@angular/common/http'; -import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import {TestBed} from '@angular/core/testing'; +import {of, throwError} from 'rxjs'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {FileDownloadService} from './file-download.service'; +import {AuthService} from './auth.service'; +import {API_CONFIG} from '../../core/config/api-config'; describe('FileDownloadService', () => { + const apiUrl = `${API_CONFIG.BASE_URL}/api/v1/books/1/download`; let service: FileDownloadService; - let httpTestingController: HttpTestingController; + let ensureAccessToken: ReturnType; beforeEach(() => { + ensureAccessToken = vi.fn().mockReturnValue(of('tok')); + TestBed.resetTestingModule(); TestBed.configureTestingModule({ providers: [ - provideHttpClient(), - provideHttpClientTesting(), FileDownloadService, + {provide: AuthService, useValue: {ensureAccessToken}}, ] }); service = TestBed.inject(FileDownloadService); - httpTestingController = TestBed.inject(HttpTestingController); }); afterEach(() => { - httpTestingController.verify(); + vi.restoreAllMocks(); TestBed.resetTestingModule(); }); - it('downloads a blob', () => { + function stubAnchor() { const click = vi.fn(); const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement; - const createElementSpy = vi.spyOn(document, 'createElement').mockReturnValue(anchor); - const createObjectUrlSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:download'); - const revokeObjectUrlSpy = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + vi.spyOn(document, 'createElement').mockReturnValue(anchor); + return {anchor, click}; + } - service.downloadFile('/files/1', 'fallback.epub'); + it('navigates to the download url with a fresh access token appended', () => { + const {anchor, click} = stubAnchor(); - const request = httpTestingController.expectOne('/files/1'); - expect(request.request.method).toBe('GET'); - expect(request.request.responseType).toBe('blob'); - request.flush(new Blob(['content']), { - headers: new HttpHeaders({ - 'Content-Disposition': "attachment; filename*=UTF-8''server%20name.epub", - }), - }); + service.downloadFile(apiUrl, 'book.epub'); - expect(createElementSpy).toHaveBeenCalledWith('a'); - expect(createObjectUrlSpy).toHaveBeenCalled(); + expect(ensureAccessToken).toHaveBeenCalledOnce(); + expect(anchor.href).toBe(`${apiUrl}?token=tok`); + expect(anchor.download).toBe('book.epub'); expect(click).toHaveBeenCalledOnce(); - expect(revokeObjectUrlSpy).toHaveBeenCalledWith('blob:download'); }); - it('downloads using the utf-8-only filename from the response header', () => { - const click = vi.fn(); - const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement; - vi.spyOn(document, 'createElement').mockReturnValue(anchor); + it('uses & as the separator when the url already has a query string', () => { + const {anchor} = stubAnchor(); - service.downloadFile('/files/1', 'fallback.epub'); + service.downloadFile(`${apiUrl}?foo=bar`, 'book.epub'); - const request = httpTestingController.expectOne('/files/1'); - request.flush(new Blob(['content']), { - headers: new HttpHeaders({ - 'Content-Disposition': "attachment; filename*=UTF-8''server%20name.epub", - }), - }); - - expect(anchor.download).toBe('server name.epub'); + expect(anchor.href).toBe(`${apiUrl}?foo=bar&token=tok`); }); - it('downloads a blob using the ascii filename from the response header', () => { - const click = vi.fn(); - const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement; - vi.spyOn(document, 'createElement').mockReturnValue(anchor); + it('url-encodes the token', () => { + ensureAccessToken.mockReturnValue(of('a b/c+d')); + const {anchor} = stubAnchor(); - service.downloadFile('/files/1', 'fallback.epub'); + service.downloadFile(apiUrl, 'book.epub'); - const request = httpTestingController.expectOne('/files/1'); - request.flush(new Blob(['content']), { - headers: new HttpHeaders({ - 'Content-Disposition': "attachment; filename=\"server name.epub\"", - }), - }); - - expect(anchor.download).toBe('server name.epub'); + expect(anchor.href).toBe(`${apiUrl}?token=a%20b%2Fc%2Bd`); }); - it('downloads a blob using the unquoted ascii filename from the response header', () => { - const click = vi.fn(); - const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement; - vi.spyOn(document, 'createElement').mockReturnValue(anchor); + it('does not append the token to a non-API (cross-origin) url', () => { + const {anchor, click} = stubAnchor(); - service.downloadFile('/files/1', 'fallback.epub'); + service.downloadFile('https://example.com/evil', 'book.epub'); - const request = httpTestingController.expectOne('/files/1'); - request.flush(new Blob(['content']), { - headers: new HttpHeaders({ - 'Content-Disposition': "attachment; filename=server_name.epub", - }), - }); - - expect(anchor.download).toBe('server_name.epub'); + expect(anchor.href).toBe('https://example.com/evil'); + expect(click).toHaveBeenCalledOnce(); }); - it('downloads a blob using the both utf-8 and ascii from the response header', () => { - const click = vi.fn(); - const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement; - vi.spyOn(document, 'createElement').mockReturnValue(anchor); + it('does not start a download when the token refresh fails', () => { + ensureAccessToken.mockReturnValue(throwError(() => new Error('refresh failed'))); + const createElement = vi.spyOn(document, 'createElement'); - service.downloadFile('/files/1', 'fallback.epub'); + service.downloadFile(apiUrl, 'book.epub'); - const request = httpTestingController.expectOne('/files/1'); - request.flush(new Blob(['content']), { - headers: new HttpHeaders({ - 'Content-Disposition': "attachment; filename=\"server name.epub\"; filename*=UTF-8''server%20name.epub", - }), - }); - - expect(anchor.download).toBe('server name.epub'); - }); - - it('falls back to the provided filename when the response has no content-disposition header', () => { - const click = vi.fn(); - const anchor = {href: '', download: '', click} as unknown as HTMLAnchorElement; - vi.spyOn(document, 'createElement').mockReturnValue(anchor); - - service.downloadFile('/files/2', 'fallback.epub'); - - const request = httpTestingController.expectOne('/files/2'); - request.flush(new Blob(['content'])); - - expect(anchor.download).toBe('fallback.epub'); + expect(createElement).not.toHaveBeenCalled(); }); }); diff --git a/frontend/src/app/shared/service/file-download.service.ts b/frontend/src/app/shared/service/file-download.service.ts index 9374a6e40..10b66c1d8 100644 --- a/frontend/src/app/shared/service/file-download.service.ts +++ b/frontend/src/app/shared/service/file-download.service.ts @@ -1,41 +1,33 @@ import {inject, Injectable} from '@angular/core'; -import {HttpClient} from '@angular/common/http'; +import {DOCUMENT} from '@angular/common'; +import {AuthService} from './auth.service'; +import {API_CONFIG} from '../../core/config/api-config'; @Injectable({ providedIn: 'root' }) export class FileDownloadService { - private http = inject(HttpClient); + private readonly document = inject(DOCUMENT); + private authService = inject(AuthService); downloadFile(url: string, filename: string): void { - this.http.get(url, {responseType: 'blob', observe: 'response'}).subscribe(response => { - const blob = response.body; - if (!blob) return; - - const resolvedFilename = this.extractFilename(response.headers.get('Content-Disposition')) ?? filename; - const objectUrl = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = objectUrl; - link.download = resolvedFilename; - link.click(); - URL.revokeObjectURL(objectUrl); + this.authService.ensureAccessToken().subscribe({ + next: token => this.triggerDownload(url, filename, token), + error: () => undefined }); } - private extractFilename(contentDisposition: string | null): string | null { - if (!contentDisposition) return null; - const utf8Match = contentDisposition.match(/filename\*=UTF-8''([\w%\-.]+)/i); - if (utf8Match) { - try { - return decodeURIComponent(utf8Match[1]); - } catch { - // Do nothing in this case and fall back to the ascii filename. - } + private triggerDownload(url: string, filename: string, token: string): void { + const link = this.document.createElement('a'); + link.href = this.appendToken(url, token); + link.download = filename; + link.click(); + } + + private appendToken(url: string, token: string): string { + if (!url.startsWith(`${API_CONFIG.BASE_URL}/api/`)) { + return url; } - const match = contentDisposition.match(/filename=(?:"([^"]+)"|([^"; ]+))/i) - if (match) { - return match[1] ?? match[2]; - } - return null; + return `${url}${url.includes('?') ? '&' : '?'}token=${encodeURIComponent(token)}`; } }