fix(api): unknown API endpoints now return 404 instead of redirecting to index

This commit is contained in:
Gauthier Roebroeck 2023-09-11 17:14:25 +08:00
parent 88983a8199
commit 7315df54d6
2 changed files with 59 additions and 2 deletions

View file

@ -1,11 +1,14 @@
package org.gotson.komga.infrastructure.web
import jakarta.servlet.http.HttpServletRequest
import org.springframework.context.annotation.Configuration
import org.springframework.http.CacheControl
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.method.support.HandlerMethodArgumentResolver
import org.springframework.web.server.ResponseStatusException
import org.springframework.web.servlet.NoHandlerFoundException
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
@ -90,9 +93,12 @@ class WebMvcConfiguration : WebMvcConfigurer {
@Component
@ControllerAdvice
class Customizer {
class ResourceNotFoundController {
val apis = listOf("/api", "/opds", "/sse")
@ExceptionHandler(NoHandlerFoundException::class)
fun notFound(): String {
fun notFound(request: HttpServletRequest): String {
if (apis.any { request.requestURI.startsWith(it, true) }) throw ResponseStatusException(HttpStatus.NOT_FOUND)
return "forward:/"
}
}

View file

@ -0,0 +1,51 @@
package org.gotson.komga.infrastructure.web
import org.gotson.komga.interfaces.api.rest.WithMockCustomUser
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
@SpringBootTest
@AutoConfigureMockMvc(printOnlyOnFailure = false)
class ResourceNotFoundControllerTest(
@Autowired private val mockMvc: MockMvc,
) {
@Test
@WithMockCustomUser
fun `when getting an unknown API endpoint then 404 is returned`() {
mockMvc.get("/api/v1/doesnotexist")
.andExpect {
status { isNotFound() }
}
}
@Test
@WithMockCustomUser
fun `when getting an unknown OPDS endpoint then 404 is returned`() {
mockMvc.get("/opds/v2/doesnotexist")
.andExpect {
status { isNotFound() }
}
}
@Test
@WithMockCustomUser
fun `when getting an unknown SSE endpoint then 404 is returned`() {
mockMvc.get("/sse/v1/doesnotexist")
.andExpect {
status { isNotFound() }
}
}
@Test
@WithMockCustomUser
fun `when getting an unknown endpoint then it is forwarded to index`() {
mockMvc.get("/book/0DBTWY6S0KNX9")
.andExpect {
status { isOk() }
}
}
}