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();
if (user == null) {
throw ApiError.FORBIDDEN.createException("Authentication required.");
}
if (user.getPermissions().isAdmin()) {
return;
}
@@ -39,6 +39,10 @@ public class LibraryAccessAspect {
BookLoreUser user = authenticationService.getAuthenticatedUser();
if (user == null) {
throw ApiError.FORBIDDEN.createException("Authentication required.");
}
if (user.getPermissions().isAdmin()) return;
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);
if (userTokenOpt.isEmpty()) {
log.warn("Invalid KOBO token: {}", token);
log.warn("Invalid KOBO token");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid KOBO token");
return;
}
@@ -62,7 +62,7 @@ public class KoboAuthFilter extends OncePerRequestFilter {
var userOpt = userRepository.findByIdWithDetails(userToken.getUserId());
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");
return;
}
@@ -58,9 +58,9 @@ public class KoreaderAuthFilter extends OncePerRequestFilter {
SecurityContextHolder.getContext().setAuthentication(auth);
} 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 {
log.warn("Missing KOReader headers");
}
@@ -42,6 +42,7 @@ public class AppSettingController {
@ApiResponse(responseCode = "200", description = "Settings updated successfully"),
@ApiResponse(responseCode = "400", description = "Invalid request")
})
@PreAuthorize("@securityUtil.isAdmin()")
@PutMapping
public void updateSettings(@Parameter(description = "List of settings to update") @RequestBody List<SettingRequest> settingRequests) throws JacksonException {
for (SettingRequest settingRequest : settingRequests) {
@@ -82,15 +82,15 @@ public class AuthenticationController {
String username = headers.get(appProperties.getRemoteAuth().getHeaderUser().toLowerCase(Locale.ROOT));
String email = headers.get(appProperties.getRemoteAuth().getHeaderEmail().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: remote auth settings: {}", appProperties.getRemoteAuth());
log.debug("Remote-Auth: header values present name: {}, username: {}, email: {}, groups: {}",
name != null, username != null, email != null, groups != null);
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);
if (user.isPresent()) {
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.")
@ApiResponse(responseCode = "200", description = "ComicInfo metadata returned successfully")
@GetMapping("/{bookId}/cbx/metadata/comicinfo")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<?> getComicInfoMetadata(
@Parameter(description = "ID of the book") @PathVariable long 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.")
@ApiResponse(responseCode = "200", description = "File metadata returned successfully")
@GetMapping("/{bookId}/file-metadata")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<?> getFileMetadata(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookMetadataService.getFileMetadata(bookId));
@@ -159,6 +161,7 @@ public class BookController {
@ApiResponse(responseCode = "404", description = "Book not found")
})
@PutMapping("/{bookId}/content")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Void> replaceBookContent(
@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.")
@ApiResponse(responseCode = "200", description = "Cover images returned successfully")
@PostMapping("/{bookId}/metadata/covers")
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
public ResponseEntity<List<CoverImage>> getImages(@Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) {
return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request));
}
@@ -1,5 +1,6 @@
package org.booklore.controller;
import org.booklore.config.security.annotation.CheckBookAccess;
import org.booklore.model.dto.response.CbxPageDimension;
import org.booklore.model.dto.response.CbxPageInfo;
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.")
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
@GetMapping("/{bookId}/pages")
@CheckBookAccess(bookIdParam = "bookId")
public List<Integer> listPages(
@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) {
@@ -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.")
@ApiResponse(responseCode = "200", description = "Page info returned successfully")
@GetMapping("/{bookId}/page-info")
@CheckBookAccess(bookIdParam = "bookId")
public List<CbxPageInfo> getPageInfo(
@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) {
@@ -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.")
@ApiResponse(responseCode = "200", description = "Page dimensions returned successfully")
@GetMapping("/{bookId}/page-dimensions")
@CheckBookAccess(bookIdParam = "bookId")
public List<CbxPageDimension> getPageDimensions(
@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) {
@@ -24,6 +24,7 @@ public class KoboSettingsController {
@Operation(summary = "Get Kobo sync settings", description = "Retrieve the current user's Kobo sync settings.")
@ApiResponse(responseCode = "200", description = "Settings returned successfully")
@GetMapping
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<KoboSyncSettings> getSettings() {
KoboSyncSettings settings = koboService.getCurrentUserSettings();
return ResponseEntity.ok(settings);
@@ -1,5 +1,6 @@
package org.booklore.controller;
import org.booklore.config.security.annotation.CheckBookAccess;
import org.booklore.model.dto.response.PdfBookInfo;
import org.booklore.service.reader.PdfReaderService;
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.")
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
@GetMapping("/{bookId}/pages")
@CheckBookAccess(bookIdParam = "bookId")
public List<Integer> listPages(
@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) {
@@ -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.")
@ApiResponse(responseCode = "200", description = "Book info returned successfully")
@GetMapping("/{bookId}/info")
@CheckBookAccess(bookIdParam = "bookId")
public PdfBookInfo getBookInfo(
@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) {
@@ -37,6 +37,7 @@ public class TaskController {
}
@PostMapping("/start")
@PreAuthorize("@securityUtil.canAccessTaskManager() or @securityUtil.isAdmin()")
public ResponseEntity<TaskCreateResponse> startTask(@RequestBody TaskCreateRequest request) {
TaskCreateResponse response = service.runAsUser(request);
if (response.getStatus() == TaskStatus.ACCEPTED) {
@@ -66,13 +66,13 @@ public class GlobalExceptionHandler {
@ExceptionHandler(AccessDeniedException.class)
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);
}
@ExceptionHandler(NoResourceFoundException.class)
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);
}
@@ -103,14 +103,14 @@ public class GlobalExceptionHandler {
@ExceptionHandler(IllegalStateException.class)
public ResponseEntity<ErrorResponse> handleIllegalStateException(IllegalStateException 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);
}
@ExceptionHandler(UnsupportedOperationException.class)
public ResponseEntity<ErrorResponse> handleUnsupportedOperationException(UnsupportedOperationException 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);
}