fix(security): add access control annotations to various controllers (#312)

* fix(security): add access control annotations to various controllers

* fix(security): improve authentication checks, add null checks
This commit is contained in:
brios
2026-04-22 17:26:58 -04:00
committed by Zach Yale
parent 2fd7310e81
commit 145b94dfc9
13 changed files with 34 additions and 12 deletions
@@ -47,6 +47,10 @@ public class BookAccessAspect {
BookLoreUser user = authenticationService.getAuthenticatedUser(); BookLoreUser user = authenticationService.getAuthenticatedUser();
if (user == null) {
throw ApiError.FORBIDDEN.createException("Authentication required.");
}
if (user.getPermissions().isAdmin()) { if (user.getPermissions().isAdmin()) {
return; return;
} }
@@ -39,6 +39,10 @@ public class LibraryAccessAspect {
BookLoreUser user = authenticationService.getAuthenticatedUser(); BookLoreUser user = authenticationService.getAuthenticatedUser();
if (user == null) {
throw ApiError.FORBIDDEN.createException("Authentication required.");
}
if (user.getPermissions().isAdmin()) return; if (user.getPermissions().isAdmin()) return;
boolean hasAccess = user.getAssignedLibraries().stream().anyMatch(lib -> lib.getId().equals(libraryId)); boolean hasAccess = user.getAssignedLibraries().stream().anyMatch(lib -> lib.getId().equals(libraryId));
@@ -53,7 +53,7 @@ public class KoboAuthFilter extends OncePerRequestFilter {
var userTokenOpt = koboUserSettingsRepository.findByToken(token); var userTokenOpt = koboUserSettingsRepository.findByToken(token);
if (userTokenOpt.isEmpty()) { if (userTokenOpt.isEmpty()) {
log.warn("Invalid KOBO token: {}", token); log.warn("Invalid KOBO token");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid KOBO token"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid KOBO token");
return; return;
} }
@@ -62,7 +62,7 @@ public class KoboAuthFilter extends OncePerRequestFilter {
var userOpt = userRepository.findByIdWithDetails(userToken.getUserId()); var userOpt = userRepository.findByIdWithDetails(userToken.getUserId());
if (userOpt.isEmpty()) { if (userOpt.isEmpty()) {
log.warn("User not found for token: {}", token); log.warn("User not found for KOBO token");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User not found"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User not found");
return; return;
} }
@@ -58,9 +58,9 @@ public class KoreaderAuthFilter extends OncePerRequestFilter {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
} else { } else {
log.warn("KOReader auth failed: password mismatch for user '{}'", username); log.warn("KOReader auth failed: password mismatch");
} }
}, () -> log.warn("KOReader user '{}' not found", username)); }, () -> log.warn("KOReader user not found"));
} else { } else {
log.warn("Missing KOReader headers"); log.warn("Missing KOReader headers");
} }
@@ -42,6 +42,7 @@ public class AppSettingController {
@ApiResponse(responseCode = "200", description = "Settings updated successfully"), @ApiResponse(responseCode = "200", description = "Settings updated successfully"),
@ApiResponse(responseCode = "400", description = "Invalid request") @ApiResponse(responseCode = "400", description = "Invalid request")
}) })
@PreAuthorize("@securityUtil.isAdmin()")
@PutMapping @PutMapping
public void updateSettings(@Parameter(description = "List of settings to update") @RequestBody List<SettingRequest> settingRequests) throws JacksonException { public void updateSettings(@Parameter(description = "List of settings to update") @RequestBody List<SettingRequest> settingRequests) throws JacksonException {
for (SettingRequest settingRequest : settingRequests) { for (SettingRequest settingRequest : settingRequests) {
@@ -82,15 +82,15 @@ public class AuthenticationController {
String username = headers.get(appProperties.getRemoteAuth().getHeaderUser().toLowerCase(Locale.ROOT)); String username = headers.get(appProperties.getRemoteAuth().getHeaderUser().toLowerCase(Locale.ROOT));
String email = headers.get(appProperties.getRemoteAuth().getHeaderEmail().toLowerCase(Locale.ROOT)); String email = headers.get(appProperties.getRemoteAuth().getHeaderEmail().toLowerCase(Locale.ROOT));
String groups = headers.get(appProperties.getRemoteAuth().getHeaderGroups().toLowerCase(Locale.ROOT)); String groups = headers.get(appProperties.getRemoteAuth().getHeaderGroups().toLowerCase(Locale.ROOT));
log.debug("Remote-Auth: retrieved values from headers: name: {}, username: {}, email: {}, groups: {}", name, username, email, groups); log.debug("Remote-Auth: header values present name: {}, username: {}, email: {}, groups: {}",
log.debug("Remote-Auth: remote auth settings: {}", appProperties.getRemoteAuth()); name != null, username != null, email != null, groups != null);
if ((username == null || username.isEmpty()) && (email != null && !email.isEmpty())) { if ((username == null || username.isEmpty()) && (email != null && !email.isEmpty())) {
log.debug("Remote-Auth: username is empty, trying to find user by email: {}", email); log.debug("Remote-Auth: username is empty, trying to find user by email");
Optional<BookLoreUserEntity> user = userRepository.findByEmail(email); Optional<BookLoreUserEntity> user = userRepository.findByEmail(email);
if (user.isPresent()) { if (user.isPresent()) {
username = user.get().getUsername(); username = user.get().getUsername();
log.debug("Remote-Auth: found user by email, username: {}", username); log.debug("Remote-Auth: found user by email");
} }
} }
@@ -125,6 +125,7 @@ public class BookController {
@Operation(summary = "Get ComicInfo metadata", description = "Retrieve ComicInfo metadata for a specific book.") @Operation(summary = "Get ComicInfo metadata", description = "Retrieve ComicInfo metadata for a specific book.")
@ApiResponse(responseCode = "200", description = "ComicInfo metadata returned successfully") @ApiResponse(responseCode = "200", description = "ComicInfo metadata returned successfully")
@GetMapping("/{bookId}/cbx/metadata/comicinfo") @GetMapping("/{bookId}/cbx/metadata/comicinfo")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<?> getComicInfoMetadata( public ResponseEntity<?> getComicInfoMetadata(
@Parameter(description = "ID of the book") @PathVariable long bookId) { @Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookMetadataService.getComicInfoMetadata(bookId)); return ResponseEntity.ok(bookMetadataService.getComicInfoMetadata(bookId));
@@ -133,6 +134,7 @@ public class BookController {
@Operation(summary = "Get file metadata", description = "Extract embedded metadata from the book file.") @Operation(summary = "Get file metadata", description = "Extract embedded metadata from the book file.")
@ApiResponse(responseCode = "200", description = "File metadata returned successfully") @ApiResponse(responseCode = "200", description = "File metadata returned successfully")
@GetMapping("/{bookId}/file-metadata") @GetMapping("/{bookId}/file-metadata")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<?> getFileMetadata( public ResponseEntity<?> getFileMetadata(
@Parameter(description = "ID of the book") @PathVariable long bookId) { @Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookMetadataService.getFileMetadata(bookId)); return ResponseEntity.ok(bookMetadataService.getFileMetadata(bookId));
@@ -159,6 +161,7 @@ public class BookController {
@ApiResponse(responseCode = "404", description = "Book not found") @ApiResponse(responseCode = "404", description = "Book not found")
}) })
@PutMapping("/{bookId}/content") @PutMapping("/{bookId}/content")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId") @CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Void> replaceBookContent( public ResponseEntity<Void> replaceBookContent(
@Parameter(description = "ID of the book") @PathVariable long bookId, @Parameter(description = "ID of the book") @PathVariable long bookId,
@@ -146,6 +146,7 @@ public class BookCoverController {
@Operation(summary = "Get cover images for a book", description = "Fetch cover images for a book.") @Operation(summary = "Get cover images for a book", description = "Fetch cover images for a book.")
@ApiResponse(responseCode = "200", description = "Cover images returned successfully") @ApiResponse(responseCode = "200", description = "Cover images returned successfully")
@PostMapping("/{bookId}/metadata/covers") @PostMapping("/{bookId}/metadata/covers")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<List<CoverImage>> getImages(@Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) { public ResponseEntity<List<CoverImage>> getImages(@Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) {
return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request)); return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request));
} }
@@ -1,5 +1,6 @@
package org.booklore.controller; package org.booklore.controller;
import org.booklore.config.security.annotation.CheckBookAccess;
import org.booklore.model.dto.response.CbxPageDimension; import org.booklore.model.dto.response.CbxPageDimension;
import org.booklore.model.dto.response.CbxPageInfo; import org.booklore.model.dto.response.CbxPageInfo;
import org.booklore.service.reader.CbxReaderService; import org.booklore.service.reader.CbxReaderService;
@@ -23,6 +24,7 @@ public class CbxReaderController {
@Operation(summary = "List pages in a CBX book", description = "Retrieve a list of available page numbers for a CBX book.") @Operation(summary = "List pages in a CBX book", description = "Retrieve a list of available page numbers for a CBX book.")
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully") @ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
@GetMapping("/{bookId}/pages") @GetMapping("/{bookId}/pages")
@CheckBookAccess(bookIdParam = "bookId")
public List<Integer> listPages( public List<Integer> listPages(
@Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
@@ -32,6 +34,7 @@ public class CbxReaderController {
@Operation(summary = "Get page info for a CBX book", description = "Retrieve page information including display names for a CBX book.") @Operation(summary = "Get page info for a CBX book", description = "Retrieve page information including display names for a CBX book.")
@ApiResponse(responseCode = "200", description = "Page info returned successfully") @ApiResponse(responseCode = "200", description = "Page info returned successfully")
@GetMapping("/{bookId}/page-info") @GetMapping("/{bookId}/page-info")
@CheckBookAccess(bookIdParam = "bookId")
public List<CbxPageInfo> getPageInfo( public List<CbxPageInfo> getPageInfo(
@Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
@@ -41,6 +44,7 @@ public class CbxReaderController {
@Operation(summary = "Get page dimensions for a CBX book", description = "Retrieve width, height, and wide flag for each page in a CBX book.") @Operation(summary = "Get page dimensions for a CBX book", description = "Retrieve width, height, and wide flag for each page in a CBX book.")
@ApiResponse(responseCode = "200", description = "Page dimensions returned successfully") @ApiResponse(responseCode = "200", description = "Page dimensions returned successfully")
@GetMapping("/{bookId}/page-dimensions") @GetMapping("/{bookId}/page-dimensions")
@CheckBookAccess(bookIdParam = "bookId")
public List<CbxPageDimension> getPageDimensions( public List<CbxPageDimension> getPageDimensions(
@Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
@@ -24,6 +24,7 @@ public class KoboSettingsController {
@Operation(summary = "Get Kobo sync settings", description = "Retrieve the current user's Kobo sync settings.") @Operation(summary = "Get Kobo sync settings", description = "Retrieve the current user's Kobo sync settings.")
@ApiResponse(responseCode = "200", description = "Settings returned successfully") @ApiResponse(responseCode = "200", description = "Settings returned successfully")
@GetMapping @GetMapping
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<KoboSyncSettings> getSettings() { public ResponseEntity<KoboSyncSettings> getSettings() {
KoboSyncSettings settings = koboService.getCurrentUserSettings(); KoboSyncSettings settings = koboService.getCurrentUserSettings();
return ResponseEntity.ok(settings); return ResponseEntity.ok(settings);
@@ -1,5 +1,6 @@
package org.booklore.controller; package org.booklore.controller;
import org.booklore.config.security.annotation.CheckBookAccess;
import org.booklore.model.dto.response.PdfBookInfo; import org.booklore.model.dto.response.PdfBookInfo;
import org.booklore.service.reader.PdfReaderService; import org.booklore.service.reader.PdfReaderService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@@ -22,6 +23,7 @@ public class PdfReaderController {
@Operation(summary = "List pages in a PDF book", description = "Retrieve a list of available page numbers for a PDF book.") @Operation(summary = "List pages in a PDF book", description = "Retrieve a list of available page numbers for a PDF book.")
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully") @ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
@GetMapping("/{bookId}/pages") @GetMapping("/{bookId}/pages")
@CheckBookAccess(bookIdParam = "bookId")
public List<Integer> listPages( public List<Integer> listPages(
@Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
@@ -31,6 +33,7 @@ public class PdfReaderController {
@Operation(summary = "Get book info for a PDF book", description = "Retrieve book information including page count and hierarchical outline/table of contents.") @Operation(summary = "Get book info for a PDF book", description = "Retrieve book information including page count and hierarchical outline/table of contents.")
@ApiResponse(responseCode = "200", description = "Book info returned successfully") @ApiResponse(responseCode = "200", description = "Book info returned successfully")
@GetMapping("/{bookId}/info") @GetMapping("/{bookId}/info")
@CheckBookAccess(bookIdParam = "bookId")
public PdfBookInfo getBookInfo( public PdfBookInfo getBookInfo(
@Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) { @Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
@@ -37,6 +37,7 @@ public class TaskController {
} }
@PostMapping("/start") @PostMapping("/start")
@PreAuthorize("@securityUtil.canAccessTaskManager() or @securityUtil.isAdmin()")
public ResponseEntity<TaskCreateResponse> startTask(@RequestBody TaskCreateRequest request) { public ResponseEntity<TaskCreateResponse> startTask(@RequestBody TaskCreateRequest request) {
TaskCreateResponse response = service.runAsUser(request); TaskCreateResponse response = service.runAsUser(request);
if (response.getStatus() == TaskStatus.ACCEPTED) { if (response.getStatus() == TaskStatus.ACCEPTED) {
@@ -66,13 +66,13 @@ public class GlobalExceptionHandler {
@ExceptionHandler(AccessDeniedException.class) @ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ErrorResponse> handleAccessDeniedException(AccessDeniedException ex) { public ResponseEntity<ErrorResponse> handleAccessDeniedException(AccessDeniedException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.FORBIDDEN.value(), ex.getMessage()); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.FORBIDDEN.value(), "Access denied.");
return new ResponseEntity<>(errorResponse, HttpStatus.FORBIDDEN); return new ResponseEntity<>(errorResponse, HttpStatus.FORBIDDEN);
} }
@ExceptionHandler(NoResourceFoundException.class) @ExceptionHandler(NoResourceFoundException.class)
public ResponseEntity<ErrorResponse> handleNoResourceFoundException(NoResourceFoundException ex) { public ResponseEntity<ErrorResponse> handleNoResourceFoundException(NoResourceFoundException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND.value(), "Resource not found: " + ex.getMessage()); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND.value(), "Resource not found.");
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND); return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
} }
@@ -103,14 +103,14 @@ public class GlobalExceptionHandler {
@ExceptionHandler(IllegalStateException.class) @ExceptionHandler(IllegalStateException.class)
public ResponseEntity<ErrorResponse> handleIllegalStateException(IllegalStateException ex) { public ResponseEntity<ErrorResponse> handleIllegalStateException(IllegalStateException ex) {
log.error("Illegal state: {}", ex.getMessage(), ex); log.error("Illegal state: {}", ex.getMessage(), ex);
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.value(), ex.getMessage()); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.value(), "A conflict occurred.");
return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT); return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT);
} }
@ExceptionHandler(UnsupportedOperationException.class) @ExceptionHandler(UnsupportedOperationException.class)
public ResponseEntity<ErrorResponse> handleUnsupportedOperationException(UnsupportedOperationException ex) { public ResponseEntity<ErrorResponse> handleUnsupportedOperationException(UnsupportedOperationException ex) {
log.error("Unsupported operation: {}", ex.getMessage(), ex); log.error("Unsupported operation: {}", ex.getMessage(), ex);
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_IMPLEMENTED.value(), ex.getMessage()); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_IMPLEMENTED.value(), "Operation not supported.");
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_IMPLEMENTED); return new ResponseEntity<>(errorResponse, HttpStatus.NOT_IMPLEMENTED);
} }