From b14d9049b33469350128913251ebbb635064b8ff Mon Sep 17 00:00:00 2001 From: FyloZ Date: Wed, 4 Aug 2021 21:34:18 -0400 Subject: [PATCH 01/37] Update drone CI/CD --- .drone.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.drone.yml b/.drone.yml index b9e00cc..abd9354 100644 --- a/.drone.yml +++ b/.drone.yml @@ -13,6 +13,9 @@ steps: image: gradle:7.1-jdk11 commands: - gradle test + when: + branch: develop + events: push - name: build image: gradle:7.1-jdk11 @@ -21,9 +24,8 @@ steps: - mv build/libs/ColorRecipesExplorer-$CRE_VERSION.jar $CRE_ARTIFACT_NAME.jar - echo -n "latest,$CRE_VERSION" > .tags when: - branch: - - master - events: [ push, tag ] + branch: master + events: push - name: containerize image: plugins/docker @@ -32,9 +34,8 @@ steps: - JAVA_VERSION=11 repo: registry.fyloz.dev:5443/colorrecipesexplorer/backend when: - branch: - - master - events: [ push, tag ] + branch: master + events: push - name: deploy image: alpine:latest @@ -65,8 +66,7 @@ steps: - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker pull $CRE_REGISTRY_IMAGE:latest" - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker run -d -p $CRE_PORT:9090 --name=$DEPLOY_CONTAINER_NAME -v $DEPLOY_DATA_VOLUME:/usr/bin/cre/data -v $DEPLOY_CONFIG_VOLUME:/usr/bin/cre/config -e spring_profiles_active=$DEPLOY_SPRING_PROFILES $CRE_REGISTRY_IMAGE" when: - branch: - - master - events: [ push, tag ] + branch: master + events: push From ae5c19faca8a8d07758c30f27dc0d1e7cd7eb3d1 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Wed, 4 Aug 2021 21:54:17 -0400 Subject: [PATCH 02/37] =?UTF-8?q?#8=20Ajout=20de=20ConfigurationBase,=20do?= =?UTF-8?q?nt=20Configuration=20et=20SecureConfiguration=20h=C3=A9ritent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/Configuration.kt | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt index c1c4384..3f6f8f8 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt @@ -12,20 +12,25 @@ import javax.persistence.Id import javax.persistence.Table import javax.validation.constraints.NotBlank -data class Configuration( +sealed class ConfigurationBase( @JsonIgnore val type: ConfigurationType, - val content: String, val lastUpdated: LocalDateTime ) { val key = type.key val requireRestart = type.requireRestart val editable = !type.computed +} +class Configuration(type: ConfigurationType, val content: String, lastUpdated: LocalDateTime) : + ConfigurationBase(type, lastUpdated) { fun toEntity() = ConfigurationEntity(key, content, lastUpdated) } +class SecureConfiguration(type: ConfigurationType, lastUpdated: LocalDateTime) : + ConfigurationBase(type, lastUpdated) + @Entity @Table(name = "configuration") data class ConfigurationEntity( @@ -92,7 +97,13 @@ enum class ConfigurationType( DATABASE_URL("database.url", defaultContent = "mysql://localhost/cre", file = true, requireRestart = true), DATABASE_USER("database.user", defaultContent = "cre", file = true, requireRestart = true), - DATABASE_PASSWORD("database.password", defaultContent = "asecurepassword", file = true, requireRestart = true, secure = true), + DATABASE_PASSWORD( + "database.password", + defaultContent = "asecurepassword", + file = true, + requireRestart = true, + secure = true + ), DATABASE_SUPPORTED_VERSION("database.version.supported", computed = true), RECIPE_APPROBATION_EXPIRATION("recipe.approbation.expiration", defaultContent = 4.months), @@ -128,15 +139,15 @@ class InvalidConfigurationKeyException(val key: String) : ) class InvalidImageConfigurationException(val type: ConfigurationType) : - RestException( - "invalid-configuration-image", - "Invalid image configuration", - HttpStatus.BAD_REQUEST, - "The configuration with the key '${type.key}' does not accept images as content", - mapOf( - "key" to type.key - ) - ) + RestException( + "invalid-configuration-image", + "Invalid image configuration", + HttpStatus.BAD_REQUEST, + "The configuration with the key '${type.key}' does not accept images as content", + mapOf( + "key" to type.key + ) + ) class ConfigurationNotSetException(val type: ConfigurationType) : RestException( From 689dbdc412e9905657b64fa5b501fcbe652b3255 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Wed, 4 Aug 2021 22:57:31 -0400 Subject: [PATCH 03/37] =?UTF-8?q?#8=20Les=20configurations=20s=C3=A9curita?= =?UTF-8?q?ires=20retournent=20leur=20informations=20sans=20leur=20contenu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DatabaseVersioning.kt | 8 +++-- .../model/Configuration.kt | 4 +++ .../rest/ConfigurationController.kt | 10 +++--- .../service/MaterialService.kt | 2 +- .../service/RecipeService.kt | 4 +-- .../service/TouchUpKitService.kt | 6 ++-- .../service/config/ConfigurationService.kt | 32 +++++++++++++++---- 7 files changed, 45 insertions(+), 21 deletions(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/DatabaseVersioning.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/DatabaseVersioning.kt index a355f4b..5f020fb 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/DatabaseVersioning.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/DatabaseVersioning.kt @@ -3,23 +3,24 @@ package dev.fyloz.colorrecipesexplorer import dev.fyloz.colorrecipesexplorer.databasemanager.CreDatabase import dev.fyloz.colorrecipesexplorer.databasemanager.databaseContext import dev.fyloz.colorrecipesexplorer.databasemanager.databaseUpdaterProperties +import dev.fyloz.colorrecipesexplorer.model.Configuration import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService import org.slf4j.Logger import org.springframework.boot.jdbc.DataSourceBuilder import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.DependsOn import org.springframework.context.annotation.Profile import org.springframework.core.env.ConfigurableEnvironment import javax.sql.DataSource +import org.springframework.context.annotation.Configuration as SpringConfiguration const val SUPPORTED_DATABASE_VERSION = 5 const val ENV_VAR_ENABLE_DATABASE_UPDATE_NAME = "CRE_ENABLE_DB_UPDATE" val DATABASE_NAME_REGEX = Regex("(\\w+)$") @Profile("!emergency") -@Configuration +@SpringConfiguration @DependsOn("configurationsInitializer", "configurationService") class DataSourceConfiguration { @Bean(name = ["dataSource"]) @@ -29,7 +30,8 @@ class DataSourceConfiguration { configurationService: ConfigurationService ): DataSource { fun getConfiguration(type: ConfigurationType) = - configurationService.get(type).content + if (type.secure) configurationService.getSecure(type) + else configurationService.getContent(type) val databaseUrl = "jdbc:" + getConfiguration(ConfigurationType.DATABASE_URL) val databaseUsername = getConfiguration(ConfigurationType.DATABASE_USER) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt index 3f6f8f8..a701661 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt @@ -81,6 +81,10 @@ fun configuration( configuration(type = key.toConfigurationType(), content = content) } +fun secureConfiguration( + configuration: Configuration +) = SecureConfiguration(configuration.type, configuration.lastUpdated) + enum class ConfigurationType( val key: String, val defaultContent: Any? = null, diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt index 1cad0ee..1e7cff4 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt @@ -1,6 +1,6 @@ package dev.fyloz.colorrecipesexplorer.rest -import dev.fyloz.colorrecipesexplorer.model.Configuration +import dev.fyloz.colorrecipesexplorer.model.ConfigurationBase import dev.fyloz.colorrecipesexplorer.model.ConfigurationDto import dev.fyloz.colorrecipesexplorer.model.ConfigurationImageDto import dev.fyloz.colorrecipesexplorer.model.account.Permission @@ -20,13 +20,11 @@ class ConfigurationController(val configurationService: ConfigurationService) { fun getAll(@RequestParam(required = false) keys: String?, authentication: Authentication?) = ok(with(configurationService) { if (keys != null) getAll(keys) else getAll() - }.filter { - !it.type.secure && authentication.hasAuthority(it) - }) + }.filter { authentication.hasAuthority(it) }) @GetMapping("{key}") fun get(@PathVariable key: String, authentication: Authentication?) = with(configurationService.get(key)) { - if (!this.type.secure && authentication.hasAuthority(this)) ok(this) else forbidden() + if (authentication.hasAuthority(this)) ok(this) else forbidden() } @PutMapping @@ -48,7 +46,7 @@ class ConfigurationController(val configurationService: ConfigurationService) { } } -private fun Authentication?.hasAuthority(configuration: Configuration) = when { +private fun Authentication?.hasAuthority(configuration: ConfigurationBase) = when { configuration.type.public -> true this != null && Permission.ADMIN.toAuthority() in this.authorities -> true else -> false diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt index 6802776..7d752f9 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt @@ -59,7 +59,7 @@ class MaterialServiceImpl( isMixType = this.isMixType, materialType = this.materialType!!, simdutUrl = if (fileService.exists(this.simdutFilePath)) - "${configService.get(ConfigurationType.INSTANCE_URL).content}$FILE_CONTROLLER_PATH?path=${ + "${configService.getContent(ConfigurationType.INSTANCE_URL)}$FILE_CONTROLLER_PATH?path=${ URLEncoder.encode( this.simdutFilePath, StandardCharsets.UTF_8 diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt index 3b44f8a..4dcda07 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt @@ -78,7 +78,7 @@ class RecipeServiceImpl( }.toSet(), this.groupsInformation, recipeImageService.getAllImages(this) - .map { this.imageUrl(configService.get(ConfigurationType.INSTANCE_URL).content, it) } + .map { this.imageUrl(configService.getContent(ConfigurationType.INSTANCE_URL), it) } .toSet() ) @@ -87,7 +87,7 @@ class RecipeServiceImpl( repository.existsByNameAndCompany(name, company) override fun isApprobationExpired(recipe: Recipe): Boolean? = - with(Period.parse(configService.get(ConfigurationType.RECIPE_APPROBATION_EXPIRATION).content)) { + with(Period.parse(configService.getContent(ConfigurationType.RECIPE_APPROBATION_EXPIRATION))) { recipe.approbationDate?.plus(this)?.isBefore(LocalDate.now()) } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt index acd1600..b966525 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt @@ -48,7 +48,7 @@ class TouchUpKitServiceImpl( touchUpKitRepository ), TouchUpKitService { private val cacheGeneratedFiles by lazy { - configService.get(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF).content == true.toString() + configService.getContent(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF) == true.toString() } override fun idNotFoundException(id: Long) = touchUpKitIdNotFoundException(id) @@ -90,7 +90,7 @@ class TouchUpKitServiceImpl( } override fun isExpired(touchUpKit: TouchUpKit) = - with(Period.parse(configService.get(ConfigurationType.TOUCH_UP_KIT_EXPIRATION).content)) { + with(Period.parse(configService.getContent(ConfigurationType.TOUCH_UP_KIT_EXPIRATION))) { touchUpKit.completed && touchUpKit.completionDate!!.plus(this) < LocalDate.now() } @@ -144,5 +144,5 @@ class TouchUpKitServiceImpl( "$TOUCH_UP_KIT_FILES_PATH/$this.pdf" private fun TouchUpKit.pdfUrl() = - "${configService.get(ConfigurationType.INSTANCE_URL).content}$TOUCH_UP_KIT_CONTROLLER_PATH/pdf?job=$project" + "${configService.getContent(ConfigurationType.INSTANCE_URL)}$TOUCH_UP_KIT_CONTROLLER_PATH/pdf?job=$project" } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt index 03eef2f..8e5d0c2 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt @@ -12,22 +12,28 @@ import org.springframework.stereotype.Service interface ConfigurationService { /** Gets all set configurations. */ - fun getAll(): List + fun getAll(): List /** * Gets all configurations with keys contained in the given [formattedKeyList]. * The [formattedKeyList] contains wanted configuration keys separated by a semi-colon. */ - fun getAll(formattedKeyList: String): List + fun getAll(formattedKeyList: String): List /** * Gets the configuration with the given [key]. * If the [key] does not exists, an [InvalidConfigurationKeyException] will be thrown. */ - fun get(key: String): Configuration + fun get(key: String): ConfigurationBase /** Gets the configuration with the given [type]. */ - fun get(type: ConfigurationType): Configuration + fun get(type: ConfigurationType): ConfigurationBase + + /** Gets the content of the configuration with the given [type]. */ + fun getContent(type: ConfigurationType): String + + /** Gets the content of the secure configuration with the given [type]. Should not be accessible to the users. */ + fun getSecure(type: ConfigurationType): String /** Sets the content of each configuration in the given [configurations] list. */ fun set(configurations: List) @@ -89,18 +95,32 @@ class ConfigurationServiceImpl( override fun get(key: String) = get(key.toConfigurationType()) - override fun get(type: ConfigurationType): Configuration { + override fun get(type: ConfigurationType): ConfigurationBase { // Encryption salt should never be returned, but cannot be set as "secure" without encrypting it if (type == ConfigurationType.GENERATED_ENCRYPTION_SALT) throw InvalidConfigurationKeyException(type.key) val configuration = configurationSource.get(type) ?: throw ConfigurationNotSetException(type) return if (type.secure) { - decryptConfiguration(configuration) + secureConfiguration(configuration) } else { configuration } } + override fun getContent(type: ConfigurationType): String { + val configuration = get(type) + if (configuration is SecureConfiguration) throw UnsupportedOperationException("Cannot get '${type.key}' configuration content because it is secure") + + return (configuration as Configuration).content + } + + override fun getSecure(type: ConfigurationType): String { + if (!type.secure) throw UnsupportedOperationException("Cannot get configuration of type '${type.key}' because it is not a secure configuration") + + val configuration = configurationSource.get(type) ?: throw ConfigurationNotSetException(type) + return decryptConfiguration(configuration).content + } + override fun set(configurations: List) { configurationSource.set( configurations From a07c72b90140fd08f5fbffb4af4a76d0fb8ee489 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Thu, 5 Aug 2021 23:00:42 -0400 Subject: [PATCH 04/37] =?UTF-8?q?#8=20Mise=20=C3=A0=20jour=20des=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/Configuration.kt | 7 ++- .../service/ConfigurationServiceTest.kt | 56 +++++++++++++++++-- .../service/RecipeServiceTest.kt | 12 ++-- .../service/TouchUpKitServiceTest.kt | 5 +- 4 files changed, 65 insertions(+), 15 deletions(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt index a701661..b913523 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt @@ -81,9 +81,14 @@ fun configuration( configuration(type = key.toConfigurationType(), content = content) } +fun secureConfiguration( + type: ConfigurationType, + lastUpdated: LocalDateTime? = null +) = SecureConfiguration(type, lastUpdated ?: LocalDateTime.now()) + fun secureConfiguration( configuration: Configuration -) = SecureConfiguration(configuration.type, configuration.lastUpdated) +) = secureConfiguration(configuration.type, configuration.lastUpdated) enum class ConfigurationType( val key: String, diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt index 8c4df85..e49fc60 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt @@ -10,6 +10,7 @@ import io.mockk.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows +import kotlin.UnsupportedOperationException import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -165,7 +166,47 @@ class ConfigurationServiceTest { } @Test - fun `get(type) decrypts configuration content when the given ConfigurationType is secure`() { + fun `get(type) returns a SecureConfiguration when the given ConfigurationType is secure`() { + val type = ConfigurationType.DATABASE_PASSWORD + val configuration = configuration( + type = type, + content = "securepassword".encrypt(type.key, securityProperties.configSalt!!) + ) + + every { configurationSource.get(type) } returns configuration + + val found = service.get(type) + + assertTrue { found is SecureConfiguration } + } + + @Test + fun `getContent(type) returns configuration content`() { + val type = ConfigurationType.INSTANCE_NAME + val configuration = configuration( + type = type, + content = "content" + ) + + every { service.get(type) } returns configuration + + val found = service.getContent(type) + + assertEquals(configuration.content, found) + } + + @Test + fun `getContent(type) throws UnsupportedOperationException when configuration is secure`() { + val type = ConfigurationType.DATABASE_PASSWORD + val configuration = secureConfiguration(type) + + every { service.get(type) } returns configuration + + assertThrows { service.getContent(type) } + } + + @Test + fun `getSecure(type) returns decrypted configuration content`() { val type = ConfigurationType.DATABASE_PASSWORD val content = "securepassword" val configuration = configuration( @@ -175,9 +216,16 @@ class ConfigurationServiceTest { every { configurationSource.get(type) } returns configuration - val found = service.get(type) + val found = service.getSecure(type) - assertEquals(content, found.content) + assertEquals(content, found) + } + + @Test + fun `getSecure(type) throws UnsupportedOperationException when configuration is not secure`() { + val type = ConfigurationType.INSTANCE_NAME + + assertThrows { service.getSecure(type) } } @Test @@ -197,7 +245,7 @@ class ConfigurationServiceTest { fun `set(configuration) encrypts secure configurations`() { val type = ConfigurationType.DATABASE_PASSWORD val content = "securepassword" - val encryptedContent =content.encrypt(type.key, securityProperties.configSalt!!) + val encryptedContent = content.encrypt(type.key, securityProperties.configSalt!!) val configuration = configuration(type = type, content = content) mockkStatic(String::encrypt) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt index 58a1193..0e055ad 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt @@ -80,9 +80,9 @@ class RecipeServiceTest : @Test fun `isApprobationExpired() returns false when the approbation date of the given recipe is within the configured period`() { val period = Period.ofMonths(4) - val config = configuration(type = ConfigurationType.RECIPE_APPROBATION_EXPIRATION, content = period.toString()) val recipe = recipe(approbationDate = LocalDate.now()) - whenever(configService.get(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(config) + + whenever(configService.getContent(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(period.toString()) val approbationExpired = service.isApprobationExpired(recipe) @@ -93,9 +93,9 @@ class RecipeServiceTest : @Test fun `isApprobationExpired() returns true when the approbation date of the given recipe is outside the configured period`() { val period = Period.ofMonths(4) - val config = configuration(type = ConfigurationType.RECIPE_APPROBATION_EXPIRATION, content = period.toString()) val recipe = recipe(approbationDate = LocalDate.now().minus(period).minusMonths(1)) - whenever(configService.get(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(config) + + whenever(configService.getContent(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(period.toString()) val approbationExpired = service.isApprobationExpired(recipe) @@ -106,9 +106,9 @@ class RecipeServiceTest : @Test fun `isApprobationExpired() returns null when the given recipe as no approbation date`() { val period = Period.ofMonths(4) - val config = configuration(type = ConfigurationType.RECIPE_APPROBATION_EXPIRATION, content = period.toString()) val recipe = recipe(approbationDate = null) - whenever(configService.get(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(config) + + whenever(configService.getContent(ConfigurationType.RECIPE_APPROBATION_EXPIRATION)).doReturn(period.toString()) val approbationExpired = service.isApprobationExpired(recipe) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt index c913d45..f6b5ba2 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt @@ -131,10 +131,7 @@ class TouchUpKitServiceTest { this.setCachePdf(false) private fun TouchUpKitServiceTestContext.setCachePdf(enabled: Boolean) { - every { configService.get(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF) } returns configuration( - type = ConfigurationType.TOUCH_UP_KIT_CACHE_PDF, - enabled.toString() - ) + every { configService.getContent(ConfigurationType.TOUCH_UP_KIT_CACHE_PDF) } returns enabled.toString() } private fun test(test: TouchUpKitServiceTestContext.() -> Unit) { From 16d1f2afda49639e28d7a8afecdca80a9f868cc1 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Thu, 5 Aug 2021 23:36:48 -0400 Subject: [PATCH 05/37] =?UTF-8?q?#8=20Mise=20=C3=A0=20jour=20CI/CD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 11 ++++++++++ .drone.yml | 55 ++++++++++++++++++++++++++++++----------------- Dockerfile | 22 +++++++++++++------ gradle.Dockerfile | 10 --------- todo.txt | 15 ------------- 5 files changed, 62 insertions(+), 51 deletions(-) create mode 100644 .dockerignore delete mode 100644 gradle.Dockerfile delete mode 100644 todo.txt diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8cdfa43 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +.gradle +.idea +**/build +**/data +**/gradle +**/logs +.gitignore +.gitlab-ci.yml +docker-compose.yml +Dockerfile +gradlew** diff --git a/.drone.yml b/.drone.yml index abd9354..c3a9b41 100644 --- a/.drone.yml +++ b/.drone.yml @@ -1,38 +1,51 @@ +--- +global-variables: + environment: &environment + JAVA_VERSION: 11 + GRADLE_VERSION: 7.1 + CRE_VERSION: dev-${DRONE_BUILD_NUMBER} + CRE_ARTIFACT_NAME: ColorRecipesExplorer + CRE_REGISTRY_IMAGE: registry.fyloz.dev:5443/colorrecipesexplorer/backend + CRE_PORT: 9101 + gradle-image: &gradle-image gradle:7.1-jdk11 + alpine-image: &alpine-image alpine:latest + docker-registry-repo: &docker-registry-repo registry.fyloz.dev:5443/colorrecipesexplorer/backend + kind: pipeline name: default type: docker -environment: - CRE_VERSION: ${DRONE_BUILD_NUMBER} - CRE_ARTIFACT_NAME: ColorRecipesExplorer - CRE_REGISTRY_IMAGE: registry.fyloz.dev:5443/colorrecipesexplorer/backend - CRE_PORT: 9101 - steps: - - name: test - image: gradle:7.1-jdk11 + - name: set-docker-tags + image: *alpine-image + environment: + <<: *environment commands: - - gradle test + - echo -n "latest,dev-$CRE_VERSION" > .tags + - cat .tags when: branch: develop events: push - - name: build - image: gradle:7.1-jdk11 + - name: gradle-test + image: *gradle-image commands: - - gradle bootJar -Pversion=$CRE_VERSION - - mv build/libs/ColorRecipesExplorer-$CRE_VERSION.jar $CRE_ARTIFACT_NAME.jar - - echo -n "latest,$CRE_VERSION" > .tags + - gradle test when: - branch: master - events: push + branch: develop + events: [push, pull_request] - name: containerize image: plugins/docker + environment: + <<: *environment settings: - build_args: - - JAVA_VERSION=11 - repo: registry.fyloz.dev:5443/colorrecipesexplorer/backend + build_args_from_env: + - GRADLE_VERSION + - JAVA_VERSION + - CRE_VERSION + - CRE_PORT + repo: *docker-registry-repo when: branch: master events: push @@ -40,6 +53,8 @@ steps: - name: deploy image: alpine:latest environment: + <<: *environment + CRE_REGISTRY_IMAGE: *docker-registry-repo DEPLOY_SERVER: from_secret: deploy_server DEPLOY_SERVER_USERNAME: @@ -64,7 +79,7 @@ steps: - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config' - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker stop $DEPLOY_CONTAINER_NAME || true && docker rm $DEPLOY_CONTAINER_NAME || true" - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker pull $CRE_REGISTRY_IMAGE:latest" - - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker run -d -p $CRE_PORT:9090 --name=$DEPLOY_CONTAINER_NAME -v $DEPLOY_DATA_VOLUME:/usr/bin/cre/data -v $DEPLOY_CONFIG_VOLUME:/usr/bin/cre/config -e spring_profiles_active=$DEPLOY_SPRING_PROFILES $CRE_REGISTRY_IMAGE" + - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker run -d -p $CRE_PORT:9090 --name=$DEPLOY_CONTAINER_NAME -v $DEPLOY_DATA_VOLUME:/usr/bin/data -v $DEPLOY_CONFIG_VOLUME:/usr/bin/config -e spring_profiles_active=$DEPLOY_SPRING_PROFILES $CRE_REGISTRY_IMAGE" when: branch: master events: push diff --git a/Dockerfile b/Dockerfile index 3f4a504..66b5bba 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,21 @@ +ARG GRADLE_VERSION=7.1 ARG JAVA_VERSION=11 +ARG CRE_VERSION=dev -FROM openjdk:$JAVA_VERSION +FROM gradle:$GRADLE_VERSION-jdk$JAVA_VERSION AS build +WORKDIR /usr/src -WORKDIR /usr/bin/cre/ +COPY . . +RUN gradle bootJar -Pversion=$CRE_VERSION -ARG CRE_ARTIFACT_NAME=ColorRecipesExplorer -COPY $CRE_ARTIFACT_NAME.jar ColorRecipesExplorer.jar +FROM alpine:latest +WORKDIR /usr/bin + +ARG JAVA_VERSION +RUN apk add --no-cache openjdk$JAVA_VERSION + +ARG CRE_VERSION +COPY --from=build /usr/src/build/libs/ColorRecipesExplorer.jar ColorRecipesExplorer.jar ARG CRE_PORT=9090 EXPOSE $CRE_PORT @@ -16,7 +26,7 @@ ENV spring_datasource_url=jdbc:h2:mem:cre ENV spring_datasource_username=root ENV spring_datasource_password=pass -VOLUME /usr/bin/cre/data -VOLUME /usr/bin/cre/config +VOLUME /usr/bin/data +VOLUME /usr/bin/config ENTRYPOINT ["java", "-jar", "ColorRecipesExplorer.jar"] diff --git a/gradle.Dockerfile b/gradle.Dockerfile deleted file mode 100644 index 2538416..0000000 --- a/gradle.Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -ARG JDK_VERSION=11 -ARG GRADLE_VERSION=7.1 - -FROM gradle:$GRADLE_VERSION-jdk$JDK_VERSION -WORKDIR /usr/src/cre/ - -COPY build.gradle.kts build.gradle.kts -COPY settings.gradle.kts settings.gradle.kts -COPY src src - diff --git a/todo.txt b/todo.txt deleted file mode 100644 index e940649..0000000 --- a/todo.txt +++ /dev/null @@ -1,15 +0,0 @@ -== Icônes pour recettes non-approuvés / quantité faible == -== Texte SIMDUT inexistant (fiche signalitique) pour les matériaux == - - - -== Comptes == -No employé - Permissions - Employés - - - -== Kits de retouche == -No Job - No Dossier - Qté - Description - Case à cocher - Note - Bouton compléter si tout est coché/imprimé ? - -Enregistrer localdatetime/personne pendant une certaine durée From 44185b0e5018b344bfdf4c4613326f159a0cb392 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Thu, 5 Aug 2021 23:40:49 -0400 Subject: [PATCH 06/37] =?UTF-8?q?#8=20Mise=20=C3=A0=20jour=20CI/CD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .drone.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.drone.yml b/.drone.yml index c3a9b41..9acf5ab 100644 --- a/.drone.yml +++ b/.drone.yml @@ -84,4 +84,9 @@ steps: branch: master events: push + trigger: + branch: + - develop + - master + From b7a15b6ce45e380d4e302020f7e397cf5a05ff69 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Thu, 5 Aug 2021 23:42:20 -0400 Subject: [PATCH 07/37] =?UTF-8?q?#8=20Mise=20=C3=A0=20jour=20CI/CD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .drone.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.drone.yml b/.drone.yml index 9acf5ab..1fcc813 100644 --- a/.drone.yml +++ b/.drone.yml @@ -86,7 +86,7 @@ steps: trigger: branch: - - develop - - master + - develop + - master From f196868bd32c54ada084bf0bfb973af4d81132b1 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Thu, 5 Aug 2021 23:42:50 -0400 Subject: [PATCH 08/37] =?UTF-8?q?#8=20Mise=20=C3=A0=20jour=20CI/CD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .drone.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.drone.yml b/.drone.yml index 1fcc813..35a4870 100644 --- a/.drone.yml +++ b/.drone.yml @@ -84,9 +84,9 @@ steps: branch: master events: push - trigger: - branch: - - develop - - master +trigger: + branch: + - develop + - master From f022e71fd748d7b73785503f765f08496a4d4662 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Fri, 6 Aug 2021 20:54:07 -0400 Subject: [PATCH 09/37] =?UTF-8?q?Mise=20=C3=A0=20jour=20CI/CD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .drone.yml | 59 ++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/.drone.yml b/.drone.yml index 35a4870..92b47c5 100644 --- a/.drone.yml +++ b/.drone.yml @@ -1,5 +1,6 @@ --- global-variables: + release: &release ${DRONE_BRANCH##/**} environment: &environment JAVA_VERSION: 11 GRADLE_VERSION: 7.1 @@ -7,6 +8,7 @@ global-variables: CRE_ARTIFACT_NAME: ColorRecipesExplorer CRE_REGISTRY_IMAGE: registry.fyloz.dev:5443/colorrecipesexplorer/backend CRE_PORT: 9101 + CRE_RELEASE: *release gradle-image: &gradle-image gradle:7.1-jdk11 alpine-image: &alpine-image alpine:latest docker-registry-repo: &docker-registry-repo registry.fyloz.dev:5443/colorrecipesexplorer/backend @@ -16,26 +18,32 @@ name: default type: docker steps: - - name: set-docker-tags - image: *alpine-image - environment: - <<: *environment - commands: - - echo -n "latest,dev-$CRE_VERSION" > .tags - - cat .tags - when: - branch: develop - events: push - - name: gradle-test image: *gradle-image commands: - gradle test when: branch: develop - events: [push, pull_request] - - name: containerize + - name: set-docker-tags-latest + image: *alpine-image + environment: + <<: *environment + commands: + - echo -n "latest" > .tags + when: + branch: develop + + - name: set-docker-tags-release + image: *alpine-image + environment: + <<: *environment + commands: + - echo -n "latest-release,$CRE_RELEASE" > .tags + when: + branch: release/** + + - name: containerize-dev image: plugins/docker environment: <<: *environment @@ -47,8 +55,22 @@ steps: - CRE_PORT repo: *docker-registry-repo when: - branch: master - events: push + branch: develop + + - name: containerize-release + image: plugins/docker + environment: + <<: *environment + settings: + build_args_from_env: + - GRADLE_VERSION + - JAVA_VERSION + - CRE_PORT + build-args: + CRE_VERSION: *release + repo: *docker-registry-repo + when: + branch: release/** - name: deploy image: alpine:latest @@ -78,11 +100,10 @@ steps: - ssh-keyscan -p $DEPLOY_SERVER_SSH_PORT -H $DEPLOY_SERVER >> ~/.ssh/known_hosts - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config' - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker stop $DEPLOY_CONTAINER_NAME || true && docker rm $DEPLOY_CONTAINER_NAME || true" - - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker pull $CRE_REGISTRY_IMAGE:latest" - - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker run -d -p $CRE_PORT:9090 --name=$DEPLOY_CONTAINER_NAME -v $DEPLOY_DATA_VOLUME:/usr/bin/data -v $DEPLOY_CONFIG_VOLUME:/usr/bin/config -e spring_profiles_active=$DEPLOY_SPRING_PROFILES $CRE_REGISTRY_IMAGE" + - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker pull $CRE_REGISTRY_IMAGE:$CRE_RELEASE" + - ssh -p $DEPLOY_SERVER_SSH_PORT $DEPLOY_SERVER_USERNAME@$DEPLOY_SERVER "docker run -d -p $CRE_PORT:9090 --name=$DEPLOY_CONTAINER_NAME -v $DEPLOY_DATA_VOLUME:/usr/bin/data -v $DEPLOY_CONFIG_VOLUME:/usr/bin/config -e spring_profiles_active=$DEPLOY_SPRING_PROFILES $CRE_REGISTRY_IMAGE:$CRE_RELEASE" when: - branch: master - events: push + branch: release/** trigger: branch: From 59a8e98e40e95bc0043416cc75358f7b2206249a Mon Sep 17 00:00:00 2001 From: FyloZ Date: Fri, 6 Aug 2021 21:20:55 -0400 Subject: [PATCH 10/37] =?UTF-8?q?Le=20Dockerfile=20d=C3=A9fini=20maintenan?= =?UTF-8?q?t=20la=20version=20de=20CRE=20correctement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 66b5bba..adf4abc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,11 @@ ARG GRADLE_VERSION=7.1 ARG JAVA_VERSION=11 -ARG CRE_VERSION=dev FROM gradle:$GRADLE_VERSION-jdk$JAVA_VERSION AS build WORKDIR /usr/src - COPY . . + +ARG CRE_VERSION=dev RUN gradle bootJar -Pversion=$CRE_VERSION FROM alpine:latest @@ -15,7 +15,7 @@ ARG JAVA_VERSION RUN apk add --no-cache openjdk$JAVA_VERSION ARG CRE_VERSION -COPY --from=build /usr/src/build/libs/ColorRecipesExplorer.jar ColorRecipesExplorer.jar +COPY --from=build /usr/src/build/libs/ColorRecipesExplorer-$CRE_VERSION.jar ColorRecipesExplorer.jar ARG CRE_PORT=9090 EXPOSE $CRE_PORT From 72b5a417f6777805c4752023917465acfae2caef Mon Sep 17 00:00:00 2001 From: William Nolin Date: Mon, 9 Aug 2021 22:33:48 -0400 Subject: [PATCH 11/37] Update '.drone.yml' --- .drone.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.drone.yml b/.drone.yml index 92b47c5..cfc5b85 100644 --- a/.drone.yml +++ b/.drone.yml @@ -108,6 +108,7 @@ steps: trigger: branch: - develop + - release/** - master From 7f0e48f08177879035d16c3972354cfac5ac62e4 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Mon, 9 Aug 2021 22:46:32 -0400 Subject: [PATCH 12/37] Update CI/CD --- .drone.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.drone.yml b/.drone.yml index cfc5b85..44ca38d 100644 --- a/.drone.yml +++ b/.drone.yml @@ -52,7 +52,6 @@ steps: - GRADLE_VERSION - JAVA_VERSION - CRE_VERSION - - CRE_PORT repo: *docker-registry-repo when: branch: develop @@ -65,9 +64,8 @@ steps: build_args_from_env: - GRADLE_VERSION - JAVA_VERSION - - CRE_PORT build-args: - CRE_VERSION: *release + CRE_VERSION: ${DRONE_BRANCH##/**} repo: *docker-registry-repo when: branch: release/** From 2c271c90abeaed4d6201b520c28c28d9e852441f Mon Sep 17 00:00:00 2001 From: FyloZ Date: Mon, 9 Aug 2021 23:26:50 -0400 Subject: [PATCH 13/37] Update CI/CD --- .drone.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.drone.yml b/.drone.yml index 44ca38d..5ab7b66 100644 --- a/.drone.yml +++ b/.drone.yml @@ -1,6 +1,6 @@ --- global-variables: - release: &release ${DRONE_BRANCH##/**} + release: &release ${DRONE_BRANCH##**/} environment: &environment JAVA_VERSION: 11 GRADLE_VERSION: 7.1 @@ -65,7 +65,7 @@ steps: - GRADLE_VERSION - JAVA_VERSION build-args: - CRE_VERSION: ${DRONE_BRANCH##/**} + CRE_VERSION: *release repo: *docker-registry-repo when: branch: release/** From 437210af897c16d9e8d2125f7ee85534e568a8cb Mon Sep 17 00:00:00 2001 From: FyloZ Date: Tue, 10 Aug 2021 19:12:37 -0400 Subject: [PATCH 14/37] Update CI/CD pour utiliser le bon nom pour build_args --- .drone.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.drone.yml b/.drone.yml index 5ab7b66..5ec553c 100644 --- a/.drone.yml +++ b/.drone.yml @@ -64,7 +64,7 @@ steps: build_args_from_env: - GRADLE_VERSION - JAVA_VERSION - build-args: + build_args: CRE_VERSION: *release repo: *docker-registry-repo when: From deadd8b14d98a9dcd27d8058496da33b577a9175 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Tue, 10 Aug 2021 19:21:52 -0400 Subject: [PATCH 15/37] Update CI/CD --- .drone.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.drone.yml b/.drone.yml index 5ec553c..e566184 100644 --- a/.drone.yml +++ b/.drone.yml @@ -65,7 +65,7 @@ steps: - GRADLE_VERSION - JAVA_VERSION build_args: - CRE_VERSION: *release + - CRE_VERSION: *release repo: *docker-registry-repo when: branch: release/** From aed457c6cefb5c84d76351c65eb5939143723d2f Mon Sep 17 00:00:00 2001 From: FyloZ Date: Tue, 10 Aug 2021 19:27:39 -0400 Subject: [PATCH 16/37] Update CI/CD --- .drone.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.drone.yml b/.drone.yml index e566184..f2456f7 100644 --- a/.drone.yml +++ b/.drone.yml @@ -65,7 +65,7 @@ steps: - GRADLE_VERSION - JAVA_VERSION build_args: - - CRE_VERSION: *release + - CRE_VERSION=${DRONE_BRANCH##**/} repo: *docker-registry-repo when: branch: release/** From 7f2ce81354ccdd649b81ce667f3624bacab0ab02 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Tue, 10 Aug 2021 19:49:06 -0400 Subject: [PATCH 17/37] Update CI/CD --- .drone.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.drone.yml b/.drone.yml index f2456f7..df600a7 100644 --- a/.drone.yml +++ b/.drone.yml @@ -83,7 +83,7 @@ steps: from_secret: deploy_server_ssh_port DEPLOY_SERVER_SSH_KEY: from_secret: deploy_server_ssh_key - DEPLOY_CONTAINER_NAME: cre_backend-${DRONE_BRANCH} + DEPLOY_CONTAINER_NAME: cre_backend DEPLOY_SPRING_PROFILES: mysql,rest DEPLOY_DATA_VOLUME: /var/cre/data DEPLOY_CONFIG_VOLUME: /var/cre/config From 9a618258bfc18db343a61b4eb8744127d7f8d06c Mon Sep 17 00:00:00 2001 From: FyloZ Date: Fri, 20 Aug 2021 17:29:45 -0400 Subject: [PATCH 18/37] #1 Fix getting app logo and icon returning HTTP 403 --- .../config/security/SecurityConfig.kt | 13 +++++++------ .../colorrecipesexplorer/rest/AccountControllers.kt | 2 ++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt index 5440e61..72fcbd0 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt @@ -8,7 +8,10 @@ import dev.fyloz.colorrecipesexplorer.service.CreUserDetailsService import dev.fyloz.colorrecipesexplorer.service.UserService import org.slf4j.Logger import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.* +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Lazy +import org.springframework.context.annotation.Profile import org.springframework.core.env.Environment import org.springframework.http.HttpMethod import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder @@ -99,11 +102,9 @@ class SecurityConfig( .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) if (!debugMode) { - http.authorizeRequests() - .antMatchers("/api/login").permitAll() - .antMatchers("/api/logout").fullyAuthenticated() - .antMatchers("/api/user/current").fullyAuthenticated() - .anyRequest().fullyAuthenticated() + http + .authorizeRequests() + .anyRequest().permitAll() } else { http .cors() diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt index 52e61d0..2230093 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt @@ -32,6 +32,7 @@ class UserController(private val userService: UserService) { ok(userService.getByIdForOutput(id)) @GetMapping("current") + @PreAuthorize("isFullyAuthenticated()") fun getCurrent(loggedInUser: Principal?) = if (loggedInUser != null) ok( @@ -161,6 +162,7 @@ class GroupsController( @Profile("!emergency") class LogoutController(private val userService: UserService) { @GetMapping("logout") + @PreAuthorize("isFullyAuthenticated()") fun logout(request: HttpServletRequest) = ok { userService.logout(request) From 25e61698ad9c948f55522f6a98d9afde8d735d4a Mon Sep 17 00:00:00 2001 From: FyloZ Date: Mon, 23 Aug 2021 19:05:50 -0400 Subject: [PATCH 19/37] #12 Add JWT builder function --- build.gradle.kts | 4 +-- .../fyloz/colorrecipesexplorer/TypeAliases.kt | 3 ++ .../config/security/JwtFilters.kt | 28 +++++----------- .../fyloz/colorrecipesexplorer/utils/Jwt.kt | 33 +++++++++++++++++++ 4 files changed, 46 insertions(+), 22 deletions(-) create mode 100644 src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt create mode 100644 src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt diff --git a/build.gradle.kts b/build.gradle.kts index 9912eaf..1979ec2 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -32,7 +32,7 @@ dependencies { implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}") implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.11.3") implementation("javax.xml.bind:jaxb-api:2.3.0") - implementation("io.jsonwebtoken:jjwt:0.9.1") + implementation("io.jsonwebtoken:jjwt-api:0.11.2") implementation("org.apache.poi:poi-ooxml:4.1.0") implementation("org.apache.pdfbox:pdfbox:2.0.4") implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2") @@ -59,7 +59,7 @@ dependencies { runtimeOnly("org.postgresql:postgresql:42.2.16") runtimeOnly("com.microsoft.sqlserver:mssql-jdbc:9.2.1.jre11") - implementation("org.springframework.cloud:spring-cloud-starter:2.2.8.RELEASE") + runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.2") } springBoot { diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt new file mode 100644 index 0000000..3dcb7b4 --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt @@ -0,0 +1,3 @@ +package dev.fyloz.colorrecipesexplorer + +public typealias SpringUser = org.springframework.security.core.userdetails.User diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt index bca86e3..d859f17 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt @@ -1,23 +1,22 @@ package dev.fyloz.colorrecipesexplorer.config.security import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import dev.fyloz.colorrecipesexplorer.SpringUser import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.model.account.UserLoginRequest +import dev.fyloz.colorrecipesexplorer.utils.buildJwt import io.jsonwebtoken.ExpiredJwtException import io.jsonwebtoken.Jwts -import io.jsonwebtoken.SignatureAlgorithm import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.context.SecurityContextHolder -import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import org.springframework.security.web.authentication.www.BasicAuthenticationFilter import org.springframework.util.Assert import org.springframework.web.util.WebUtils -import java.util.* import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @@ -28,7 +27,7 @@ val blacklistedJwtTokens = mutableListOf() class JwtAuthenticationFilter( private val authManager: AuthenticationManager, - private val securityConfigurationProperties: CreSecurityProperties, + private val securityProperties: CreSecurityProperties, private val updateUserLoginTime: (Long) -> Unit ) : UsernamePasswordAuthenticationFilter() { private var debugMode = false @@ -49,29 +48,17 @@ class JwtAuthenticationFilter( chain: FilterChain, authResult: Authentication ) { - val jwtSecret = securityConfigurationProperties.jwtSecret - val jwtDuration = securityConfigurationProperties.jwtDuration - Assert.notNull(jwtSecret, "No JWT secret has been defined.") - Assert.notNull(jwtDuration, "No JWT duration has been defined.") - val userId = (authResult.principal as User).username - updateUserLoginTime(userId.toLong()) - val expirationMs = System.currentTimeMillis() + jwtDuration - val expirationDate = Date(expirationMs) - val token = Jwts.builder() - .setSubject(userId) - .setExpiration(expirationDate) - .signWith(SignatureAlgorithm.HS512, jwtSecret.toByteArray()) - .compact() - response.addHeader("Access-Control-Expose-Headers", "X-Authentication-Expiration") + val user = (authResult.principal as SpringUser) + val token = user.buildJwt(securityProperties) + var bearerCookie = - "$authorizationCookieName=Bearer$token; Max-Age=${jwtDuration / 1000}; HttpOnly; SameSite=strict" + "$authorizationCookieName=Bearer$token; Max-Age=${securityProperties.jwtDuration / 1000}; HttpOnly; SameSite=strict" if (!debugMode) bearerCookie += "; Secure;" response.addHeader( "Set-Cookie", bearerCookie ) response.addHeader(authorizationCookieName, "Bearer $token") - response.addHeader("X-Authentication-Expiration", "$expirationMs") } } @@ -115,6 +102,7 @@ class JwtAuthorizationFilter( val jwtSecret = securityConfigurationProperties.jwtSecret Assert.notNull(jwtSecret, "No JWT secret has been defined.") return try { + val userId = Jwts.parser() .setSigningKey(jwtSecret.toByteArray()) .parseClaimsJws(token.replace("Bearer", "")) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt new file mode 100644 index 0000000..446dbf0 --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt @@ -0,0 +1,33 @@ +package dev.fyloz.colorrecipesexplorer.utils + +import dev.fyloz.colorrecipesexplorer.SpringUser +import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties +import io.jsonwebtoken.Jwts +import io.jsonwebtoken.SignatureAlgorithm +import io.jsonwebtoken.io.Encoders +import io.jsonwebtoken.security.Keys +import java.util.* + +data class Jwt( + val subject: String, + val secret: String, + val duration: Long, + val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512 +) + +fun SpringUser.buildJwt(properties: CreSecurityProperties) = + Jwt(this.username, properties.jwtSecret, properties.jwtDuration).build() + +fun Jwt.build(): String { + val expirationMs = System.currentTimeMillis() + this.duration + val expirationDate = Date(expirationMs) + + val base64Secret = Encoders.BASE64.encode(this.secret.toByteArray()) + val key = Keys.hmacShaKeyFor(base64Secret.toByteArray()) + + return Jwts.builder() + .setSubject(this.subject) + .setExpiration(expirationDate) + .signWith(key) + .compact() +} From 4dfca3349c5f92325a9a30f2f001a039f2c3a62e Mon Sep 17 00:00:00 2001 From: FyloZ Date: Thu, 26 Aug 2021 23:33:20 -0400 Subject: [PATCH 20/37] #12 Add jwt parser --- build.gradle.kts | 1 + gradlew | 2 +- .../fyloz/colorrecipesexplorer/TypeAliases.kt | 4 +- .../config/security/JwtFilters.kt | 29 +++++----- .../config/security/SecurityConfig.kt | 18 +++---- .../model/account/User.kt | 17 ++++-- .../service/AccountService.kt | 11 ++-- .../fyloz/colorrecipesexplorer/utils/Jwt.kt | 54 +++++++++++++------ src/main/resources/application.properties | 2 +- 9 files changed, 81 insertions(+), 57 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 1979ec2..8c57eda 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -60,6 +60,7 @@ dependencies { runtimeOnly("com.microsoft.sqlserver:mssql-jdbc:9.2.1.jre11") runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.2") + runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.2") } springBoot { diff --git a/gradlew b/gradlew index 4f906e0..744e882 100755 --- a/gradlew +++ b/gradlew @@ -72,7 +72,7 @@ case "`uname`" in Darwin* ) darwin=true ;; - MINGW* ) + MSYS* | MINGW* ) msys=true ;; NONSTOP* ) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt index 3dcb7b4..b56a00d 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/TypeAliases.kt @@ -1,3 +1,5 @@ package dev.fyloz.colorrecipesexplorer -public typealias SpringUser = org.springframework.security.core.userdetails.User +typealias SpringUser = org.springframework.security.core.userdetails.User +typealias SpringUserDetails = org.springframework.security.core.userdetails.UserDetails +typealias SpringUserDetailsService = org.springframework.security.core.userdetails.UserDetailsService diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt index d859f17..2ded760 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt @@ -1,21 +1,19 @@ package dev.fyloz.colorrecipesexplorer.config.security import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import dev.fyloz.colorrecipesexplorer.SpringUser import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.exception.NotFoundException +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails import dev.fyloz.colorrecipesexplorer.model.account.UserLoginRequest import dev.fyloz.colorrecipesexplorer.utils.buildJwt +import dev.fyloz.colorrecipesexplorer.utils.parseJwt import io.jsonwebtoken.ExpiredJwtException -import io.jsonwebtoken.Jwts import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.context.SecurityContextHolder -import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import org.springframework.security.web.authentication.www.BasicAuthenticationFilter -import org.springframework.util.Assert import org.springframework.web.util.WebUtils import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest @@ -46,10 +44,11 @@ class JwtAuthenticationFilter( request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain, - authResult: Authentication + auth: Authentication ) { - val user = (authResult.principal as SpringUser) - val token = user.buildJwt(securityProperties) + val userDetails = (auth.principal as UserDetails) + val token = + userDetails.user.buildJwt(securityProperties.jwtSecret, duration = securityProperties.jwtDuration).token var bearerCookie = "$authorizationCookieName=Bearer$token; Max-Age=${securityProperties.jwtDuration / 1000}; HttpOnly; SameSite=strict" @@ -59,11 +58,13 @@ class JwtAuthenticationFilter( bearerCookie ) response.addHeader(authorizationCookieName, "Bearer $token") + + updateUserLoginTime(userDetails.user.id) } } class JwtAuthorizationFilter( - private val securityConfigurationProperties: CreSecurityProperties, + private val securityProperties: CreSecurityProperties, authenticationManager: AuthenticationManager, private val loadUserById: (Long) -> UserDetails ) : BasicAuthenticationFilter(authenticationManager) { @@ -99,16 +100,10 @@ class JwtAuthorizationFilter( } private fun getAuthentication(token: String): UsernamePasswordAuthenticationToken? { - val jwtSecret = securityConfigurationProperties.jwtSecret - Assert.notNull(jwtSecret, "No JWT secret has been defined.") return try { - - val userId = Jwts.parser() - .setSigningKey(jwtSecret.toByteArray()) - .parseClaimsJws(token.replace("Bearer", "")) - .body - .subject - if (userId != null) getAuthenticationToken(userId) else null + with(parseJwt(token.replace("Bearer", ""), securityProperties.jwtSecret)) { + getAuthenticationToken(this.subject) + } } catch (_: ExpiredJwtException) { null } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt index 72fcbd0..6835dc2 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt @@ -4,6 +4,8 @@ import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.emergencyMode import dev.fyloz.colorrecipesexplorer.model.account.Permission import dev.fyloz.colorrecipesexplorer.model.account.User +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails +import dev.fyloz.colorrecipesexplorer.model.account.user import dev.fyloz.colorrecipesexplorer.service.CreUserDetailsService import dev.fyloz.colorrecipesexplorer.service.UserService import org.slf4j.Logger @@ -22,7 +24,6 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.AuthenticationException import org.springframework.security.core.authority.SimpleGrantedAuthority -import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder @@ -34,7 +35,6 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource import javax.annotation.PostConstruct import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse -import org.springframework.security.core.userdetails.User as SpringUser @Configuration @Profile("!emergency") @@ -122,8 +122,6 @@ class EmergencySecurityConfig( private val securityProperties: CreSecurityProperties, private val environment: Environment ) : WebSecurityConfigurerAdapter() { - private val rootUserRole = Permission.ADMIN.name - init { emergencyMode = true } @@ -142,7 +140,7 @@ class EmergencySecurityConfig( auth.inMemoryAuthentication() .withUser(securityProperties.root!!.id.toString()) .password(passwordEncoder().encode(securityProperties.root!!.password)) - .authorities(SimpleGrantedAuthority(rootUserRole)) + .authorities(SimpleGrantedAuthority(Permission.ADMIN.name)) } override fun configure(http: HttpSecurity) { @@ -172,11 +170,11 @@ class EmergencySecurityConfig( private fun loadUserById(id: Long): UserDetails { assertRootUserNotNull(securityProperties) if (id == securityProperties.root!!.id) { - return SpringUser( - id.toString(), - securityProperties.root!!.password, - listOf(SimpleGrantedAuthority(rootUserRole)) - ) + return UserDetails(user( + id = id, + password = securityProperties.root!!.password, + permissions = mutableSetOf(Permission.ADMIN) + )) } throw UsernameNotFoundException(id.toString()) } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt index 3f4a64a..8f0559a 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt @@ -1,5 +1,6 @@ package dev.fyloz.colorrecipesexplorer.model.account +import dev.fyloz.colorrecipesexplorer.SpringUserDetails import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.model.EntityDto @@ -59,9 +60,6 @@ data class User( .apply { if (group != null) this.addAll(group!!.flatPermissions) } - - val authorities: Set - get() = flatPermissions.map { it.toAuthority() }.toMutableSet() } open class UserSaveDto( @@ -110,6 +108,19 @@ data class UserOutputDto( data class UserLoginRequest(val id: Long, val password: String) +data class UserDetails(val user: User) : SpringUserDetails { + override fun getPassword() = user.password + override fun getUsername() = user.id.toString() + + override fun getAuthorities() = + user.flatPermissions.map { it.toAuthority() }.toMutableSet() + + override fun isAccountNonExpired() = true + override fun isAccountNonLocked() = true + override fun isCredentialsNonExpired() = true + override fun isEnabled() = true +} + // ==== DSL ==== fun user( passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(), diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt index 9373ecb..fcb0122 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt @@ -1,5 +1,6 @@ package dev.fyloz.colorrecipesexplorer.service +import dev.fyloz.colorrecipesexplorer.SpringUserDetailsService import dev.fyloz.colorrecipesexplorer.config.security.blacklistedJwtTokens import dev.fyloz.colorrecipesexplorer.config.security.defaultGroupCookieName import dev.fyloz.colorrecipesexplorer.exception.NotFoundException @@ -9,8 +10,6 @@ import dev.fyloz.colorrecipesexplorer.repository.GroupRepository import dev.fyloz.colorrecipesexplorer.repository.UserRepository import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Profile -import org.springframework.security.core.userdetails.UserDetails -import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service @@ -19,7 +18,6 @@ import java.time.LocalDateTime import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.transaction.Transactional -import org.springframework.security.core.userdetails.User as SpringUser interface UserService : ExternalModelService { @@ -69,7 +67,7 @@ interface GroupService : fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) } -interface CreUserDetailsService : UserDetailsService { +interface CreUserDetailsService : SpringUserDetailsService { /** Loads an [User] for the given [id]. */ fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean = false): UserDetails } @@ -304,8 +302,7 @@ class GroupServiceImpl( @Profile("!emergency") class CreUserDetailsServiceImpl( private val userService: UserService -) : - CreUserDetailsService { +) : CreUserDetailsService { override fun loadUserByUsername(username: String): UserDetails { try { return loadUserById(username.toLong(), true) @@ -322,6 +319,6 @@ class CreUserDetailsServiceImpl( ignoreDefaultGroupUsers = ignoreDefaultGroupUsers, ignoreSystemUsers = false ) - return SpringUser(user.id.toString(), user.password, user.authorities) + return UserDetails(user) } } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt index 446dbf0..a430fb3 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt @@ -1,33 +1,53 @@ package dev.fyloz.colorrecipesexplorer.utils -import dev.fyloz.colorrecipesexplorer.SpringUser -import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties +import dev.fyloz.colorrecipesexplorer.model.account.User import io.jsonwebtoken.Jwts import io.jsonwebtoken.SignatureAlgorithm import io.jsonwebtoken.io.Encoders import io.jsonwebtoken.security.Keys import java.util.* +import javax.crypto.SecretKey data class Jwt( val subject: String, val secret: String, - val duration: Long, + val duration: Long? = null, val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512 -) +) { + val token: String by lazy { + val builder = Jwts.builder() + .setSubject(subject) -fun SpringUser.buildJwt(properties: CreSecurityProperties) = - Jwt(this.username, properties.jwtSecret, properties.jwtDuration).build() + duration?.let { + val expirationMs = System.currentTimeMillis() + it + val expirationDate = Date(expirationMs) -fun Jwt.build(): String { - val expirationMs = System.currentTimeMillis() + this.duration - val expirationDate = Date(expirationMs) + builder.setExpiration(expirationDate) + } - val base64Secret = Encoders.BASE64.encode(this.secret.toByteArray()) - val key = Keys.hmacShaKeyFor(base64Secret.toByteArray()) - - return Jwts.builder() - .setSubject(this.subject) - .setExpiration(expirationDate) - .signWith(key) - .compact() + builder + .signWith(keyFromSecret(secret)) + .compact() + } } + +/** Build a [Jwt] for the given [User]. */ +fun User.buildJwt(secret: String, duration: Long?) = + Jwt(this.id.toString(), secret, duration) + +/** Parses the given [jwt] string. */ +fun parseJwt(jwt: String, secret: String) = + with( + Jwts.parserBuilder() + .setSigningKey(keyFromSecret(secret)) + .build() + .parseClaimsJws(jwt) + ) { + Jwt(this.body.subject, secret) + } + +/** Creates a base64 encoded [SecretKey] from the given [secret]. */ +private fun keyFromSecret(secret: String) = + with(Encoders.BASE64.encode(secret.toByteArray())) { + Keys.hmacShaKeyFor(this.toByteArray()) + } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e796dda..18852ab 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,7 +3,7 @@ server.port=9090 # CRE cre.server.data-directory=data cre.server.config-directory=config -cre.security.jwt-secret=CtnvGQjgZ44A1fh295gE +cre.security.jwt-secret=CtnvGQjgZ44A1fh295gE78WWOgl8InrbwBgQsMy0 cre.security.jwt-duration=18000000 cre.security.aes-secret=blabla # Root user From 975ebae553465398091b00377cf8790c80ea7547 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Fri, 27 Aug 2021 18:44:16 -0400 Subject: [PATCH 21/37] #12 Add custom claims to JWT builder --- .../fyloz/colorrecipesexplorer/utils/Jwt.kt | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt index a430fb3..b36527e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt @@ -12,11 +12,14 @@ data class Jwt( val subject: String, val secret: String, val duration: Long? = null, - val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512 + val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512, + val claims: Map = mapOf() ) { val token: String by lazy { val builder = Jwts.builder() + .signWith(keyFromSecret(secret)) .setSubject(subject) + .addClaims(claims.filterValues { it != null }) duration?.let { val expirationMs = System.currentTimeMillis() + it @@ -25,15 +28,21 @@ data class Jwt( builder.setExpiration(expirationDate) } - builder - .signWith(keyFromSecret(secret)) - .compact() + builder.compact() } } /** Build a [Jwt] for the given [User]. */ fun User.buildJwt(secret: String, duration: Long?) = - Jwt(this.id.toString(), secret, duration) + Jwt( + subject = this.id.toString(), + secret, + duration, + claims = mapOf( + "groupId" to this.group?.id, + "groupName" to this.group?.name + ) + ) /** Parses the given [jwt] string. */ fun parseJwt(jwt: String, secret: String) = From da2a8244147f0f2fc548bcd3d230b1fcbc8e5118 Mon Sep 17 00:00:00 2001 From: William Nolin Date: Sat, 28 Aug 2021 14:16:28 -0400 Subject: [PATCH 22/37] #12 Add emergency user details service implementation --- build.gradle.kts | 5 +- .../config/security/SecurityConfig.kt | 36 ++--- .../model/account/User.kt | 27 +++- .../rest/AccountControllers.kt | 4 +- .../service/RecipeService.kt | 1 + .../service/users/GroupService.kt | 97 ++++++++++++ .../service/users/UserDetailsService.kt | 77 ++++++++++ .../UserService.kt} | 142 ++---------------- .../fyloz/colorrecipesexplorer/utils/Jwt.kt | 21 ++- .../service/AccountsServiceTest.kt | 21 +-- 10 files changed, 252 insertions(+), 179 deletions(-) create mode 100644 src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/GroupService.kt create mode 100644 src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserDetailsService.kt rename src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/{AccountService.kt => users/UserService.kt} (60%) diff --git a/build.gradle.kts b/build.gradle.kts index 8c57eda..d1502a1 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -33,6 +33,8 @@ dependencies { implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.11.3") implementation("javax.xml.bind:jaxb-api:2.3.0") implementation("io.jsonwebtoken:jjwt-api:0.11.2") + implementation("io.jsonwebtoken:jjwt-impl:0.11.2") + implementation("io.jsonwebtoken:jjwt-jackson:0.11.2") implementation("org.apache.poi:poi-ooxml:4.1.0") implementation("org.apache.pdfbox:pdfbox:2.0.4") implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2") @@ -58,9 +60,6 @@ dependencies { runtimeOnly("mysql:mysql-connector-java:8.0.22") runtimeOnly("org.postgresql:postgresql:42.2.16") runtimeOnly("com.microsoft.sqlserver:mssql-jdbc:9.2.1.jre11") - - runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.2") - runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.2") } springBoot { diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt index 6835dc2..323706e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt @@ -4,10 +4,8 @@ import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.emergencyMode import dev.fyloz.colorrecipesexplorer.model.account.Permission import dev.fyloz.colorrecipesexplorer.model.account.User -import dev.fyloz.colorrecipesexplorer.model.account.UserDetails -import dev.fyloz.colorrecipesexplorer.model.account.user -import dev.fyloz.colorrecipesexplorer.service.CreUserDetailsService -import dev.fyloz.colorrecipesexplorer.service.UserService +import dev.fyloz.colorrecipesexplorer.service.users.UserDetailsService +import dev.fyloz.colorrecipesexplorer.service.users.UserService import org.slf4j.Logger import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean @@ -23,8 +21,6 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.AuthenticationException -import org.springframework.security.core.authority.SimpleGrantedAuthority -import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.AuthenticationEntryPoint @@ -43,7 +39,7 @@ import javax.servlet.http.HttpServletResponse @EnableConfigurationProperties(CreSecurityProperties::class) class SecurityConfig( private val securityProperties: CreSecurityProperties, - @Lazy private val userDetailsService: CreUserDetailsService, + @Lazy private val userDetailsService: UserDetailsService, @Lazy private val userService: UserService, private val environment: Environment, private val logger: Logger @@ -120,6 +116,7 @@ class SecurityConfig( @EnableConfigurationProperties(CreSecurityProperties::class) class EmergencySecurityConfig( private val securityProperties: CreSecurityProperties, + private val userDetailsService: UserDetailsService, private val environment: Environment ) : WebSecurityConfigurerAdapter() { init { @@ -134,13 +131,8 @@ class EmergencySecurityConfig( fun passwordEncoder() = getPasswordEncoder() - override fun configure(auth: AuthenticationManagerBuilder) { - assertRootUserNotNull(securityProperties) - // Create in-memory root user - auth.inMemoryAuthentication() - .withUser(securityProperties.root!!.id.toString()) - .password(passwordEncoder().encode(securityProperties.root!!.password)) - .authorities(SimpleGrantedAuthority(Permission.ADMIN.name)) + override fun configure(authBuilder: AuthenticationManagerBuilder) { + authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()) } override fun configure(http: HttpSecurity) { @@ -154,7 +146,9 @@ class EmergencySecurityConfig( JwtAuthenticationFilter(authenticationManager(), securityProperties) { } ) .addFilter( - JwtAuthorizationFilter(securityProperties, authenticationManager(), this::loadUserById) + JwtAuthorizationFilter(securityProperties, authenticationManager()) { + userDetailsService.loadUserById(it, false) + } ) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() @@ -166,18 +160,6 @@ class EmergencySecurityConfig( http.cors() } } - - private fun loadUserById(id: Long): UserDetails { - assertRootUserNotNull(securityProperties) - if (id == securityProperties.root!!.id) { - return UserDetails(user( - id = id, - password = securityProperties.root!!.password, - permissions = mutableSetOf(Permission.ADMIN) - )) - } - throw UsernameNotFoundException(id.toString()) - } } @Component diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt index 8f0559a..8fbee34 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt @@ -123,11 +123,10 @@ data class UserDetails(val user: User) : SpringUserDetails { // ==== DSL ==== fun user( - passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(), id: Long = 0L, firstName: String = "firstName", lastName: String = "lastName", - password: String = passwordEncoder.encode("password"), + password: String = "password", isDefaultGroupUser: Boolean = false, isSystemUser: Boolean = false, group: Group? = null, @@ -146,6 +145,30 @@ fun user( lastLoginTime ).apply(op) +fun user( + id: Long = 0L, + firstName: String = "firstName", + lastName: String = "lastName", + plainPassword: String = "password", + isDefaultGroupUser: Boolean = false, + isSystemUser: Boolean = false, + group: Group? = null, + permissions: MutableSet = mutableSetOf(), + lastLoginTime: LocalDateTime? = null, + passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(), + op: User.() -> Unit = {} +) = User( + id, + firstName, + lastName, + passwordEncoder.encode(plainPassword), + isDefaultGroupUser, + isSystemUser, + group, + permissions, + lastLoginTime +).apply(op) + fun userSaveDto( passwordEncoder: PasswordEncoder = BCryptPasswordEncoder(), id: Long = 0L, diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt index 2230093..42ab55e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt @@ -3,8 +3,8 @@ package dev.fyloz.colorrecipesexplorer.rest import dev.fyloz.colorrecipesexplorer.config.annotations.PreAuthorizeEditUsers import dev.fyloz.colorrecipesexplorer.config.annotations.PreAuthorizeViewUsers import dev.fyloz.colorrecipesexplorer.model.account.* -import dev.fyloz.colorrecipesexplorer.service.UserService -import dev.fyloz.colorrecipesexplorer.service.GroupService +import dev.fyloz.colorrecipesexplorer.service.users.GroupService +import dev.fyloz.colorrecipesexplorer.service.users.UserService import org.springframework.context.annotation.Profile import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt index 4dcda07..f878df3 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt @@ -5,6 +5,7 @@ import dev.fyloz.colorrecipesexplorer.model.account.Group import dev.fyloz.colorrecipesexplorer.model.validation.or import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.users.GroupService import dev.fyloz.colorrecipesexplorer.utils.setAll import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Profile diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/GroupService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/GroupService.kt new file mode 100644 index 0000000..62ac1f0 --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/GroupService.kt @@ -0,0 +1,97 @@ +package dev.fyloz.colorrecipesexplorer.service.users + +import dev.fyloz.colorrecipesexplorer.config.security.defaultGroupCookieName +import dev.fyloz.colorrecipesexplorer.model.account.* +import dev.fyloz.colorrecipesexplorer.repository.GroupRepository +import dev.fyloz.colorrecipesexplorer.service.AbstractExternalNamedModelService +import dev.fyloz.colorrecipesexplorer.service.ExternalNamedModelService +import org.springframework.context.annotation.Profile +import org.springframework.stereotype.Service +import org.springframework.web.util.WebUtils +import javax.servlet.http.HttpServletRequest +import javax.servlet.http.HttpServletResponse +import javax.transaction.Transactional + +const val defaultGroupCookieMaxAge = 10 * 365 * 24 * 60 * 60 // 10 ans + +interface GroupService : + ExternalNamedModelService { + /** Gets all the users of the group with the given [id]. */ + fun getUsersForGroup(id: Long): Collection + + /** Gets the default group from a cookie in the given HTTP [request]. */ + fun getRequestDefaultGroup(request: HttpServletRequest): Group + + /** Sets the default group cookie for the given HTTP [response]. */ + fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) +} + +@Service +@Profile("!emergency") +class GroupServiceImpl( + private val userService: UserService, + groupRepository: GroupRepository +) : AbstractExternalNamedModelService( + groupRepository +), + GroupService { + override fun idNotFoundException(id: Long) = groupIdNotFoundException(id) + override fun idAlreadyExistsException(id: Long) = groupIdAlreadyExistsException(id) + override fun nameNotFoundException(name: String) = groupNameNotFoundException(name) + override fun nameAlreadyExistsException(name: String) = groupNameAlreadyExistsException(name) + + override fun Group.toOutput() = GroupOutputDto( + this.id!!, + this.name, + this.permissions, + this.flatPermissions + ) + + override fun existsByName(name: String): Boolean = repository.existsByName(name) + override fun getUsersForGroup(id: Long): Collection = + userService.getByGroup(getById(id)) + + @Transactional + override fun save(entity: Group): Group { + return super.save(entity).apply { + userService.saveDefaultGroupUser(this) + } + } + + override fun update(entity: GroupUpdateDto): Group { + val persistedGroup by lazy { getById(entity.id) } + return update(with(entity) { + Group( + entity.id, + if (name.isNotBlank()) entity.name else persistedGroup.name, + if (permissions.isNotEmpty()) entity.permissions else persistedGroup.permissions + ) + }) + } + + @Transactional + override fun delete(entity: Group) { + userService.delete(userService.getDefaultGroupUser(entity)) + super.delete(entity) + } + + override fun getRequestDefaultGroup(request: HttpServletRequest): Group { + val defaultGroupCookie = WebUtils.getCookie(request, defaultGroupCookieName) + ?: throw NoDefaultGroupException() + val defaultGroupUser = userService.getById( + defaultGroupCookie.value.toLong(), + ignoreDefaultGroupUsers = false, + ignoreSystemUsers = true + ) + return defaultGroupUser.group!! + } + + override fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) { + val group = getById(groupId) + val defaultGroupUser = userService.getDefaultGroupUser(group) + response.addHeader( + "Set-Cookie", + "$defaultGroupCookieName=${defaultGroupUser.id}; Max-Age=$defaultGroupCookieMaxAge; Path=/api; HttpOnly; Secure; SameSite=strict" + ) + } +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserDetailsService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserDetailsService.kt new file mode 100644 index 0000000..923abed --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserDetailsService.kt @@ -0,0 +1,77 @@ +package dev.fyloz.colorrecipesexplorer.service.users + +import dev.fyloz.colorrecipesexplorer.SpringUserDetails +import dev.fyloz.colorrecipesexplorer.SpringUserDetailsService +import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties +import dev.fyloz.colorrecipesexplorer.exception.NotFoundException +import dev.fyloz.colorrecipesexplorer.model.account.Permission +import dev.fyloz.colorrecipesexplorer.model.account.User +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails +import dev.fyloz.colorrecipesexplorer.model.account.user +import org.springframework.context.annotation.Profile +import org.springframework.security.core.userdetails.UsernameNotFoundException +import org.springframework.stereotype.Service + +interface UserDetailsService : SpringUserDetailsService { + /** Loads an [User] for the given [id]. */ + fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean = false): UserDetails +} + +@Service +@Profile("!emergency") +class UserDetailsServiceImpl( + private val userService: UserService +) : UserDetailsService { + override fun loadUserByUsername(username: String): UserDetails { + try { + return loadUserById(username.toLong(), true) + } catch (ex: NotFoundException) { + throw UsernameNotFoundException(username) + } + } + + override fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean): UserDetails { + val user = userService.getById( + id, + ignoreDefaultGroupUsers = ignoreDefaultGroupUsers, + ignoreSystemUsers = false + ) + return UserDetails(user) + } +} + +@Service +@Profile("emergency") +class EmergencyUserDetailsServiceImpl( + securityProperties: CreSecurityProperties +) : UserDetailsService { + private val users: Set + + init { + if (securityProperties.root == null) { + throw NullPointerException("The root user has not been configured") + } + + users = setOf( + // Add root user + with(securityProperties.root!!) { + user( + id = this.id, + plainPassword = this.password, + permissions = mutableSetOf(Permission.ADMIN) + ) + } + ) + } + + override fun loadUserByUsername(username: String): SpringUserDetails { + return loadUserById(username.toLong(), true) + } + + override fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean): UserDetails { + val user = users.firstOrNull { it.id == id } + ?: throw UsernameNotFoundException(id.toString()) + + return UserDetails(user) + } +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt similarity index 60% rename from src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt rename to src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt index fcb0122..b1df3ea 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt @@ -1,23 +1,18 @@ -package dev.fyloz.colorrecipesexplorer.service +package dev.fyloz.colorrecipesexplorer.service.users -import dev.fyloz.colorrecipesexplorer.SpringUserDetailsService import dev.fyloz.colorrecipesexplorer.config.security.blacklistedJwtTokens -import dev.fyloz.colorrecipesexplorer.config.security.defaultGroupCookieName -import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.model.account.* import dev.fyloz.colorrecipesexplorer.model.validation.or -import dev.fyloz.colorrecipesexplorer.repository.GroupRepository import dev.fyloz.colorrecipesexplorer.repository.UserRepository +import dev.fyloz.colorrecipesexplorer.service.AbstractExternalModelService +import dev.fyloz.colorrecipesexplorer.service.ExternalModelService import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Profile -import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.stereotype.Service import org.springframework.web.util.WebUtils import java.time.LocalDateTime import javax.servlet.http.HttpServletRequest -import javax.servlet.http.HttpServletResponse -import javax.transaction.Transactional interface UserService : ExternalModelService { @@ -55,29 +50,11 @@ interface UserService : fun logout(request: HttpServletRequest) } -interface GroupService : - ExternalNamedModelService { - /** Gets all the users of the group with the given [id]. */ - fun getUsersForGroup(id: Long): Collection - - /** Gets the default group from a cookie in the given HTTP [request]. */ - fun getRequestDefaultGroup(request: HttpServletRequest): Group - - /** Sets the default group cookie for the given HTTP [response]. */ - fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) -} - -interface CreUserDetailsService : SpringUserDetailsService { - /** Loads an [User] for the given [id]. */ - fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean = false): UserDetails -} - @Service @Profile("!emergency") class UserServiceImpl( userRepository: UserRepository, @Lazy val groupService: GroupService, - @Lazy val passwordEncoder: PasswordEncoder, ) : AbstractExternalModelService( userRepository ), @@ -120,11 +97,11 @@ class UserServiceImpl( override fun save(entity: UserSaveDto): User = save(with(entity) { - User( - id, - firstName, - lastName, - passwordEncoder.encode(password), + user( + id = id, + firstName = firstName, + lastName = lastName, + plainPassword = password, isDefaultGroupUser = false, isSystemUser = false, group = if (groupId != null) groupService.getById(groupId) else null, @@ -146,7 +123,7 @@ class UserServiceImpl( id = 1000000L + group.id!!, firstName = group.name, lastName = "User", - password = passwordEncoder.encode(group.name), + plainPassword = group.name, group = group, isDefaultGroupUser = true ) @@ -195,11 +172,11 @@ class UserServiceImpl( override fun updatePassword(id: Long, password: String): User { val persistedUser = getById(id, ignoreDefaultGroupUsers = true, ignoreSystemUsers = true) return super.update(with(persistedUser) { - User( + user( id, firstName, lastName, - passwordEncoder.encode(password), + plainPassword = password, isDefaultGroupUser, isSystemUser, group, @@ -225,100 +202,3 @@ class UserServiceImpl( } } } - -const val defaultGroupCookieMaxAge = 10 * 365 * 24 * 60 * 60 // 10 ans - -@Service -@Profile("!emergency") -class GroupServiceImpl( - private val userService: UserService, - groupRepository: GroupRepository -) : AbstractExternalNamedModelService( - groupRepository -), - GroupService { - override fun idNotFoundException(id: Long) = groupIdNotFoundException(id) - override fun idAlreadyExistsException(id: Long) = groupIdAlreadyExistsException(id) - override fun nameNotFoundException(name: String) = groupNameNotFoundException(name) - override fun nameAlreadyExistsException(name: String) = groupNameAlreadyExistsException(name) - - override fun Group.toOutput() = GroupOutputDto( - this.id!!, - this.name, - this.permissions, - this.flatPermissions - ) - - override fun existsByName(name: String): Boolean = repository.existsByName(name) - override fun getUsersForGroup(id: Long): Collection = - userService.getByGroup(getById(id)) - - @Transactional - override fun save(entity: Group): Group { - return super.save(entity).apply { - userService.saveDefaultGroupUser(this) - } - } - - override fun update(entity: GroupUpdateDto): Group { - val persistedGroup by lazy { getById(entity.id) } - return update(with(entity) { - Group( - entity.id, - if (name.isNotBlank()) entity.name else persistedGroup.name, - if (permissions.isNotEmpty()) entity.permissions else persistedGroup.permissions - ) - }) - } - - @Transactional - override fun delete(entity: Group) { - userService.delete(userService.getDefaultGroupUser(entity)) - super.delete(entity) - } - - override fun getRequestDefaultGroup(request: HttpServletRequest): Group { - val defaultGroupCookie = WebUtils.getCookie(request, defaultGroupCookieName) - ?: throw NoDefaultGroupException() - val defaultGroupUser = userService.getById( - defaultGroupCookie.value.toLong(), - ignoreDefaultGroupUsers = false, - ignoreSystemUsers = true - ) - return defaultGroupUser.group!! - } - - override fun setResponseDefaultGroup(groupId: Long, response: HttpServletResponse) { - val group = getById(groupId) - val defaultGroupUser = userService.getDefaultGroupUser(group) - response.addHeader( - "Set-Cookie", - "$defaultGroupCookieName=${defaultGroupUser.id}; Max-Age=${defaultGroupCookieMaxAge}; Path=/api; HttpOnly; Secure; SameSite=strict" - ) - } -} - -@Service -@Profile("!emergency") -class CreUserDetailsServiceImpl( - private val userService: UserService -) : CreUserDetailsService { - override fun loadUserByUsername(username: String): UserDetails { - try { - return loadUserById(username.toLong(), true) - } catch (ex: NotFoundException) { - throw UsernameNotFoundException(username) - } catch (ex: NotFoundException) { - throw UsernameNotFoundException(username) - } - } - - override fun loadUserById(id: Long, ignoreDefaultGroupUsers: Boolean): UserDetails { - val user = userService.getById( - id, - ignoreDefaultGroupUsers = ignoreDefaultGroupUsers, - ignoreSystemUsers = false - ) - return UserDetails(user) - } -} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt index b36527e..dbfb2df 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt @@ -1,6 +1,7 @@ package dev.fyloz.colorrecipesexplorer.utils import dev.fyloz.colorrecipesexplorer.model.account.User +import io.jsonwebtoken.Claims import io.jsonwebtoken.Jwts import io.jsonwebtoken.SignatureAlgorithm import io.jsonwebtoken.io.Encoders @@ -13,13 +14,13 @@ data class Jwt( val secret: String, val duration: Long? = null, val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512, - val claims: Map = mapOf() + val claims: Map = mapOf() ) { val token: String by lazy { val builder = Jwts.builder() .signWith(keyFromSecret(secret)) .setSubject(subject) - .addClaims(claims.filterValues { it != null }) + .addClaims(mappedClaims) duration?.let { val expirationMs = System.currentTimeMillis() + it @@ -30,6 +31,18 @@ data class Jwt( builder.compact() } + + private val mappedClaims: Map by lazy { + claims + .filterValues { it != null } + .mapKeys { it.key.claim } + .mapValues { it.value.toString() } + } +} + +enum class JwtClaim(val claim: String) { + GROUP_ID("groupId"), + GROUP_NAME("groupName") } /** Build a [Jwt] for the given [User]. */ @@ -39,8 +52,8 @@ fun User.buildJwt(secret: String, duration: Long?) = secret, duration, claims = mapOf( - "groupId" to this.group?.id, - "groupName" to this.group?.name + JwtClaim.GROUP_ID to this.group?.id, + JwtClaim.GROUP_NAME to this.group?.name ) ) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt index a9979b7..48bce7d 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt @@ -5,8 +5,9 @@ import dev.fyloz.colorrecipesexplorer.config.security.defaultGroupCookieName import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.exception.NotFoundException import dev.fyloz.colorrecipesexplorer.model.account.* -import dev.fyloz.colorrecipesexplorer.repository.UserRepository import dev.fyloz.colorrecipesexplorer.repository.GroupRepository +import dev.fyloz.colorrecipesexplorer.repository.UserRepository +import dev.fyloz.colorrecipesexplorer.service.users.* import org.junit.jupiter.api.* import org.springframework.mock.web.MockHttpServletResponse import org.springframework.security.core.userdetails.UsernameNotFoundException @@ -25,17 +26,17 @@ class UserServiceTest : AbstractExternalModelServiceTest() { private val passwordEncoder = BCryptPasswordEncoder() - override val entity: User = user(passwordEncoder, id = 0L) - override val anotherEntity: User = user(passwordEncoder, id = 1L) - private val entityDefaultGroupUser = user(passwordEncoder, id = 2L, isDefaultGroupUser = true) - private val entitySystemUser = user(passwordEncoder, id = 3L, isSystemUser = true) + override val entity: User = user(id = 0L, passwordEncoder = passwordEncoder) + override val anotherEntity: User = user(id = 1L, passwordEncoder = passwordEncoder) + private val entityDefaultGroupUser = user(id = 2L, isDefaultGroupUser = true, passwordEncoder = passwordEncoder) + private val entitySystemUser = user(id = 3L, isSystemUser = true, passwordEncoder = passwordEncoder) private val group = group(id = 0L) override val entitySaveDto: UserSaveDto = spy(userSaveDto(passwordEncoder, id = 0L)) override val entityUpdateDto: UserUpdateDto = spy(userUpdateDto(id = 0L)) override val repository: UserRepository = mock() private val groupService: GroupService = mock() - override val service: UserService = spy(UserServiceImpl(repository, groupService, passwordEncoder)) + override val service: UserService = spy(UserServiceImpl(repository, groupService)) private val entitySaveDtoUser = User( entitySaveDto.id, @@ -210,7 +211,7 @@ class GroupServiceTest : override val entityWithEntityName: Group = group(id = 2L, name = entity.name) private val groupUserId = 1000000L + entity.id!! - private val groupUser = user(BCryptPasswordEncoder(), id = groupUserId, group = entity) + private val groupUser = user(passwordEncoder = BCryptPasswordEncoder(), id = groupUserId, group = entity) @BeforeEach override fun afterEach() { @@ -303,7 +304,7 @@ class GroupServiceTest : @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserUserDetailsServiceTest { private val userService: UserService = mock() - private val service = spy(CreUserDetailsServiceImpl(userService)) + private val service = spy(UserDetailsServiceImpl(userService)) private val user = user(id = 0L) @@ -317,8 +318,8 @@ class UserUserDetailsServiceTest { @Test fun `loadUserByUsername() calls loadUserByUserId() with the given username as an id`() { whenever(userService.getById(eq(user.id), any(), any())).doReturn(user) - doReturn(SpringUser(user.id.toString(), user.password, listOf())).whenever(service) - .loadUserById(user.id) + doReturn(UserDetails(user(id = user.id, plainPassword = user.password))) + .whenever(service).loadUserById(user.id) service.loadUserByUsername(user.id.toString()) From 72f9710bdb35bfec1fc8852379c5d5de68fb758e Mon Sep 17 00:00:00 2001 From: William Nolin Date: Sun, 29 Aug 2021 18:46:22 -0400 Subject: [PATCH 23/37] #12 Start adding claims deserialization --- build.gradle.kts | 2 +- .../config/security/JwtFilters.kt | 7 +- .../model/account/User.kt | 12 +++ .../service/users/UserService.kt | 10 +- .../fyloz/colorrecipesexplorer/utils/Jwt.kt | 100 ++++++++++++++---- .../service/AccountsServiceTest.kt | 1 - .../service/RecipeServiceTest.kt | 1 + 7 files changed, 102 insertions(+), 31 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index d1502a1..7d857c0 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -30,7 +30,7 @@ dependencies { implementation(platform("org.jetbrains.kotlin:kotlin-bom:${kotlinVersion}")) implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}") implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}") - implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.11.3") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.12.4") implementation("javax.xml.bind:jaxb-api:2.3.0") implementation("io.jsonwebtoken:jjwt-api:0.11.2") implementation("io.jsonwebtoken:jjwt-impl:0.11.2") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt index 2ded760..4c8e5e5 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt @@ -3,8 +3,10 @@ package dev.fyloz.colorrecipesexplorer.config.security import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.exception.NotFoundException +import dev.fyloz.colorrecipesexplorer.model.account.User import dev.fyloz.colorrecipesexplorer.model.account.UserDetails import dev.fyloz.colorrecipesexplorer.model.account.UserLoginRequest +import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto import dev.fyloz.colorrecipesexplorer.utils.buildJwt import dev.fyloz.colorrecipesexplorer.utils.parseJwt import io.jsonwebtoken.ExpiredJwtException @@ -28,6 +30,7 @@ class JwtAuthenticationFilter( private val securityProperties: CreSecurityProperties, private val updateUserLoginTime: (Long) -> Unit ) : UsernamePasswordAuthenticationFilter() { + private val objectMapper = jacksonObjectMapper() private var debugMode = false init { @@ -36,7 +39,7 @@ class JwtAuthenticationFilter( } override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication { - val loginRequest = jacksonObjectMapper().readValue(request.inputStream, UserLoginRequest::class.java) + val loginRequest = objectMapper.readValue(request.inputStream, UserLoginRequest::class.java) return authManager.authenticate(UsernamePasswordAuthenticationToken(loginRequest.id, loginRequest.password)) } @@ -101,7 +104,7 @@ class JwtAuthorizationFilter( private fun getAuthentication(token: String): UsernamePasswordAuthenticationToken? { return try { - with(parseJwt(token.replace("Bearer", ""), securityProperties.jwtSecret)) { + with(parseJwt(token.replace("Bearer", ""), securityProperties.jwtSecret)) { getAuthenticationToken(this.subject) } } catch (_: ExpiredJwtException) { diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt index 8fbee34..6fceff4 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt @@ -189,6 +189,18 @@ fun userUpdateDto( op: UserUpdateDto.() -> Unit = {} ) = UserUpdateDto(id, firstName, lastName, groupId, permissions).apply(op) +fun userOutputDto( + user: User +) = UserOutputDto( + user.id, + user.firstName, + user.lastName, + user.group, + user.flatPermissions, + user.permissions, + user.lastLoginTime +) + // ==== Exceptions ==== private const val USER_NOT_FOUND_EXCEPTION_TITLE = "User not found" private const val USER_ALREADY_EXISTS_EXCEPTION_TITLE = "User already exists" diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt index b1df3ea..8211687 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt @@ -62,15 +62,7 @@ class UserServiceImpl( override fun idNotFoundException(id: Long) = userIdNotFoundException(id) override fun idAlreadyExistsException(id: Long) = userIdAlreadyExistsException(id) - override fun User.toOutput() = UserOutputDto( - this.id, - this.firstName, - this.lastName, - this.group, - this.flatPermissions, - this.permissions, - this.lastLoginTime - ) + override fun User.toOutput() = userOutputDto(this) override fun existsByFirstNameAndLastName(firstName: String, lastName: String): Boolean = repository.existsByFirstNameAndLastName(firstName, lastName) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt index dbfb2df..c8b53b3 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt @@ -1,26 +1,40 @@ package dev.fyloz.colorrecipesexplorer.utils +import com.fasterxml.jackson.core.JsonParser +import com.fasterxml.jackson.core.TreeNode +import com.fasterxml.jackson.databind.DeserializationContext +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer +import com.fasterxml.jackson.databind.module.SimpleModule +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import dev.fyloz.colorrecipesexplorer.model.account.User +import dev.fyloz.colorrecipesexplorer.model.account.userOutputDto import io.jsonwebtoken.Claims +import io.jsonwebtoken.Jws import io.jsonwebtoken.Jwts import io.jsonwebtoken.SignatureAlgorithm +import io.jsonwebtoken.io.DeserializationException +import io.jsonwebtoken.io.Deserializer import io.jsonwebtoken.io.Encoders +import io.jsonwebtoken.io.IOException +import io.jsonwebtoken.jackson.io.JacksonDeserializer import io.jsonwebtoken.security.Keys import java.util.* import javax.crypto.SecretKey -data class Jwt( + +data class Jwt( val subject: String, val secret: String, val duration: Long? = null, val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512, - val claims: Map = mapOf() + val body: B? = null ) { val token: String by lazy { val builder = Jwts.builder() .signWith(keyFromSecret(secret)) .setSubject(subject) - .addClaims(mappedClaims) + .claim("payload", body) duration?.let { val expirationMs = System.currentTimeMillis() + it @@ -31,45 +45,95 @@ data class Jwt( builder.compact() } - - private val mappedClaims: Map by lazy { - claims - .filterValues { it != null } - .mapKeys { it.key.claim } - .mapValues { it.value.toString() } - } } -enum class JwtClaim(val claim: String) { +enum class ClaimType(val key: String) { GROUP_ID("groupId"), GROUP_NAME("groupName") } +data class UserJwtBody( + val groupId: Long?, + val groupName: String? +) + /** Build a [Jwt] for the given [User]. */ fun User.buildJwt(secret: String, duration: Long?) = Jwt( subject = this.id.toString(), secret, duration, - claims = mapOf( - JwtClaim.GROUP_ID to this.group?.id, - JwtClaim.GROUP_NAME to this.group?.name - ) + body = userOutputDto(this) ) +//class JacksonDeserializer( +// val claimTypeMap: Map> +//) : Deserializer { +// val objectMapper: ObjectMapper +// +// init { +// objectMapper = jacksonObjectMapper() +// +// val module = SimpleModule() +// module.addDeserializer(Any::class.java, MappedTypeDeserializer(Collections.unmodifiableMap(claimTypeMap))) +// objectMapper.registerModule(module) +// } +// +// override fun deserialize(bytes: ByteArray?): T { +// return try { +// readValue(bytes) +// } catch (e: IOException) { +// val msg = +// "Unable to deserialize bytes into a " + returnType.getName().toString() + " instance: " + e.getMessage() +// throw DeserializationException(msg, e) +// } +// } +// +// protected fun readValue(bytes: ByteArray?): T { +// return objectMapper.readValue(bytes, returnType) +// } +//} +// +//private class MappedTypeDeserializer( +// private val claimTypeMap: Map> +//) : UntypedObjectDeserializer(null, null) { +// override fun deserialize(parser: JsonParser, context: DeserializationContext): Any { +// val name: String = parser.currentName() +// if (claimTypeMap.containsKey(name)) { +// val type = claimTypeMap[name]!! +// return parser.readValueAsTree().traverse(parser.codec).readValueAs(type) +// } +// // otherwise default to super +// return super.deserialize(parser, context) +// } +//} + +class CustomDeserializer(map: Map>) { + private val objectMapper: ObjectMapper = jacksonObjectMapper() + private val returnType: Class = Object::class.java as Class +} + /** Parses the given [jwt] string. */ -fun parseJwt(jwt: String, secret: String) = +inline fun parseJwt(jwt: String, secret: String) = with( Jwts.parserBuilder() + .deserializeJsonWith(JacksonDeserializer(mapOf("payload" to B::class.java))) .setSigningKey(keyFromSecret(secret)) .build() .parseClaimsJws(jwt) ) { - Jwt(this.body.subject, secret) + val jwt = Jwt(this.body.subject, secret) + + val payload = this.body.get("payload", B::class.java) + jwt } /** Creates a base64 encoded [SecretKey] from the given [secret]. */ -private fun keyFromSecret(secret: String) = +fun keyFromSecret(secret: String) = with(Encoders.BASE64.encode(secret.toByteArray())) { Keys.hmacShaKeyFor(this.toByteArray()) } + +/** Gets the claim with the given [claimType] in a [Jws]. */ +private inline fun Jws.getClaim(claimType: ClaimType) = + this.body.get(claimType.key, T::class.java) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt index 48bce7d..7fd9b53 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/AccountsServiceTest.kt @@ -19,7 +19,6 @@ import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue -import org.springframework.security.core.userdetails.User as SpringUser @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserServiceTest : diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt index 0e055ad..8d73364 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt @@ -6,6 +6,7 @@ import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.model.account.group import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.users.GroupService import io.mockk.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test From 2bd59e72c60fe8e56f09d35b4c44a7570f13904b Mon Sep 17 00:00:00 2001 From: William Nolin Date: Tue, 31 Aug 2021 10:36:13 -0400 Subject: [PATCH 24/37] #13 Add icon and logo to resources --- src/main/resources/images/favicon.png | Bin 0 -> 6745 bytes src/main/resources/images/logo.png | Bin 0 -> 2338 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/main/resources/images/favicon.png create mode 100644 src/main/resources/images/logo.png diff --git a/src/main/resources/images/favicon.png b/src/main/resources/images/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..1e877b7c56f791c9d054152b2bc3f64b2e394de2 GIT binary patch literal 6745 zcmeHKXH-*J*A608QA9;4Vu*+eh7=M=0uhleAW=Yy1(KT^2#`V&LO`Ud)S)OKBkF(( zQUyejCLI-(ricYWK!veT^wmKG<-0-0(e=%rdDlDt%vv}1-gEYT_TJBa?pf!=Qg&D= z$g9f3U@!$6Yx7;u9WB0OrJ;Y91=GvBG$$-H` zkH%d02%nOc%#P|XAidJx+mTQl?ObeWQEF1V#YUW&s0JW+q^ zlT1mAW{urmTiw>DX?xf^xjR3-Ir>Q>WME<@t)paeI=g?LhdC}M$;g*DQGYqQFzTsR z<(Zm9ACvm7>nQgvGbO)~NHW_E&c?+13wt^ecNy2oddcuM-#Wf~I#iC7^qY|S&7j)rsY!BLGfVa4^kgS6W&JT`yDT%a-Wx23yhk>YC%>J|0mq*G- zZBohU{GC^FUh6)VeZYTYqDxpkcgT0Zs(I&{o<7s*$$s5L4fmKV@UXgNa%t1!Q4L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1w(_*+FB}|LgG=gYT9#h?*~B&~gc_zNl}@?^n*mviKK&U$ylw zMu4Dy2Kh(){-oL%X^_=y*1%sxChD zOVezv%;yhzuxYcJFz88+YwgB|!SvRNF9}hOi4Yo;5!l#U$UK))U$D`jZCPF>G&Evk zZtCPcF!t-iC6b!577_2}!XDNc9P7E5e>|?!a@^FwDhOVVSLA~Pg*%O-7=Jt|64c&~7KNoep`-~O>Jx9nx(Mz0!V&xA{F zQ@qM4Gii^wJB**E&{8vqZ^NRAsgpKqMm7h8+^_ni;T?X8SgKRDZd53XZ%}~ccx8Jm z&3vo5&}hf`Et__>W~x1uix?_V`jwixY44hCZk8@F_2*MS5y#o$*j>$1{2@inmSYLl x@Nq562wD6^hZsk|>i1QS^)jki5~}dpf%3;rZVTj=Ifyy3vDjgLVVh^<{{b&*z8U}k literal 0 HcmV?d00001 diff --git a/src/main/resources/images/logo.png b/src/main/resources/images/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..08822c80f11c5da7d23f4d739afe4904d62c71d6 GIT binary patch literal 2338 zcmV+-3ElRIP)EX>4Tx04R}tkv&MmKpe$iQ>7wR5eteaWT;LSL`5963Pq?8YK2xEOfLO`CJjl7 zi=*ILaPVWX>fqw6tAnc`2!4RLxj8AiNQwVT3oT+iIPS;0dyl(!fKV+m&1xG5G~G56 zv8b3zuZn?J_|cDU^kP_MmN6$uad?ied-(Wz7vWjn=l&dBYQ|!KPb8jYhG`RT5KnK~ z2Iqa^5X;Ld@j3CBNf#u3x%5W^ytAVGwJG72cdMub+K6blL3k9znAUB5&wg+6mx)2Cnp`zf=WgK1r`M zweS(pvkhEaH#KDsxZD8-o($QPUCB>V$Yz1}Gy0}9(02=TuGM>M?BnzSNK#kv8{ps& z7|l`ky2raaT6_EVOryUaL!fe$BtIkI00006VoOIv00000008+zyMF)x010qNS#tmY zE+YT{E+YYWr9XB6000McNlirueSad^gZEa<4bO1wgWnpw> zWFU8GbZ8()Nlj2!fese{00#O=L_t(|+U=ZsOcX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_PA^ZE~hpsAlANL1pzz+&%ArKYCR*%@b&l9DVoHjBMRWsEMJ$6ba&KH^4G zKS79f>Q7Hkr?W#?{?tzpH1!iCDnXE_1c^!zBq~9WsKoog-#&w-3(eC)1ONa407*qo IM6N<$g1U)NkpKVy literal 0 HcmV?d00001 From a02099387e844e237f9ec5b1e0e1f1732302a906 Mon Sep 17 00:00:00 2001 From: William Nolin Date: Wed, 1 Sep 2021 17:53:19 -0400 Subject: [PATCH 25/37] #13 Add icon and logo endpoints to ConfigurationController --- .../model/Configuration.kt | 12 +--- .../rest/ConfigurationController.kt | 31 +++++++-- .../rest/FileController.kt | 11 ++-- .../colorrecipesexplorer/rest/RestUtils.kt | 13 ++++ .../rest/TouchUpKitController.kt | 4 +- .../service/MaterialService.kt | 3 +- .../service/RecipeService.kt | 3 +- .../service/TouchUpKitService.kt | 9 ++- .../service/config/ConfigurationService.kt | 61 ++++++++++++++---- .../service/config/ConfigurationSource.kt | 2 +- .../service/{ => files}/FileService.kt | 15 +++-- .../service/files/ResourceFileService.kt | 26 ++++++++ .../images/{favicon.png => icon.png} | Bin 13 files changed, 143 insertions(+), 47 deletions(-) rename src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/{ => files}/FileService.kt (96%) create mode 100644 src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt rename src/main/resources/images/{favicon.png => icon.png} (100%) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt index b913523..990551c 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/Configuration.kt @@ -100,19 +100,13 @@ enum class ConfigurationType( val secure: Boolean = false ) { INSTANCE_NAME("instance.name", defaultContent = "Color Recipes Explorer", public = true), - INSTANCE_LOGO_PATH("instance.logo.path", defaultContent = "images/logo", public = true), - INSTANCE_ICON_PATH("instance.icon.path", defaultContent = "images/icon", public = true), + INSTANCE_LOGO_SET("instance.logo.set", defaultContent = false, public = true), + INSTANCE_ICON_SET("instance.icon.set", defaultContent = false, public = true), INSTANCE_URL("instance.url", "http://localhost:9090", public = true), DATABASE_URL("database.url", defaultContent = "mysql://localhost/cre", file = true, requireRestart = true), DATABASE_USER("database.user", defaultContent = "cre", file = true, requireRestart = true), - DATABASE_PASSWORD( - "database.password", - defaultContent = "asecurepassword", - file = true, - requireRestart = true, - secure = true - ), + DATABASE_PASSWORD("database.password", defaultContent = "asecurepassword", file = true, requireRestart = true, secure = true), DATABASE_SUPPORTED_VERSION("database.version.supported", computed = true), RECIPE_APPROBATION_EXPIRATION("recipe.approbation.expiration", defaultContent = 4.months), diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt index 1e7cff4..5e30ea6 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt @@ -7,6 +7,7 @@ import dev.fyloz.colorrecipesexplorer.model.account.Permission import dev.fyloz.colorrecipesexplorer.model.account.toAuthority import dev.fyloz.colorrecipesexplorer.restartApplication import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.core.Authentication import org.springframework.web.bind.annotation.* @@ -33,17 +34,35 @@ class ConfigurationController(val configurationService: ConfigurationService) { configurationService.set(configurations) } - @PutMapping("image") - @PreAuthorize("hasAuthority('ADMIN')") - fun setImage(@RequestParam @NotBlank key: String, @RequestParam @NotBlank image: MultipartFile) = noContent { - configurationService.set(ConfigurationImageDto(key, image)) - } - @PostMapping("restart") @PreAuthorize("hasAuthority('ADMIN')") fun restart() = noContent { restartApplication() } + + // Icon + + @GetMapping("icon") + fun getIcon() = + ok(configurationService.getConfiguredIcon(), MediaType.IMAGE_PNG_VALUE) + + @PutMapping("icon") + @PreAuthorize("hasAuthority('ADMIN')") + fun setIcon(@RequestParam icon: MultipartFile) = noContent { + configurationService.setConfiguredIcon(icon) + } + + // Logo + + @GetMapping("logo") + fun getLogo() = + ok(configurationService.getConfiguredLogo(), MediaType.IMAGE_PNG_VALUE) + + @PutMapping("logo") + @PreAuthorize("hasAuthority('ADMIN')") + fun setLogo(@RequestParam logo: MultipartFile) = noContent { + configurationService.setConfiguredLogo(logo) + } } private fun Authentication?.hasAuthority(configuration: ConfigurationBase) = when { diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt index 5f1e689..c7879d6 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt @@ -2,8 +2,9 @@ package dev.fyloz.colorrecipesexplorer.rest import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService -import dev.fyloz.colorrecipesexplorer.service.FileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize @@ -12,19 +13,18 @@ import org.springframework.web.multipart.MultipartFile import java.net.URI const val FILE_CONTROLLER_PATH = "/api/file" -private const val DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_OCTET_STREAM_VALUE @RestController @RequestMapping(FILE_CONTROLLER_PATH) class FileController( - private val fileService: FileService, + private val fileService: WriteableFileService, private val configService: ConfigurationService ) { @GetMapping(produces = [MediaType.APPLICATION_OCTET_STREAM_VALUE]) fun upload( @RequestParam path: String, @RequestParam(required = false) mediaType: String? - ): ResponseEntity { + ): ResponseEntity { val file = fileService.read(path) return ResponseEntity.ok() .header("Content-Disposition", "filename=${getFileNameFromPath(path)}") @@ -56,7 +56,4 @@ class FileController( ResponseEntity .created(URI.create("${configService.get(ConfigurationType.INSTANCE_URL)}$FILE_CONTROLLER_PATH?path=$path")) .build() - - private fun getFileNameFromPath(path: String) = - path.split("/").last() } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt index 23d59da..36b892e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt @@ -2,12 +2,14 @@ package dev.fyloz.colorrecipesexplorer.rest import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.model.Model +import org.springframework.core.io.Resource import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import java.net.URI +const val DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_OCTET_STREAM_VALUE lateinit var CRE_PROPERTIES: CreProperties /** Creates a HTTP OK [ResponseEntity] from the given [body]. */ @@ -24,6 +26,14 @@ fun ok(action: () -> Unit): ResponseEntity { return ResponseEntity.ok().build() } +fun ok(file: Resource, mediaType: String? = null): ResponseEntity { + return ResponseEntity.ok() + .header("Content-Disposition", "filename=${file.filename}") + .contentLength(file.contentLength()) + .contentType(MediaType.parseMediaType(mediaType ?: DEFAULT_MEDIA_TYPE)) + .body(file) +} + /** Creates a HTTP CREATED [ResponseEntity] from the given [body] with the location set to [controllerPath]/id. */ fun created(controllerPath: String, body: T): ResponseEntity = created(controllerPath, body, body.id!!) @@ -63,3 +73,6 @@ fun httpHeaders( op() } + +fun getFileNameFromPath(path: String) = + path.split("/").last() diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/TouchUpKitController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/TouchUpKitController.kt index e9cbe47..027d71d 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/TouchUpKitController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/TouchUpKitController.kt @@ -5,7 +5,7 @@ import dev.fyloz.colorrecipesexplorer.model.touchupkit.TouchUpKitSaveDto import dev.fyloz.colorrecipesexplorer.model.touchupkit.TouchUpKitUpdateDto import dev.fyloz.colorrecipesexplorer.service.TouchUpKitService import org.springframework.context.annotation.Profile -import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize @@ -57,7 +57,7 @@ class TouchUpKitController( } @GetMapping("pdf") - fun getJobPdf(@RequestParam project: String): ResponseEntity { + fun getJobPdf(@RequestParam project: String): ResponseEntity { with(touchUpKitService.generateJobPdfResource(project)) { return ResponseEntity.ok() .header("Content-Disposition", "filename=TouchUpKit_$project.pdf") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt index 7d752f9..327d6e2 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialService.kt @@ -4,6 +4,7 @@ import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.repository.MaterialRepository import dev.fyloz.colorrecipesexplorer.rest.FILE_CONTROLLER_PATH import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import io.jsonwebtoken.lang.Assert import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Profile @@ -39,7 +40,7 @@ class MaterialServiceImpl( val recipeService: RecipeService, val mixService: MixService, @Lazy val materialTypeService: MaterialTypeService, - val fileService: FileService, + val fileService: WriteableFileService, val configService: ConfigurationService ) : AbstractExternalNamedModelService( diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt index 4dcda07..4361728 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeService.kt @@ -5,6 +5,7 @@ import dev.fyloz.colorrecipesexplorer.model.account.Group import dev.fyloz.colorrecipesexplorer.model.validation.or import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.setAll import org.springframework.context.annotation.Lazy import org.springframework.context.annotation.Profile @@ -222,7 +223,7 @@ const val RECIPE_IMAGE_EXTENSION = ".jpg" @Service @Profile("!emergency") class RecipeImageServiceImpl( - val fileService: FileService + val fileService: WriteableFileService ) : RecipeImageService { override fun getAllImages(recipe: Recipe): Set { val recipeDirectory = recipe.getDirectory() diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt index b966525..a6bbc1e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitService.kt @@ -5,9 +5,12 @@ import dev.fyloz.colorrecipesexplorer.model.touchupkit.* import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository import dev.fyloz.colorrecipesexplorer.rest.TOUCH_UP_KIT_CONTROLLER_PATH import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.FileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.* import org.springframework.context.annotation.Profile import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource import org.springframework.stereotype.Service import java.time.LocalDate import java.time.Period @@ -32,7 +35,7 @@ interface TouchUpKitService : * If TOUCH_UP_KIT_CACHE_PDF is enabled and a file exists for the job, its content will be returned. * If caching is enabled but no file exists for the job, the generated ByteArrayResource will be cached on the disk. */ - fun generateJobPdfResource(job: String): ByteArrayResource + fun generateJobPdfResource(job: String): Resource /** Writes the given [document] to the [FileService] if TOUCH_UP_KIT_CACHE_PDF is enabled. */ fun String.cachePdfDocument(document: PdfDocument) @@ -41,7 +44,7 @@ interface TouchUpKitService : @Service @Profile("!emergency") class TouchUpKitServiceImpl( - private val fileService: FileService, + private val fileService: WriteableFileService, private val configService: ConfigurationService, touchUpKitRepository: TouchUpKitRepository ) : AbstractExternalModelService( @@ -120,7 +123,7 @@ class TouchUpKitServiceImpl( } } - override fun generateJobPdfResource(job: String): ByteArrayResource { + override fun generateJobPdfResource(job: String): Resource { if (cacheGeneratedFiles) { with(job.pdfDocumentPath()) { if (fileService.exists(this)) { diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt index 8e5d0c2..302c3b3 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt @@ -2,13 +2,16 @@ package dev.fyloz.colorrecipesexplorer.service.config import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.model.* -import dev.fyloz.colorrecipesexplorer.service.FileService +import dev.fyloz.colorrecipesexplorer.service.files.ResourceFileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.decrypt import dev.fyloz.colorrecipesexplorer.utils.encrypt import org.slf4j.Logger import org.springframework.context.annotation.Lazy +import org.springframework.core.io.Resource import org.springframework.security.crypto.keygen.KeyGenerators import org.springframework.stereotype.Service +import org.springframework.web.multipart.MultipartFile interface ConfigurationService { /** Gets all set configurations. */ @@ -35,6 +38,12 @@ interface ConfigurationService { /** Gets the content of the secure configuration with the given [type]. Should not be accessible to the users. */ fun getSecure(type: ConfigurationType): String + /** Gets the app's icon. */ + fun getConfiguredIcon(): Resource + + /** Gets the app's logo. */ + fun getConfiguredLogo(): Resource + /** Sets the content of each configuration in the given [configurations] list. */ fun set(configurations: List) @@ -47,20 +56,26 @@ interface ConfigurationService { /** Sets the content given [configuration]. */ fun set(configuration: Configuration) - /** Sets the content of the configuration matching the given [configuration] with a given image. */ - fun set(configuration: ConfigurationImageDto) + /** Sets the app's icon. */ + fun setConfiguredIcon(icon: MultipartFile) + + /** Sets the app's logo. */ + fun setConfiguredLogo(logo: MultipartFile) /** Initialize the properties matching the given [predicate]. */ fun initializeProperties(predicate: (ConfigurationType) -> Boolean) } +const val CONFIGURATION_LOGO_RESOURCE_PATH = "images/logo.png" const val CONFIGURATION_LOGO_FILE_PATH = "images/logo" +const val CONFIGURATION_ICON_RESOURCE_PATH = "images/icon.png" const val CONFIGURATION_ICON_FILE_PATH = "images/icon" const val CONFIGURATION_FORMATTED_LIST_DELIMITER = ';' @Service("configurationService") class ConfigurationServiceImpl( - @Lazy private val fileService: FileService, + @Lazy private val fileService: WriteableFileService, + private val resourceFileService: ResourceFileService, private val configurationSource: ConfigurationSource, private val securityProperties: CreSecurityProperties, private val logger: Logger @@ -121,6 +136,29 @@ class ConfigurationServiceImpl( return decryptConfiguration(configuration).content } + override fun getConfiguredIcon() = + getConfiguredImage( + type = ConfigurationType.INSTANCE_ICON_SET, + filePath = CONFIGURATION_ICON_FILE_PATH, + resourcePath = CONFIGURATION_ICON_RESOURCE_PATH + ) + + override fun getConfiguredLogo() = + getConfiguredImage( + type = ConfigurationType.INSTANCE_LOGO_SET, + filePath = CONFIGURATION_LOGO_FILE_PATH, + resourcePath = CONFIGURATION_LOGO_RESOURCE_PATH + ) + + private fun getConfiguredImage(type: ConfigurationType, filePath: String, resourcePath: String) = + with(get(type) as Configuration) { + if (this.content == true.toString()) { + fileService.read(filePath) + } else { + resourceFileService.read(resourcePath) + } + } + override fun set(configurations: List) { configurationSource.set( configurations @@ -136,14 +174,15 @@ class ConfigurationServiceImpl( configurationSource.set(encryptConfigurationIfSecure(configuration)) } - override fun set(configuration: ConfigurationImageDto) { - val filePath = when (val configurationType = configuration.key.toConfigurationType()) { - ConfigurationType.INSTANCE_LOGO_PATH -> CONFIGURATION_LOGO_FILE_PATH - ConfigurationType.INSTANCE_ICON_PATH -> CONFIGURATION_ICON_FILE_PATH - else -> throw InvalidImageConfigurationException(configurationType) - } + override fun setConfiguredIcon(icon: MultipartFile) = + setConfiguredImage(icon, CONFIGURATION_ICON_FILE_PATH, ConfigurationType.INSTANCE_ICON_SET) - fileService.write(configuration.image, filePath, true) + override fun setConfiguredLogo(logo: MultipartFile) = + setConfiguredImage(logo, CONFIGURATION_LOGO_FILE_PATH, ConfigurationType.INSTANCE_LOGO_SET) + + private fun setConfiguredImage(image: MultipartFile, path: String, type: ConfigurationType) { + fileService.write(image, path, true) + set(configuration(type, content = true.toString())) } override fun initializeProperties(predicate: (ConfigurationType) -> Boolean) { diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationSource.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationSource.kt index 0b00a97..6971f9e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationSource.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationSource.kt @@ -8,7 +8,7 @@ import dev.fyloz.colorrecipesexplorer.model.Configuration import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.configuration import dev.fyloz.colorrecipesexplorer.repository.ConfigurationRepository -import dev.fyloz.colorrecipesexplorer.service.create +import dev.fyloz.colorrecipesexplorer.service.files.create import dev.fyloz.colorrecipesexplorer.utils.excludeAll import org.slf4j.Logger import org.springframework.boot.info.BuildProperties diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/FileService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileService.kt similarity index 96% rename from src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/FileService.kt rename to src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileService.kt index 69cd4aa..4136ebe 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/FileService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileService.kt @@ -1,9 +1,10 @@ -package dev.fyloz.colorrecipesexplorer.service +package dev.fyloz.colorrecipesexplorer.service.files import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.exception.RestException import org.slf4j.Logger import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.web.multipart.MultipartFile @@ -23,8 +24,13 @@ interface FileService { fun exists(path: String): Boolean /** Reads the file at the given [path]. */ - fun read(path: String): ByteArrayResource + fun read(path: String): Resource + /** Completes the path of the given [String] by adding the working directory. */ + fun String.fullPath(): FilePath +} + +interface WriteableFileService : FileService { /** Creates a file at the given [path]. */ fun create(path: String) @@ -36,16 +42,13 @@ interface FileService { /** Deletes the file at the given [path]. */ fun delete(path: String) - - /** Completes the path of the given [String] by adding the working directory. */ - fun String.fullPath(): FilePath } @Service class FileServiceImpl( private val creProperties: CreProperties, private val logger: Logger -) : FileService { +) : WriteableFileService { override fun exists(path: String) = withFileAt(path.fullPath()) { this.exists() && this.isFile } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt new file mode 100644 index 0000000..8ac67f5 --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt @@ -0,0 +1,26 @@ +package dev.fyloz.colorrecipesexplorer.service.files + +import org.springframework.core.io.Resource +import org.springframework.core.io.ResourceLoader +import org.springframework.stereotype.Service + +@Service +class ResourceFileService( + private val resourceLoader: ResourceLoader +) : FileService { + override fun exists(path: String) = + read(path).exists() + + override fun read(path: String): Resource = + path.fullPath().resource.also { + if (!it.exists()) { + throw FileNotFoundException(path) + } + } + + override fun String.fullPath() = + FilePath("classpath:${this}") + + private val FilePath.resource: Resource + get() = resourceLoader.getResource(this.path) +} diff --git a/src/main/resources/images/favicon.png b/src/main/resources/images/icon.png similarity index 100% rename from src/main/resources/images/favicon.png rename to src/main/resources/images/icon.png From e1ca6a8d837e9376d79e6c9622914f8c5f1579d6 Mon Sep 17 00:00:00 2001 From: William Nolin Date: Wed, 1 Sep 2021 17:59:53 -0400 Subject: [PATCH 26/37] #13 Update FileController to use new HTTP OK util function --- .../colorrecipesexplorer/rest/FileController.kt | 16 +++------------- .../fyloz/colorrecipesexplorer/rest/RestUtils.kt | 6 +++--- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt index c7879d6..b4cfd14 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt @@ -3,8 +3,6 @@ package dev.fyloz.colorrecipesexplorer.rest import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService -import org.springframework.core.io.ByteArrayResource -import org.springframework.core.io.Resource import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize @@ -24,14 +22,7 @@ class FileController( fun upload( @RequestParam path: String, @RequestParam(required = false) mediaType: String? - ): ResponseEntity { - val file = fileService.read(path) - return ResponseEntity.ok() - .header("Content-Disposition", "filename=${getFileNameFromPath(path)}") - .contentLength(file.contentLength()) - .contentType(MediaType.parseMediaType(mediaType ?: DEFAULT_MEDIA_TYPE)) - .body(file) - } + ) = ok(fileService.read(path), mediaType) @PutMapping(consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) @PreAuthorize("hasAnyAuthority('WRITE_FILE')") @@ -46,11 +37,10 @@ class FileController( @DeleteMapping @PreAuthorize("hasAnyAuthority('WRITE_FILE')") - fun delete(@RequestParam path: String): ResponseEntity { - return noContent { + fun delete(@RequestParam path: String): ResponseEntity = + noContent { fileService.delete(path) } - } private fun created(path: String): ResponseEntity = ResponseEntity diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt index 36b892e..23f115d 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt @@ -26,13 +26,13 @@ fun ok(action: () -> Unit): ResponseEntity { return ResponseEntity.ok().build() } -fun ok(file: Resource, mediaType: String? = null): ResponseEntity { - return ResponseEntity.ok() +/** Creates a HTTP OK [ResponseEntity] for the given [file], with the given [mediaType]. */ +fun ok(file: Resource, mediaType: String? = null): ResponseEntity = + ResponseEntity.ok() .header("Content-Disposition", "filename=${file.filename}") .contentLength(file.contentLength()) .contentType(MediaType.parseMediaType(mediaType ?: DEFAULT_MEDIA_TYPE)) .body(file) -} /** Creates a HTTP CREATED [ResponseEntity] from the given [body] with the location set to [controllerPath]/id. */ fun created(controllerPath: String, body: T): ResponseEntity = From 9a260b6edf81beec342cec589a0d52a6c0d62c99 Mon Sep 17 00:00:00 2001 From: William Nolin Date: Tue, 7 Sep 2021 10:23:56 -0400 Subject: [PATCH 27/37] #13 Add tests --- build.gradle.kts | 6 +- .../rest/ConfigurationController.kt | 4 +- .../rest/FileController.kt | 2 +- .../colorrecipesexplorer/rest/RestUtils.kt | 2 +- .../service/files/ResourceFileService.kt | 4 +- .../service/ConfigurationServiceTest.kt | 144 ++++++++++++++++-- .../service/MaterialServiceTest.kt | 4 +- .../service/RecipeServiceTest.kt | 3 +- .../service/TouchUpKitServiceTest.kt | 6 +- .../service/{ => files}/FileServiceTest.kt | 2 +- .../service/files/ResourceFileServiceTest.kt | 114 ++++++++++++++ 11 files changed, 264 insertions(+), 27 deletions(-) rename src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/{ => files}/FileServiceTest.kt (99%) create mode 100644 src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileServiceTest.kt diff --git a/build.gradle.kts b/build.gradle.kts index 9912eaf..ee0689e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -46,10 +46,10 @@ dependencies { implementation("org.springframework.boot:spring-boot-devtools:${springBootVersion}") testImplementation("org.springframework:spring-test:5.1.6.RELEASE") - testImplementation("org.mockito:mockito-inline:3.11.2") + testImplementation("org.mockito:mockito-inline:3.12.4") testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0") - testImplementation("org.junit.jupiter:junit-jupiter-api:5.3.2") - testImplementation("io.mockk:mockk:1.10.6") + testImplementation("org.junit.jupiter:junit-jupiter-api:5.7.2") + testImplementation("io.mockk:mockk:1.12.0") testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}") testImplementation("org.springframework.boot:spring-boot-test-autoconfigure:${springBootVersion}") testImplementation("org.jetbrains.kotlin:kotlin-test:${kotlinVersion}") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt index 5e30ea6..db64365 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/ConfigurationController.kt @@ -44,7 +44,7 @@ class ConfigurationController(val configurationService: ConfigurationService) { @GetMapping("icon") fun getIcon() = - ok(configurationService.getConfiguredIcon(), MediaType.IMAGE_PNG_VALUE) + okFile(configurationService.getConfiguredIcon(), MediaType.IMAGE_PNG_VALUE) @PutMapping("icon") @PreAuthorize("hasAuthority('ADMIN')") @@ -56,7 +56,7 @@ class ConfigurationController(val configurationService: ConfigurationService) { @GetMapping("logo") fun getLogo() = - ok(configurationService.getConfiguredLogo(), MediaType.IMAGE_PNG_VALUE) + okFile(configurationService.getConfiguredLogo(), MediaType.IMAGE_PNG_VALUE) @PutMapping("logo") @PreAuthorize("hasAuthority('ADMIN')") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt index b4cfd14..92b078a 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/FileController.kt @@ -22,7 +22,7 @@ class FileController( fun upload( @RequestParam path: String, @RequestParam(required = false) mediaType: String? - ) = ok(fileService.read(path), mediaType) + ) = okFile(fileService.read(path), mediaType) @PutMapping(consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) @PreAuthorize("hasAnyAuthority('WRITE_FILE')") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt index 23f115d..7147aa0 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/RestUtils.kt @@ -27,7 +27,7 @@ fun ok(action: () -> Unit): ResponseEntity { } /** Creates a HTTP OK [ResponseEntity] for the given [file], with the given [mediaType]. */ -fun ok(file: Resource, mediaType: String? = null): ResponseEntity = +fun okFile(file: Resource, mediaType: String? = null): ResponseEntity = ResponseEntity.ok() .header("Content-Disposition", "filename=${file.filename}") .contentLength(file.contentLength()) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt index 8ac67f5..be9ba6e 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileService.kt @@ -9,7 +9,7 @@ class ResourceFileService( private val resourceLoader: ResourceLoader ) : FileService { override fun exists(path: String) = - read(path).exists() + path.fullPath().resource.exists() override fun read(path: String): Resource = path.fullPath().resource.also { @@ -21,6 +21,6 @@ class ResourceFileService( override fun String.fullPath() = FilePath("classpath:${this}") - private val FilePath.resource: Resource + val FilePath.resource: Resource get() = resourceLoader.getResource(this.path) } diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt index e49fc60..ea4a73f 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt @@ -5,23 +5,35 @@ import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.service.config.CONFIGURATION_FORMATTED_LIST_DELIMITER import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationServiceImpl import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationSource +import dev.fyloz.colorrecipesexplorer.service.files.ResourceFileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.encrypt import io.mockk.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows -import kotlin.UnsupportedOperationException +import org.springframework.core.io.Resource +import org.springframework.web.multipart.MultipartFile import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class ConfigurationServiceTest { - private val fileService = mockk() + private val fileService = mockk() + private val resourceFileService = mockk() private val configurationSource = mockk() private val securityProperties = mockk { every { configSalt } returns "d32270943af7e1cc" } - private val service = spyk(ConfigurationServiceImpl(fileService, configurationSource, securityProperties, mockk())) + private val service = spyk( + ConfigurationServiceImpl( + fileService, + resourceFileService, + configurationSource, + securityProperties, + mockk() + ) + ) @AfterEach fun afterEach() { @@ -49,8 +61,8 @@ class ConfigurationServiceTest { fun `getAll() only returns set configurations`() { val unsetConfigurationTypes = listOf( ConfigurationType.INSTANCE_NAME, - ConfigurationType.INSTANCE_LOGO_PATH, - ConfigurationType.INSTANCE_ICON_PATH + ConfigurationType.INSTANCE_LOGO_SET, + ConfigurationType.INSTANCE_ICON_SET ) every { service.get(match { it in unsetConfigurationTypes }) } answers { @@ -82,8 +94,8 @@ class ConfigurationServiceTest { fun `getAll() only includes configurations matching the formatted formatted key list`() { val configurationTypes = listOf( ConfigurationType.INSTANCE_NAME, - ConfigurationType.INSTANCE_LOGO_PATH, - ConfigurationType.INSTANCE_ICON_PATH + ConfigurationType.INSTANCE_LOGO_SET, + ConfigurationType.INSTANCE_ICON_SET ) val formattedKeyList = configurationTypes .map { it.key } @@ -113,7 +125,7 @@ class ConfigurationServiceTest { @Test fun `get(key) calls get() with the ConfigurationType matching the given key`() { - val type = ConfigurationType.INSTANCE_ICON_PATH + val type = ConfigurationType.INSTANCE_ICON_SET val key = type.key every { service.get(type) } answers { @@ -132,7 +144,7 @@ class ConfigurationServiceTest { @Test fun `get(type) gets the configuration in the ConfigurationSource`() { - val type = ConfigurationType.INSTANCE_ICON_PATH + val type = ConfigurationType.INSTANCE_ICON_SET val configuration = configuration(type = type) every { configurationSource.get(type) } returns configuration @@ -144,7 +156,7 @@ class ConfigurationServiceTest { @Test fun `get(type) throws ConfigurationNotSetException when the given ConfigurationType has no set configuration`() { - val type = ConfigurationType.INSTANCE_ICON_PATH + val type = ConfigurationType.INSTANCE_ICON_SET every { configurationSource.get(type) } returns null @@ -228,6 +240,57 @@ class ConfigurationServiceTest { assertThrows { service.getSecure(type) } } + private fun getConfiguredImageTest( + configurationType: ConfigurationType, + imageSet: Boolean, + test: (Resource) -> Unit + ) { + val resource = mockk() + val configuration = configuration(configurationType, imageSet.toString()) + val imageService = if (imageSet) fileService else resourceFileService + + every { service.get(configurationType) } returns configuration + every { imageService.read(any()) } returns resource + + test(resource) + } + + @Test + fun `getConfiguredIcon() gets icon from resources when INSTANCE_ICON_SET configuration is false`() { + getConfiguredImageTest(ConfigurationType.INSTANCE_ICON_SET, false) { resource -> + val found = service.getConfiguredIcon() + + assertEquals(resource, found) + } + } + + @Test + fun `getConfiguredIcon() gets icon from files when INSTANCE_ICON_SET configuration is true`() { + getConfiguredImageTest(ConfigurationType.INSTANCE_ICON_SET, true) { resource -> + val found = service.getConfiguredIcon() + + assertEquals(resource, found) + } + } + + @Test + fun `getConfiguredLogo() gets logo from resources when INSTANCE_LOGO_SET is false`() { + getConfiguredImageTest(ConfigurationType.INSTANCE_LOGO_SET, false) { resource -> + val found = service.getConfiguredLogo() + + assertEquals(resource, found) + } + } + + @Test + fun `getConfiguredLogo() gets logo from files when INSTANCE_LOGO_SET is true`() { + getConfiguredImageTest(ConfigurationType.INSTANCE_LOGO_SET, true) { resource -> + val found = service.getConfiguredLogo() + + assertEquals(resource, found) + } + } + @Test fun `set(configuration) set configuration in ConfigurationSource`() { val configuration = configuration(type = ConfigurationType.INSTANCE_NAME) @@ -261,4 +324,65 @@ class ConfigurationServiceTest { }) } } + + private fun setConfiguredImageTest(test: (MultipartFile) -> Unit) { + val file = mockk() + + every { service.set(any()) } just runs + every { fileService.write(any(), any(), any()) } just runs + + test(file) + } + + @Test + fun `setConfiguredIcon() sets icon in files`() { + setConfiguredImageTest { file -> + service.setConfiguredIcon(file) + + verify { + fileService.write(file, any(), true) + } + } + } + + @Test + fun `setConfiguredIcon() sets INSTANCE_ICON_SET configuration to true`() { + val type = ConfigurationType.INSTANCE_ICON_SET + + setConfiguredImageTest { file -> + service.setConfiguredIcon(file) + + verify { + service.set(match { + it.key == type.key && it.content == true.toString() + }) + } + } + } + + @Test + fun `setConfiguredLogo() sets logo in files`() { + setConfiguredImageTest { file -> + service.setConfiguredLogo(file) + + verify { + fileService.write(file, any(), true) + } + } + } + + @Test + fun `setConfiguredLogo() sets INSTANCE_LOGO_SET configuration to true`() { + val type = ConfigurationType.INSTANCE_LOGO_SET + + setConfiguredImageTest { file -> + service.setConfiguredLogo(file) + + verify { + service.set(match { + it.key == type.key && it.content == true.toString() + }) + } + } + } } diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt index 0962323..be7c476 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt @@ -4,7 +4,7 @@ import com.nhaarman.mockitokotlin2.* import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.repository.MaterialRepository -import dev.fyloz.colorrecipesexplorer.service.FileService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance @@ -21,7 +21,7 @@ class MaterialServiceTest : private val recipeService: RecipeService = mock() private val mixService: MixService = mock() private val materialTypeService: MaterialTypeService = mock() - private val fileService: FileService = mock() + private val fileService: WriteableFileService = mock() override val service: MaterialService = spy(MaterialServiceImpl(repository, recipeService, mixService, materialTypeService, fileService, mock())) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt index 0e055ad..d27a78c 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeServiceTest.kt @@ -6,6 +6,7 @@ import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.model.account.group import dev.fyloz.colorrecipesexplorer.repository.RecipeRepository import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import io.mockk.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test @@ -263,7 +264,7 @@ class RecipeServiceTest : } private class RecipeImageServiceTestContext { - val fileService = mockk { + val fileService = mockk { every { write(any(), any(), any()) } just Runs every { delete(any()) } just Runs } diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt index f6b5ba2..51ef288 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt @@ -1,11 +1,10 @@ package dev.fyloz.colorrecipesexplorer.service -import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.configuration import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository -import dev.fyloz.colorrecipesexplorer.service.* import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService +import dev.fyloz.colorrecipesexplorer.service.files.WriteableFileService import dev.fyloz.colorrecipesexplorer.utils.PdfDocument import dev.fyloz.colorrecipesexplorer.utils.toByteArrayResource import io.mockk.* @@ -16,10 +15,9 @@ import kotlin.test.assertEquals private class TouchUpKitServiceTestContext { val touchUpKitRepository = mockk() - val fileService = mockk { + val fileService = mockk { every { write(any(), any(), any()) } just Runs } - val creProperties = mockk() val configService = mockk(relaxed = true) val touchUpKitService = spyk(TouchUpKitServiceImpl(fileService, configService, touchUpKitRepository)) val pdfDocumentData = mockk() diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/FileServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileServiceTest.kt similarity index 99% rename from src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/FileServiceTest.kt rename to src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileServiceTest.kt index 8c4ca7a..936bf47 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/FileServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/FileServiceTest.kt @@ -1,4 +1,4 @@ -package dev.fyloz.colorrecipesexplorer.service +package dev.fyloz.colorrecipesexplorer.service.files import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import io.mockk.* diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileServiceTest.kt new file mode 100644 index 0000000..5c0d6ff --- /dev/null +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/files/ResourceFileServiceTest.kt @@ -0,0 +1,114 @@ +package dev.fyloz.colorrecipesexplorer.service.files + +import io.mockk.clearAllMocks +import io.mockk.every +import io.mockk.mockk +import io.mockk.spyk +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.springframework.core.io.Resource +import org.springframework.core.io.ResourceLoader +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ResourceFileServiceTest { + private val resourceLoader = mockk() + + private val service = spyk(ResourceFileService(resourceLoader)) + + @AfterEach + fun afterEach() { + clearAllMocks() + } + + private fun existsTest(shouldExists: Boolean, test: (String) -> Unit) { + val path = "unit_test_resource" + with(service) { + every { path.fullPath() } returns mockk { + every { resource } returns mockk { + every { exists() } returns shouldExists + } + } + + test(path) + } + } + + @Test + fun `exists() returns true when a resource exists at the given path`() { + existsTest(true) { path -> + val found = service.exists(path) + + assertTrue { found } + } + } + + @Test + fun `exists() returns false when no resource exists at the given path`() { + existsTest(false) { path -> + val found = service.exists(path) + + assertFalse { found } + } + } + + private fun readTest(shouldExists: Boolean, test: (Resource, String) -> Unit) { + val mockResource = mockk { + every { exists() } returns shouldExists + } + val path = "unit_test_path" + with(service) { + every { path.fullPath() } returns mockk { + every { resource } returns mockResource + } + + test(mockResource, path) + } + } + + @Test + fun `read() returns the resource at the given path`() { + readTest(true) { resource, path -> + val found = service.read(path) + + assertEquals(resource, found) + } + } + + @Test + fun `read() throws FileNotFoundException when no resource exists at the given path`() { + readTest(false) { _, path -> + assertThrows { + service.read(path) + } + } + } + + @Test + fun `fullPath() returns the given path in the classpath`() { + val path = "unit_test_path" + val expectedPath = "classpath:$path" + + with(service) { + val found = path.fullPath() + + assertEquals(expectedPath, found.path) + } + } + + @Test + fun `resource returns a resource for the given path`() { + val filePath = FilePath("classpath:unit_test_path") + val resource = mockk() + + every { resourceLoader.getResource(filePath.path) } returns resource + + with(service) { + val found = filePath.resource + + assertEquals(resource, found) + } + } +} From 1216ace3141892ea3e33d8c77c59dc7231329e39 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Sat, 11 Sep 2021 23:48:23 -0400 Subject: [PATCH 28/37] #12 JWT --- .../config/security/JwtFilters.kt | 28 ++-- .../model/account/User.kt | 30 ++-- .../service/users/UserService.kt | 2 +- .../fyloz/colorrecipesexplorer/utils/Jwt.kt | 141 ++++-------------- 4 files changed, 59 insertions(+), 142 deletions(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt index 4c8e5e5..d4a36bf 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt @@ -3,12 +3,9 @@ package dev.fyloz.colorrecipesexplorer.config.security import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.exception.NotFoundException -import dev.fyloz.colorrecipesexplorer.model.account.User -import dev.fyloz.colorrecipesexplorer.model.account.UserDetails -import dev.fyloz.colorrecipesexplorer.model.account.UserLoginRequest -import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.* import dev.fyloz.colorrecipesexplorer.utils.buildJwt -import dev.fyloz.colorrecipesexplorer.utils.parseJwt +import dev.fyloz.colorrecipesexplorer.utils.parseJwtUser import io.jsonwebtoken.ExpiredJwtException import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken @@ -30,7 +27,6 @@ class JwtAuthenticationFilter( private val securityProperties: CreSecurityProperties, private val updateUserLoginTime: (Long) -> Unit ) : UsernamePasswordAuthenticationFilter() { - private val objectMapper = jacksonObjectMapper() private var debugMode = false init { @@ -39,7 +35,7 @@ class JwtAuthenticationFilter( } override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication { - val loginRequest = objectMapper.readValue(request.inputStream, UserLoginRequest::class.java) + val loginRequest = jacksonObjectMapper().readValue(request.inputStream, UserLoginRequest::class.java) return authManager.authenticate(UsernamePasswordAuthenticationToken(loginRequest.id, loginRequest.password)) } @@ -50,8 +46,7 @@ class JwtAuthenticationFilter( auth: Authentication ) { val userDetails = (auth.principal as UserDetails) - val token = - userDetails.user.buildJwt(securityProperties.jwtSecret, duration = securityProperties.jwtDuration).token + val token = userDetails.user.buildJwt(securityProperties.jwtSecret, securityProperties.jwtDuration) var bearerCookie = "$authorizationCookieName=Bearer$token; Max-Age=${securityProperties.jwtDuration / 1000}; HttpOnly; SameSite=strict" @@ -104,18 +99,23 @@ class JwtAuthorizationFilter( private fun getAuthentication(token: String): UsernamePasswordAuthenticationToken? { return try { - with(parseJwt(token.replace("Bearer", ""), securityProperties.jwtSecret)) { - getAuthenticationToken(this.subject) - } + val user = parseJwtUser(token.replace("Bearer", ""), securityProperties.jwtSecret) + getAuthenticationToken(user) } catch (_: ExpiredJwtException) { null } } - private fun getAuthenticationToken(userId: String): UsernamePasswordAuthenticationToken? = try { - val userDetails = loadUserById(userId.toLong()) + private fun getAuthenticationToken(user: UserOutputDto) = + UsernamePasswordAuthenticationToken(user.id, null, user.permissions.toAuthorities()) + + private fun getAuthenticationToken(userId: Long): UsernamePasswordAuthenticationToken? = try { + val userDetails = loadUserById(userId) UsernamePasswordAuthenticationToken(userDetails.username, null, userDetails.authorities) } catch (_: NotFoundException) { null } + + private fun getAuthenticationToken(userId: String) = + getAuthenticationToken(userId.toLong()) } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt index 6fceff4..ac6f5d6 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/model/account/User.kt @@ -7,7 +7,6 @@ import dev.fyloz.colorrecipesexplorer.model.EntityDto import dev.fyloz.colorrecipesexplorer.model.Model import org.hibernate.annotations.Fetch import org.hibernate.annotations.FetchMode -import org.springframework.security.core.GrantedAuthority import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import java.time.LocalDateTime @@ -111,9 +110,7 @@ data class UserLoginRequest(val id: Long, val password: String) data class UserDetails(val user: User) : SpringUserDetails { override fun getPassword() = user.password override fun getUsername() = user.id.toString() - - override fun getAuthorities() = - user.flatPermissions.map { it.toAuthority() }.toMutableSet() + override fun getAuthorities() = user.flatPermissions.toAuthorities() override fun isAccountNonExpired() = true override fun isAccountNonLocked() = true @@ -189,17 +186,20 @@ fun userUpdateDto( op: UserUpdateDto.() -> Unit = {} ) = UserUpdateDto(id, firstName, lastName, groupId, permissions).apply(op) -fun userOutputDto( - user: User -) = UserOutputDto( - user.id, - user.firstName, - user.lastName, - user.group, - user.flatPermissions, - user.permissions, - user.lastLoginTime -) +// ==== Extensions ==== +fun Set.toAuthorities() = + this.map { it.toAuthority() }.toMutableSet() + +fun User.toOutputDto() = + UserOutputDto( + this.id, + this.firstName, + this.lastName, + this.group, + this.flatPermissions, + this.permissions, + this.lastLoginTime + ) // ==== Exceptions ==== private const val USER_NOT_FOUND_EXCEPTION_TITLE = "User not found" diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt index 8211687..04add2b 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/UserService.kt @@ -62,7 +62,7 @@ class UserServiceImpl( override fun idNotFoundException(id: Long) = userIdNotFoundException(id) override fun idAlreadyExistsException(id: Long) = userIdAlreadyExistsException(id) - override fun User.toOutput() = userOutputDto(this) + override fun User.toOutput() = this.toOutputDto() override fun existsByFirstNameAndLastName(firstName: String, lastName: String): Boolean = repository.existsByFirstNameAndLastName(firstName, lastName) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt index c8b53b3..280e7e0 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt @@ -1,139 +1,56 @@ package dev.fyloz.colorrecipesexplorer.utils -import com.fasterxml.jackson.core.JsonParser -import com.fasterxml.jackson.core.TreeNode -import com.fasterxml.jackson.databind.DeserializationContext -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer -import com.fasterxml.jackson.databind.module.SimpleModule -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule +import com.fasterxml.jackson.module.kotlin.jacksonMapperBuilder +import com.fasterxml.jackson.module.kotlin.readValue import dev.fyloz.colorrecipesexplorer.model.account.User -import dev.fyloz.colorrecipesexplorer.model.account.userOutputDto -import io.jsonwebtoken.Claims -import io.jsonwebtoken.Jws +import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto import io.jsonwebtoken.Jwts -import io.jsonwebtoken.SignatureAlgorithm -import io.jsonwebtoken.io.DeserializationException -import io.jsonwebtoken.io.Deserializer import io.jsonwebtoken.io.Encoders -import io.jsonwebtoken.io.IOException import io.jsonwebtoken.jackson.io.JacksonDeserializer +import io.jsonwebtoken.jackson.io.JacksonSerializer import io.jsonwebtoken.security.Keys import java.util.* import javax.crypto.SecretKey +private const val userClaimName = "user" -data class Jwt( - val subject: String, - val secret: String, - val duration: Long? = null, - val signatureAlgorithm: SignatureAlgorithm = SignatureAlgorithm.HS512, - val body: B? = null -) { - val token: String by lazy { - val builder = Jwts.builder() - .signWith(keyFromSecret(secret)) - .setSubject(subject) - .claim("payload", body) +private val objectMapper = jacksonMapperBuilder() + .apply { addModule(JavaTimeModule()) } + .build() +private val serializer = JacksonSerializer>(objectMapper) +private val deserializer = JacksonDeserializer>(objectMapper) - duration?.let { - val expirationMs = System.currentTimeMillis() + it - val expirationDate = Date(expirationMs) +/** Build a JWT token for the given [User]. */ +fun User.buildJwt(secret: String, duration: Long): String { + val expirationDate = Date(System.currentTimeMillis() + duration) + val serializedUser = objectMapper.writeValueAsString(this.toOutputDto()) - builder.setExpiration(expirationDate) - } - - builder.compact() - } + return Jwts.builder() + .serializeToJsonWith(serializer) + .signWith(keyFromSecret(secret)) + .setSubject(this.id.toString()) + .setExpiration(expirationDate) + .claim(userClaimName, serializedUser) + .compact() } -enum class ClaimType(val key: String) { - GROUP_ID("groupId"), - GROUP_NAME("groupName") -} - -data class UserJwtBody( - val groupId: Long?, - val groupName: String? -) - -/** Build a [Jwt] for the given [User]. */ -fun User.buildJwt(secret: String, duration: Long?) = - Jwt( - subject = this.id.toString(), - secret, - duration, - body = userOutputDto(this) - ) - -//class JacksonDeserializer( -// val claimTypeMap: Map> -//) : Deserializer { -// val objectMapper: ObjectMapper -// -// init { -// objectMapper = jacksonObjectMapper() -// -// val module = SimpleModule() -// module.addDeserializer(Any::class.java, MappedTypeDeserializer(Collections.unmodifiableMap(claimTypeMap))) -// objectMapper.registerModule(module) -// } -// -// override fun deserialize(bytes: ByteArray?): T { -// return try { -// readValue(bytes) -// } catch (e: IOException) { -// val msg = -// "Unable to deserialize bytes into a " + returnType.getName().toString() + " instance: " + e.getMessage() -// throw DeserializationException(msg, e) -// } -// } -// -// protected fun readValue(bytes: ByteArray?): T { -// return objectMapper.readValue(bytes, returnType) -// } -//} -// -//private class MappedTypeDeserializer( -// private val claimTypeMap: Map> -//) : UntypedObjectDeserializer(null, null) { -// override fun deserialize(parser: JsonParser, context: DeserializationContext): Any { -// val name: String = parser.currentName() -// if (claimTypeMap.containsKey(name)) { -// val type = claimTypeMap[name]!! -// return parser.readValueAsTree().traverse(parser.codec).readValueAs(type) -// } -// // otherwise default to super -// return super.deserialize(parser, context) -// } -//} - -class CustomDeserializer(map: Map>) { - private val objectMapper: ObjectMapper = jacksonObjectMapper() - private val returnType: Class = Object::class.java as Class -} - -/** Parses the given [jwt] string. */ -inline fun parseJwt(jwt: String, secret: String) = +/** Parses the user of the given [jwt]. */ +fun parseJwtUser(jwt: String, secret: String): UserOutputDto = with( Jwts.parserBuilder() - .deserializeJsonWith(JacksonDeserializer(mapOf("payload" to B::class.java))) + .deserializeJsonWith(deserializer) .setSigningKey(keyFromSecret(secret)) .build() .parseClaimsJws(jwt) + .body.get(userClaimName, String::class.java) ) { - val jwt = Jwt(this.body.subject, secret) - - val payload = this.body.get("payload", B::class.java) - jwt + objectMapper.readValue(this) } /** Creates a base64 encoded [SecretKey] from the given [secret]. */ -fun keyFromSecret(secret: String) = +private fun keyFromSecret(secret: String): SecretKey = with(Encoders.BASE64.encode(secret.toByteArray())) { Keys.hmacShaKeyFor(this.toByteArray()) } - -/** Gets the claim with the given [claimType] in a [Jws]. */ -private inline fun Jws.getClaim(claimType: ClaimType) = - this.body.get(claimType.key, T::class.java) From f5355f044d0c6ae850f62e6707c8b0358bd606ac Mon Sep 17 00:00:00 2001 From: FyloZ Date: Sat, 11 Sep 2021 23:50:07 -0400 Subject: [PATCH 29/37] Update maven repository location --- build.gradle.kts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index ee0689e..574ac80 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -22,7 +22,7 @@ repositories { mavenCentral() maven { - url = uri("https://git.fyloz.dev/api/v4/projects/40/packages/maven") + url = uri("https://archiva.fyloz.dev/repository/internal") } } @@ -35,7 +35,7 @@ dependencies { implementation("io.jsonwebtoken:jjwt:0.9.1") implementation("org.apache.poi:poi-ooxml:4.1.0") implementation("org.apache.pdfbox:pdfbox:2.0.4") - implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2") + implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2.1") implementation("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}") implementation("org.springframework.boot:spring-boot-starter-jdbc:${springBootVersion}") From 1b3e5c23a701dc72ba57168de2afefc1447a331c Mon Sep 17 00:00:00 2001 From: FyloZ Date: Tue, 12 Oct 2021 21:45:21 -0400 Subject: [PATCH 30/37] Add cookie extension function to HttpServletResponse --- build.gradle.kts | 4 +- .../config/security/JwtFilters.kt | 33 ++++---- .../config/security/SecurityConfig.kt | 11 ++- .../service/users/JwtService.kt | 78 +++++++++++++++++++ .../fyloz/colorrecipesexplorer/utils/Http.kt | 55 +++++++++++++ .../fyloz/colorrecipesexplorer/utils/Jwt.kt | 56 ------------- 6 files changed, 160 insertions(+), 77 deletions(-) create mode 100644 src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt create mode 100644 src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt delete mode 100644 src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt diff --git a/build.gradle.kts b/build.gradle.kts index 7d857c0..c997a35 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -22,7 +22,7 @@ repositories { mavenCentral() maven { - url = uri("https://git.fyloz.dev/api/v4/projects/40/packages/maven") + url = uri("https://archiva.fyloz.dev/repository/internal") } } @@ -37,7 +37,7 @@ dependencies { implementation("io.jsonwebtoken:jjwt-jackson:0.11.2") implementation("org.apache.poi:poi-ooxml:4.1.0") implementation("org.apache.pdfbox:pdfbox:2.0.4") - implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2") + implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2.1") implementation("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}") implementation("org.springframework.boot:spring-boot-starter-jdbc:${springBootVersion}") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt index d4a36bf..18a9711 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt @@ -3,9 +3,12 @@ package dev.fyloz.colorrecipesexplorer.config.security import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.exception.NotFoundException -import dev.fyloz.colorrecipesexplorer.model.account.* -import dev.fyloz.colorrecipesexplorer.utils.buildJwt -import dev.fyloz.colorrecipesexplorer.utils.parseJwtUser +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails +import dev.fyloz.colorrecipesexplorer.model.account.UserLoginRequest +import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.toAuthorities +import dev.fyloz.colorrecipesexplorer.service.users.JwtService +import dev.fyloz.colorrecipesexplorer.utils.addCookie import io.jsonwebtoken.ExpiredJwtException import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken @@ -20,10 +23,11 @@ import javax.servlet.http.HttpServletResponse const val authorizationCookieName = "Authorization" const val defaultGroupCookieName = "Default-Group" -val blacklistedJwtTokens = mutableListOf() +val blacklistedJwtTokens = mutableListOf() // Not working, move to a cache or something class JwtAuthenticationFilter( private val authManager: AuthenticationManager, + private val jwtService: JwtService, private val securityProperties: CreSecurityProperties, private val updateUserLoginTime: (Long) -> Unit ) : UsernamePasswordAuthenticationFilter() { @@ -45,24 +49,23 @@ class JwtAuthenticationFilter( chain: FilterChain, auth: Authentication ) { - val userDetails = (auth.principal as UserDetails) - val token = userDetails.user.buildJwt(securityProperties.jwtSecret, securityProperties.jwtDuration) + val userDetails = auth.principal as UserDetails + val token = jwtService.buildJwt(userDetails) - var bearerCookie = - "$authorizationCookieName=Bearer$token; Max-Age=${securityProperties.jwtDuration / 1000}; HttpOnly; SameSite=strict" - if (!debugMode) bearerCookie += "; Secure;" - response.addHeader( - "Set-Cookie", - bearerCookie - ) response.addHeader(authorizationCookieName, "Bearer $token") + response.addCookie(authorizationCookieName, "Bearer$token") { + httpOnly = true + sameSite = true + secure = !debugMode + maxAge = securityProperties.jwtDuration / 1000 + } updateUserLoginTime(userDetails.user.id) } } class JwtAuthorizationFilter( - private val securityProperties: CreSecurityProperties, + private val jwtService: JwtService, authenticationManager: AuthenticationManager, private val loadUserById: (Long) -> UserDetails ) : BasicAuthenticationFilter(authenticationManager) { @@ -99,7 +102,7 @@ class JwtAuthorizationFilter( private fun getAuthentication(token: String): UsernamePasswordAuthenticationToken? { return try { - val user = parseJwtUser(token.replace("Bearer", ""), securityProperties.jwtSecret) + val user = jwtService.parseJwt(token.replace("Bearer", "")) getAuthenticationToken(user) } catch (_: ExpiredJwtException) { null diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt index 323706e..cb48092 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt @@ -4,6 +4,7 @@ import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties import dev.fyloz.colorrecipesexplorer.emergencyMode import dev.fyloz.colorrecipesexplorer.model.account.Permission import dev.fyloz.colorrecipesexplorer.model.account.User +import dev.fyloz.colorrecipesexplorer.service.users.JwtService import dev.fyloz.colorrecipesexplorer.service.users.UserDetailsService import dev.fyloz.colorrecipesexplorer.service.users.UserService import org.slf4j.Logger @@ -41,6 +42,7 @@ class SecurityConfig( private val securityProperties: CreSecurityProperties, @Lazy private val userDetailsService: UserDetailsService, @Lazy private val userService: UserService, + private val jwtService: JwtService, private val environment: Environment, private val logger: Logger ) : WebSecurityConfigurerAdapter() { @@ -86,12 +88,12 @@ class SecurityConfig( .and() .csrf().disable() .addFilter( - JwtAuthenticationFilter(authenticationManager(), securityProperties) { + JwtAuthenticationFilter(authenticationManager(), jwtService, securityProperties) { userService.updateLastLoginTime(it) } ) .addFilter( - JwtAuthorizationFilter(securityProperties, authenticationManager()) { + JwtAuthorizationFilter(jwtService, authenticationManager()) { userDetailsService.loadUserById(it, false) } ) @@ -117,6 +119,7 @@ class SecurityConfig( class EmergencySecurityConfig( private val securityProperties: CreSecurityProperties, private val userDetailsService: UserDetailsService, + private val jwtService: JwtService, private val environment: Environment ) : WebSecurityConfigurerAdapter() { init { @@ -143,10 +146,10 @@ class EmergencySecurityConfig( .and() .csrf().disable() .addFilter( - JwtAuthenticationFilter(authenticationManager(), securityProperties) { } + JwtAuthenticationFilter(authenticationManager(), jwtService, securityProperties) { } ) .addFilter( - JwtAuthorizationFilter(securityProperties, authenticationManager()) { + JwtAuthorizationFilter(jwtService, authenticationManager()) { userDetailsService.loadUserById(it, false) } ) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt new file mode 100644 index 0000000..46dcfc1 --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt @@ -0,0 +1,78 @@ +package dev.fyloz.colorrecipesexplorer.service.users + +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.module.kotlin.readValue +import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties +import dev.fyloz.colorrecipesexplorer.model.account.User +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails +import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto +import io.jsonwebtoken.Jwts +import io.jsonwebtoken.io.Encoders +import io.jsonwebtoken.jackson.io.JacksonDeserializer +import io.jsonwebtoken.jackson.io.JacksonSerializer +import io.jsonwebtoken.security.Keys +import org.springframework.stereotype.Service +import java.util.* + +const val jwtClaimUser = "user" + +interface JwtService { + /** Build a JWT token for the given [userDetails]. */ + fun buildJwt(userDetails: UserDetails): String + + /** Build a JWT token for the given [user]. */ + fun buildJwt(user: User): String + + /** Parses a user from the given [jwt] token. */ + fun parseJwt(jwt: String): UserOutputDto +} + +@Service +class JwtServiceImpl( + val objectMapper: ObjectMapper, + val securityProperties: CreSecurityProperties +) : JwtService { + private val secretKey by lazy { + with(Encoders.BASE64.encode(securityProperties.jwtSecret.toByteArray())) { + Keys.hmacShaKeyFor(this.toByteArray()) + } + } + + private val jwtBuilder by lazy { + Jwts.builder() + .serializeToJsonWith(JacksonSerializer>(objectMapper)) + .signWith(secretKey) + } + + private val jwtParser by lazy { + Jwts.parserBuilder() + .deserializeJsonWith(JacksonDeserializer>(objectMapper)) + .setSigningKey(secretKey) + .build() + } + + override fun buildJwt(userDetails: UserDetails) = + buildJwt(userDetails.user) + + override fun buildJwt(user: User): String = + jwtBuilder + .setSubject(user.id.toString()) + .setExpiration(getCurrentExpirationDate()) + .claim(jwtClaimUser, user.serialize()) + .compact() + + override fun parseJwt(jwt: String): UserOutputDto = + with( + jwtParser.parseClaimsJws(jwt) + .body.get(jwtClaimUser, String::class.java) + ) { + objectMapper.readValue(this) + } + + private fun getCurrentExpirationDate(): Date = + Date(System.currentTimeMillis() + securityProperties.jwtDuration) + + private fun User.serialize(): String = + objectMapper.writeValueAsString(this.toOutputDto()) +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt new file mode 100644 index 0000000..5eb4c2f --- /dev/null +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt @@ -0,0 +1,55 @@ +package dev.fyloz.colorrecipesexplorer.utils + +import javax.servlet.http.HttpServletResponse + +private const val defaultCookieMaxAge = 3600L +private const val defaultCookieHttpOnly = true +private const val defaultCookieSameSite = true +private const val defaultCookieSecure = true + +data class CookieOptions( + /** HTTP Only cookies cannot be access by Javascript clients. */ + var httpOnly: Boolean = defaultCookieHttpOnly, + + /** SameSite cookies are only sent in requests to their origin location. */ + var sameSite: Boolean = defaultCookieSameSite, + + /** Secure cookies are only sent in HTTPS requests. */ + var secure: Boolean = defaultCookieSecure, + + /** Cookie's maximum age in seconds. */ + var maxAge: Long = defaultCookieMaxAge +) + +private enum class CookieOption(val optionName: String) { + HTTP_ONLY("HttpOnly"), + SAME_SITE("SameSite"), + SECURE("Secure"), + MAX_AGE("Max-Age") +} + +fun HttpServletResponse.addCookie(name: String, value: String, optionsBuilder: CookieOptions.() -> Unit) { + this.addHeader("Set-Cookie", buildCookie(name, value, optionsBuilder)) +} + +private fun buildCookie(name: String, value: String, optionsBuilder: CookieOptions.() -> Unit): String { + val options = CookieOptions().apply(optionsBuilder) + val cookie = StringBuilder("$name=$value;") + + fun addBoolOption(option: CookieOption, enabled: Boolean) { + if (enabled) { + cookie.append("${option.optionName};") + } + } + + fun addOption(option: CookieOption, value: Any) { + cookie.append("${option.optionName}=$value;") + } + + addBoolOption(CookieOption.HTTP_ONLY, options.httpOnly) + addBoolOption(CookieOption.SAME_SITE, options.sameSite) + addBoolOption(CookieOption.SECURE, options.secure) + addOption(CookieOption.MAX_AGE, options.maxAge) + + return cookie.toString() +} diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt deleted file mode 100644 index 280e7e0..0000000 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Jwt.kt +++ /dev/null @@ -1,56 +0,0 @@ -package dev.fyloz.colorrecipesexplorer.utils - -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule -import com.fasterxml.jackson.module.kotlin.jacksonMapperBuilder -import com.fasterxml.jackson.module.kotlin.readValue -import dev.fyloz.colorrecipesexplorer.model.account.User -import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto -import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto -import io.jsonwebtoken.Jwts -import io.jsonwebtoken.io.Encoders -import io.jsonwebtoken.jackson.io.JacksonDeserializer -import io.jsonwebtoken.jackson.io.JacksonSerializer -import io.jsonwebtoken.security.Keys -import java.util.* -import javax.crypto.SecretKey - -private const val userClaimName = "user" - -private val objectMapper = jacksonMapperBuilder() - .apply { addModule(JavaTimeModule()) } - .build() -private val serializer = JacksonSerializer>(objectMapper) -private val deserializer = JacksonDeserializer>(objectMapper) - -/** Build a JWT token for the given [User]. */ -fun User.buildJwt(secret: String, duration: Long): String { - val expirationDate = Date(System.currentTimeMillis() + duration) - val serializedUser = objectMapper.writeValueAsString(this.toOutputDto()) - - return Jwts.builder() - .serializeToJsonWith(serializer) - .signWith(keyFromSecret(secret)) - .setSubject(this.id.toString()) - .setExpiration(expirationDate) - .claim(userClaimName, serializedUser) - .compact() -} - -/** Parses the user of the given [jwt]. */ -fun parseJwtUser(jwt: String, secret: String): UserOutputDto = - with( - Jwts.parserBuilder() - .deserializeJsonWith(deserializer) - .setSigningKey(keyFromSecret(secret)) - .build() - .parseClaimsJws(jwt) - .body.get(userClaimName, String::class.java) - ) { - objectMapper.readValue(this) - } - -/** Creates a base64 encoded [SecretKey] from the given [secret]. */ -private fun keyFromSecret(secret: String): SecretKey = - with(Encoders.BASE64.encode(secret.toByteArray())) { - Keys.hmacShaKeyFor(this.toByteArray()) - } From d873139933e94bf777ecd63044a9763cf615e2f8 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Tue, 9 Nov 2021 19:40:26 -0500 Subject: [PATCH 31/37] Add JwtService unit tests --- build.gradle.kts | 15 +- gradle/wrapper/gradle-wrapper.jar | Bin 59203 -> 59536 bytes gradle/wrapper/gradle-wrapper.properties | 2 +- gradlew | 269 +++++++++++------- .../config/security/JwtFilters.kt | 5 +- .../config/security/SecurityConfig.kt | 260 ++++++++--------- .../service/config/ConfigurationService.kt | 2 +- .../service/users/JwtService.kt | 13 +- .../colorrecipesexplorer/utils/Crypto.kt | 7 + .../fyloz/colorrecipesexplorer/utils/Http.kt | 22 +- .../fyloz/colorrecipesexplorer/utils/Time.kt | 9 + .../service/JwtServiceTest.kt | 99 +++++++ 12 files changed, 415 insertions(+), 288 deletions(-) create mode 100644 src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt diff --git a/build.gradle.kts b/build.gradle.kts index c997a35..0abe109 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -2,13 +2,13 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile group = "dev.fyloz.colorrecipesexplorer" -val kotlinVersion = "1.5.21" -val springBootVersion = "2.3.4.RELEASE" +val kotlinVersion = "1.5.31" +val springBootVersion = "2.5.6" plugins { // Outer scope variables can't be accessed in the plugins section, so we have to redefine them here - val kotlinVersion = "1.5.21" - val springBootVersion = "2.3.4.RELEASE" + val kotlinVersion = "1.5.31" + val springBootVersion = "2.5.6" id("java") id("org.jetbrains.kotlin.jvm") version kotlinVersion @@ -30,7 +30,7 @@ dependencies { implementation(platform("org.jetbrains.kotlin:kotlin-bom:${kotlinVersion}")) implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}") implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}") - implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.12.4") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.0") implementation("javax.xml.bind:jaxb-api:2.3.0") implementation("io.jsonwebtoken:jjwt-api:0.11.2") implementation("io.jsonwebtoken:jjwt-impl:0.11.2") @@ -47,11 +47,10 @@ dependencies { implementation("org.springframework.boot:spring-boot-configuration-processor:${springBootVersion}") implementation("org.springframework.boot:spring-boot-devtools:${springBootVersion}") - testImplementation("org.springframework:spring-test:5.1.6.RELEASE") + testImplementation("org.springframework:spring-test:5.3.12") testImplementation("org.mockito:mockito-inline:3.11.2") testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0") - testImplementation("org.junit.jupiter:junit-jupiter-api:5.3.2") - testImplementation("io.mockk:mockk:1.10.6") + testImplementation("io.mockk:mockk:1.12.0") testImplementation("org.springframework.boot:spring-boot-starter-test:${springBootVersion}") testImplementation("org.springframework.boot:spring-boot-test-autoconfigure:${springBootVersion}") testImplementation("org.jetbrains.kotlin:kotlin-test:${kotlinVersion}") diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c023ec8b20f512888fe07c5bd3ff77bb8f..7454180f2ae8848c63b8b4dea2cb829da983f2fa 100644 GIT binary patch delta 18435 zcmY&<19zBR)MXm8v2EM7ZQHi-#I|kQZfv7Tn#Q)%81v4zX3d)U4d4 zYYc!v@NU%|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Fp=Xhg!wPNgYzS>{Bp%%Qa+624X@ X49Luk)baa85H9$5YCsTPT`SVRWMtMW diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 69a9715..ffed3a2 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 744e882..1b6c787 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MSYS* | MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -106,80 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt index 18a9711..16523e8 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt @@ -8,6 +8,7 @@ import dev.fyloz.colorrecipesexplorer.model.account.UserLoginRequest import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto import dev.fyloz.colorrecipesexplorer.model.account.toAuthorities import dev.fyloz.colorrecipesexplorer.service.users.JwtService +import dev.fyloz.colorrecipesexplorer.service.users.UserDetailsService import dev.fyloz.colorrecipesexplorer.utils.addCookie import io.jsonwebtoken.ExpiredJwtException import org.springframework.security.authentication.AuthenticationManager @@ -67,7 +68,7 @@ class JwtAuthenticationFilter( class JwtAuthorizationFilter( private val jwtService: JwtService, authenticationManager: AuthenticationManager, - private val loadUserById: (Long) -> UserDetails + private val userDetailsService: UserDetailsService ) : BasicAuthenticationFilter(authenticationManager) { override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) { fun tryLoginFromBearer(): Boolean { @@ -113,7 +114,7 @@ class JwtAuthorizationFilter( UsernamePasswordAuthenticationToken(user.id, null, user.permissions.toAuthorities()) private fun getAuthenticationToken(userId: Long): UsernamePasswordAuthenticationToken? = try { - val userDetails = loadUserById(userId) + val userDetails = userDetailsService.loadUserById(userId) UsernamePasswordAuthenticationToken(userDetails.username, null, userDetails.authorities) } catch (_: NotFoundException) { null diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt index cb48092..7272775 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt @@ -23,135 +23,68 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.AuthenticationException import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder -import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.AuthenticationEntryPoint import org.springframework.stereotype.Component -import org.springframework.util.Assert import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.UrlBasedCorsConfigurationSource import javax.annotation.PostConstruct import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse -@Configuration -@Profile("!emergency") -@EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) -@EnableConfigurationProperties(CreSecurityProperties::class) -class SecurityConfig( - private val securityProperties: CreSecurityProperties, - @Lazy private val userDetailsService: UserDetailsService, - @Lazy private val userService: UserService, - private val jwtService: JwtService, - private val environment: Environment, - private val logger: Logger -) : WebSecurityConfigurerAdapter() { - var debugMode = false +private const val angularDevServerOrigin = "http://localhost:4200" +private const val rootUserFirstName = "Root" +private const val rootUserLastName = "User" - override fun configure(authBuilder: AuthenticationManagerBuilder) { - authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()) - } - - @Bean - fun passwordEncoder() = - getPasswordEncoder() - - @Bean - fun corsConfigurationSource() = - getCorsConfigurationSource() - - @PostConstruct - fun initWebSecurity() { - if (emergencyMode) { - logger.error("Emergency mode is enabled, system users will not be created") - return - } - - debugMode = "debug" in environment.activeProfiles - if (debugMode) logger.warn("Debug mode is enabled, security will be decreased!") - - // Create Root user - assertRootUserNotNull(securityProperties) - createSystemUser( - securityProperties.root!!, - userService, - passwordEncoder(), - "Root", - "User", - listOf(Permission.ADMIN) - ) - } - - override fun configure(http: HttpSecurity) { - http - .headers().frameOptions().disable() - .and() - .csrf().disable() - .addFilter( - JwtAuthenticationFilter(authenticationManager(), jwtService, securityProperties) { - userService.updateLastLoginTime(it) - } - ) - .addFilter( - JwtAuthorizationFilter(jwtService, authenticationManager()) { - userDetailsService.loadUserById(it, false) - } - ) - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) - - if (!debugMode) { - http - .authorizeRequests() - .anyRequest().permitAll() - } else { - http - .cors() - .and() - .authorizeRequests() - .antMatchers("**").permitAll() - } - } -} - -@Configuration -@Profile("emergency") -@EnableConfigurationProperties(CreSecurityProperties::class) -class EmergencySecurityConfig( - private val securityProperties: CreSecurityProperties, +abstract class BaseSecurityConfig( private val userDetailsService: UserDetailsService, private val jwtService: JwtService, - private val environment: Environment + private val environment: Environment, + protected val logger: Logger, + protected val securityProperties: CreSecurityProperties ) : WebSecurityConfigurerAdapter() { - init { - emergencyMode = true - } + protected val passwordEncoder = BCryptPasswordEncoder() + var debugMode = false @Bean - fun corsConfigurationSource() = - getCorsConfigurationSource() + open fun passwordEncoder() = + passwordEncoder @Bean - fun passwordEncoder() = - getPasswordEncoder() + open fun corsConfigurationSource() = + UrlBasedCorsConfigurationSource().apply { + registerCorsConfiguration("/**", CorsConfiguration().apply { + allowedOrigins = listOf(angularDevServerOrigin) + allowedMethods = listOf( + HttpMethod.GET.name, + HttpMethod.POST.name, + HttpMethod.PUT.name, + HttpMethod.DELETE.name, + HttpMethod.OPTIONS.name, + HttpMethod.HEAD.name + ) + allowCredentials = true + }.applyPermitDefaultValues()) + } override fun configure(authBuilder: AuthenticationManagerBuilder) { - authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()) + authBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder) } override fun configure(http: HttpSecurity) { - val debugMode = "debug" in environment.activeProfiles - http .headers().frameOptions().disable() .and() .csrf().disable() .addFilter( - JwtAuthenticationFilter(authenticationManager(), jwtService, securityProperties) { } + JwtAuthenticationFilter( + authenticationManager(), + jwtService, + securityProperties, + this::updateUserLoginTime + ) ) .addFilter( - JwtAuthorizationFilter(jwtService, authenticationManager()) { - userDetailsService.loadUserById(it, false) - } + JwtAuthorizationFilter(jwtService, authenticationManager(), userDetailsService) ) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() @@ -160,9 +93,83 @@ class EmergencySecurityConfig( .antMatchers("/api/login").permitAll() if (debugMode) { - http.cors() + http + .cors() } } + + @PostConstruct + fun initDebugMode() { + debugMode = "debug" in environment.activeProfiles + if (debugMode) logger.warn("Debug mode is enabled, security will be decreased!") + } + + protected open fun updateUserLoginTime(userId: Long) { + } +} + +@Configuration +@Profile("!emergency") +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableConfigurationProperties(CreSecurityProperties::class) +class SecurityConfig( + @Lazy userDetailsService: UserDetailsService, + @Lazy private val userService: UserService, + jwtService: JwtService, + environment: Environment, + logger: Logger, + securityProperties: CreSecurityProperties +) : BaseSecurityConfig(userDetailsService, jwtService, environment, logger, securityProperties) { + @PostConstruct + fun initWebSecurity() { + if (emergencyMode) { + logger.error("Emergency mode is enabled, system users will not be created") + return + } + + createRootUser() + } + + override fun updateUserLoginTime(userId: Long) { + userService.updateLastLoginTime(userId) + } + + private fun createRootUser() { + if (securityProperties.root == null) { + throw InvalidSystemUserException("root", "cre.security.root configuration is not defined") + } + + with(securityProperties.root!!) { + if (!userService.existsById(this.id)) { + userService.save( + User( + id = this.id, + firstName = rootUserFirstName, + lastName = rootUserLastName, + password = passwordEncoder.encode(this.password), + isSystemUser = true, + permissions = mutableSetOf(Permission.ADMIN) + ) + ) + } + } + } +} + +@Configuration +@Profile("emergency") +@EnableConfigurationProperties(CreSecurityProperties::class) +class EmergencySecurityConfig( + userDetailsService: UserDetailsService, + jwtService: JwtService, + environment: Environment, + logger: Logger, + securityProperties: CreSecurityProperties +) : BaseSecurityConfig(userDetailsService, jwtService, environment, logger, securityProperties) { + init { + emergencyMode = true + } } @Component @@ -174,50 +181,5 @@ class RestAuthenticationEntryPoint : AuthenticationEntryPoint { ) = response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized") } -fun createSystemUser( - credentials: CreSecurityProperties.SystemUserCredentials, - userService: UserService, - passwordEncoder: PasswordEncoder, - firstName: String, - lastName: String, - permissions: List -) { - Assert.notNull(credentials.id, "A system user has no identifier defined") - Assert.notNull(credentials.password, "A system user has no password defined") - - if (!userService.existsById(credentials.id)) { - userService.save( - User( - id = credentials.id, - firstName = firstName, - lastName = lastName, - password = passwordEncoder.encode(credentials.password), - isSystemUser = true, - permissions = permissions.toMutableSet() - ) - ) - } -} - -fun getPasswordEncoder() = - BCryptPasswordEncoder() - -fun getCorsConfigurationSource() = - UrlBasedCorsConfigurationSource().apply { - registerCorsConfiguration("/**", CorsConfiguration().apply { - allowedOrigins = listOf("http://localhost:4200") // Angular development server - allowedMethods = listOf( - HttpMethod.GET.name, - HttpMethod.POST.name, - HttpMethod.PUT.name, - HttpMethod.DELETE.name, - HttpMethod.OPTIONS.name, - HttpMethod.HEAD.name - ) - allowCredentials = true - }.applyPermitDefaultValues()) - } - -private fun assertRootUserNotNull(securityProperties: CreSecurityProperties) { - Assert.notNull(securityProperties.root, "cre.security.root should be defined") -} +private class InvalidSystemUserException(userType: String, message: String) : + RuntimeException("Invalid $userType user: $message") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt index 8e5d0c2..bbb16de 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/config/ConfigurationService.kt @@ -200,7 +200,7 @@ class ConfigurationServiceImpl( private fun getGeneratedSalt(): String { logger.warn("Sensitives configurations encryption salt was not configured, using generated salt") - logger.warn("Consider configuring the encryption salt. More details at: https://git.fyloz.dev/color-recipes-explorer/backend/-/wikis/Configuration/S%C3%A9curit%C3%A9/#sel") + logger.warn("Consider configuring the encryption salt. More details at: https://cre.fyloz.dev/docs/Configuration/S%C3%A9curit%C3%A9/#sel") var saltConfiguration = configurationSource.get(saltConfigurationType) if (saltConfiguration == null) { diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt index 46dcfc1..282d6ba 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/service/users/JwtService.kt @@ -7,12 +7,13 @@ import dev.fyloz.colorrecipesexplorer.model.account.User import dev.fyloz.colorrecipesexplorer.model.account.UserDetails import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto +import dev.fyloz.colorrecipesexplorer.utils.base64encode +import dev.fyloz.colorrecipesexplorer.utils.toDate import io.jsonwebtoken.Jwts -import io.jsonwebtoken.io.Encoders import io.jsonwebtoken.jackson.io.JacksonDeserializer import io.jsonwebtoken.jackson.io.JacksonSerializer -import io.jsonwebtoken.security.Keys import org.springframework.stereotype.Service +import java.time.Instant import java.util.* const val jwtClaimUser = "user" @@ -34,9 +35,7 @@ class JwtServiceImpl( val securityProperties: CreSecurityProperties ) : JwtService { private val secretKey by lazy { - with(Encoders.BASE64.encode(securityProperties.jwtSecret.toByteArray())) { - Keys.hmacShaKeyFor(this.toByteArray()) - } + securityProperties.jwtSecret.base64encode() } private val jwtBuilder by lazy { @@ -71,7 +70,9 @@ class JwtServiceImpl( } private fun getCurrentExpirationDate(): Date = - Date(System.currentTimeMillis() + securityProperties.jwtDuration) + Instant.now() + .plusSeconds(securityProperties.jwtDuration) + .toDate() private fun User.serialize(): String = objectMapper.writeValueAsString(this.toOutputDto()) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Crypto.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Crypto.kt index a8206e6..1c27b76 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Crypto.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Crypto.kt @@ -1,5 +1,7 @@ package dev.fyloz.colorrecipesexplorer.utils +import io.jsonwebtoken.io.Encoders +import io.jsonwebtoken.security.Keys import org.springframework.security.crypto.encrypt.Encryptors import org.springframework.security.crypto.encrypt.TextEncryptor @@ -15,3 +17,8 @@ fun String.decrypt(password: String, salt: String): String = private fun withTextEncryptor(password: String, salt: String, op: (TextEncryptor) -> String) = op(Encryptors.text(password, salt)) + +fun String.base64encode() = + with(Encoders.BASE64.encode(this.toByteArray())) { + Keys.hmacShaKeyFor(this.toByteArray()) + } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt index 5eb4c2f..b9af339 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Http.kt @@ -7,7 +7,7 @@ private const val defaultCookieHttpOnly = true private const val defaultCookieSameSite = true private const val defaultCookieSecure = true -data class CookieOptions( +data class CookieBuilderOptions( /** HTTP Only cookies cannot be access by Javascript clients. */ var httpOnly: Boolean = defaultCookieHttpOnly, @@ -21,35 +21,35 @@ data class CookieOptions( var maxAge: Long = defaultCookieMaxAge ) -private enum class CookieOption(val optionName: String) { +private enum class CookieBuilderOption(val optionName: String) { HTTP_ONLY("HttpOnly"), SAME_SITE("SameSite"), SECURE("Secure"), MAX_AGE("Max-Age") } -fun HttpServletResponse.addCookie(name: String, value: String, optionsBuilder: CookieOptions.() -> Unit) { +fun HttpServletResponse.addCookie(name: String, value: String, optionsBuilder: CookieBuilderOptions.() -> Unit) { this.addHeader("Set-Cookie", buildCookie(name, value, optionsBuilder)) } -private fun buildCookie(name: String, value: String, optionsBuilder: CookieOptions.() -> Unit): String { - val options = CookieOptions().apply(optionsBuilder) +private fun buildCookie(name: String, value: String, optionsBuilder: CookieBuilderOptions.() -> Unit): String { + val options = CookieBuilderOptions().apply(optionsBuilder) val cookie = StringBuilder("$name=$value;") - fun addBoolOption(option: CookieOption, enabled: Boolean) { + fun addBoolOption(option: CookieBuilderOption, enabled: Boolean) { if (enabled) { cookie.append("${option.optionName};") } } - fun addOption(option: CookieOption, value: Any) { + fun addOption(option: CookieBuilderOption, value: Any) { cookie.append("${option.optionName}=$value;") } - addBoolOption(CookieOption.HTTP_ONLY, options.httpOnly) - addBoolOption(CookieOption.SAME_SITE, options.sameSite) - addBoolOption(CookieOption.SECURE, options.secure) - addOption(CookieOption.MAX_AGE, options.maxAge) + addBoolOption(CookieBuilderOption.HTTP_ONLY, options.httpOnly) + addBoolOption(CookieBuilderOption.SAME_SITE, options.sameSite) + addBoolOption(CookieBuilderOption.SECURE, options.secure) + addOption(CookieBuilderOption.MAX_AGE, options.maxAge) return cookie.toString() } diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Time.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Time.kt index 9889865..272ad29 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Time.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/utils/Time.kt @@ -1,9 +1,18 @@ package dev.fyloz.colorrecipesexplorer.utils +import java.time.Instant import java.time.Period +import java.util.* fun period(days: Int = 0, months: Int = 0, years: Int = 0): Period = Period.of(days, months, years) +fun Instant.toDate(): Date = + Date.from(this) + +/** Checks if a [Instant] is around the given [other] Instant, with an allowed [offset] in seconds. */ +fun Instant.isAround(other: Instant, offset: Long = 1L) = + this.isAfter(other.minusSeconds(offset)) && this.isBefore(other.plusSeconds(offset)) + val Int.months: Period get() = period(months = this) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt new file mode 100644 index 0000000..d13f70c --- /dev/null +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt @@ -0,0 +1,99 @@ +package dev.fyloz.colorrecipesexplorer.service + +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import com.fasterxml.jackson.module.kotlin.readValue +import dev.fyloz.colorrecipesexplorer.config.properties.CreSecurityProperties +import dev.fyloz.colorrecipesexplorer.model.account.UserDetails +import dev.fyloz.colorrecipesexplorer.model.account.UserOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.toOutputDto +import dev.fyloz.colorrecipesexplorer.model.account.user +import dev.fyloz.colorrecipesexplorer.service.users.JwtServiceImpl +import dev.fyloz.colorrecipesexplorer.service.users.jwtClaimUser +import dev.fyloz.colorrecipesexplorer.utils.base64encode +import dev.fyloz.colorrecipesexplorer.utils.isAround +import io.jsonwebtoken.Jwts +import io.jsonwebtoken.jackson.io.JacksonDeserializer +import io.mockk.spyk +import org.junit.jupiter.api.Test +import java.time.Instant +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class JwtServiceTest { + private val objectMapper = jacksonObjectMapper() + private val securityProperties = CreSecurityProperties().apply { + jwtSecret = "XRRm7OflmFuCrOB2Xvmfsercih9DCKom" + jwtDuration = 1000000L + } + private val jwtParser by lazy { + Jwts.parserBuilder() + .deserializeJsonWith(JacksonDeserializer>(objectMapper)) + .setSigningKey(securityProperties.jwtSecret.base64encode()) + .build() + } + + private val jwtService = spyk(JwtServiceImpl(objectMapper, securityProperties)) + private val user = user() + private val userOutputDto = user.toOutputDto() + + private val jwt = + "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwIiwiZXhwIjoxNjM3NTA0NDYyLCJ1c2VyIjoie1wiaWRcIjowLFwiZmlyc3ROYW1lXCI6XCJmaXJzdE5hbWVcIixcImxhc3ROYW1lXCI6XCJsYXN0TmFtZVwiLFwiZ3JvdXBcIjpudWxsLFwicGVybWlzc2lvbnNcIjpbXSxcImV4cGxpY2l0UGVybWlzc2lvbnNcIjpbXSxcImxhc3RMb2dpblRpbWVcIjpudWxsfSJ9.tSU4gzkPIHldfGKwBuMg1qdQTWIA5kOzMDOBwQuj0S4" + + // buildJwt() + + private fun withParsedUserOutputDto(jwt: String, test: (UserOutputDto) -> Unit) { + val serializedUser = jwtParser.parseClaimsJws(jwt) + .body.get(jwtClaimUser, String::class.java) + + test(objectMapper.readValue(serializedUser)) + } + + @Test + fun `buildJwt(userDetails) returns jwt string with valid user`() { + val userDetails = UserDetails(user) + + val builtJwt = jwtService.buildJwt(userDetails) + + withParsedUserOutputDto(builtJwt) { parsedUser -> + assertEquals(user.toOutputDto(), parsedUser) + } + } + + @Test + fun `buildJwt() returns jwt string with valid user`() { + val builtJwt = jwtService.buildJwt(user) + + withParsedUserOutputDto(builtJwt) { parsedUser -> + assertEquals(user.toOutputDto(), parsedUser) + } + } + + @Test + fun `buildJwt() returns jwt string with valid subject`() { + val builtJwt = jwtService.buildJwt(user) + val jwtSubject = jwtParser.parseClaimsJws(builtJwt).body.subject + + assertEquals(user.id.toString(), jwtSubject) + } + + @Test + fun `buildJwt() returns jwt with valid expiration date`() { + val jwtExpectedExpirationDate = Instant.now().plusSeconds(securityProperties.jwtDuration) + + val builtJwt = jwtService.buildJwt(user) + val jwtExpiration = jwtParser.parseClaimsJws(builtJwt) + .body.expiration.toInstant() + + // Check if it's between 1 second + assertTrue { jwtExpiration.isAround(jwtExpectedExpirationDate) } + } + + // parseJwt() + + @Test + fun `parseJwt() does things`() { + val parsedUser = jwtService.parseJwt(jwt) + + assertEquals(userOutputDto, parsedUser) + } +} From 4a425ecac62d2f60cb405330eba0377776d7b368 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Mon, 15 Nov 2021 22:02:03 -0500 Subject: [PATCH 32/37] Upgrade dependencies --- build.gradle.kts | 6 +++--- .../repository/MaterialRepositoryTest.kt | 4 ++-- .../colorrecipesexplorer/repository/MixRepositoryTest.kt | 4 ++-- .../service/ConfigurationServiceTest.kt | 1 - .../fyloz/colorrecipesexplorer/service/JwtServiceTest.kt | 2 +- .../colorrecipesexplorer/service/MaterialServiceTest.kt | 1 - .../fyloz/colorrecipesexplorer/service/MixServiceTest.kt | 6 +++--- .../colorrecipesexplorer/service/RecipeStepServiceTest.kt | 5 ++++- .../colorrecipesexplorer/service/TouchUpKitServiceTest.kt | 1 - 9 files changed, 15 insertions(+), 15 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 0abe109..d0df0f4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -2,12 +2,12 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile group = "dev.fyloz.colorrecipesexplorer" -val kotlinVersion = "1.5.31" +val kotlinVersion = "1.6.0" val springBootVersion = "2.5.6" plugins { // Outer scope variables can't be accessed in the plugins section, so we have to redefine them here - val kotlinVersion = "1.5.31" + val kotlinVersion = "1.6.0" val springBootVersion = "2.5.6" id("java") @@ -47,7 +47,7 @@ dependencies { implementation("org.springframework.boot:spring-boot-configuration-processor:${springBootVersion}") implementation("org.springframework.boot:spring-boot-devtools:${springBootVersion}") - testImplementation("org.springframework:spring-test:5.3.12") + testImplementation("org.springframework:spring-test:5.3.13") testImplementation("org.mockito:mockito-inline:3.11.2") testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0") testImplementation("io.mockk:mockk:1.12.0") diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MaterialRepositoryTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MaterialRepositoryTest.kt index 7394f85..fa622f0 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MaterialRepositoryTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MaterialRepositoryTest.kt @@ -10,8 +10,8 @@ import kotlin.test.assertEquals @DataJpaTest(excludeAutoConfiguration = [LiquibaseAutoConfiguration::class]) class MaterialRepositoryTest @Autowired constructor( - private val materialRepository: MaterialRepository, - private val entityManager: TestEntityManager + private val materialRepository: MaterialRepository, + private val entityManager: TestEntityManager ) { // updateInventoryQuantityById() diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MixRepositoryTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MixRepositoryTest.kt index 2362e33..e87c425 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MixRepositoryTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/repository/MixRepositoryTest.kt @@ -10,8 +10,8 @@ import kotlin.test.assertEquals @DataJpaTest(excludeAutoConfiguration = [LiquibaseAutoConfiguration::class]) class MixRepositoryTest @Autowired constructor( - private val mixRepository: MixRepository, - private val entityManager: TestEntityManager + private val mixRepository: MixRepository, + private val entityManager: TestEntityManager ) { // updateLocationById() diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt index e49fc60..79a3a24 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/ConfigurationServiceTest.kt @@ -10,7 +10,6 @@ import io.mockk.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows -import kotlin.UnsupportedOperationException import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt index d13f70c..e957fad 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt @@ -33,9 +33,9 @@ class JwtServiceTest { } private val jwtService = spyk(JwtServiceImpl(objectMapper, securityProperties)) + private val user = user() private val userOutputDto = user.toOutputDto() - private val jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwIiwiZXhwIjoxNjM3NTA0NDYyLCJ1c2VyIjoie1wiaWRcIjowLFwiZmlyc3ROYW1lXCI6XCJmaXJzdE5hbWVcIixcImxhc3ROYW1lXCI6XCJsYXN0TmFtZVwiLFwiZ3JvdXBcIjpudWxsLFwicGVybWlzc2lvbnNcIjpbXSxcImV4cGxpY2l0UGVybWlzc2lvbnNcIjpbXSxcImxhc3RMb2dpblRpbWVcIjpudWxsfSJ9.tSU4gzkPIHldfGKwBuMg1qdQTWIA5kOzMDOBwQuj0S4" diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt index 0962323..14e730d 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MaterialServiceTest.kt @@ -4,7 +4,6 @@ import com.nhaarman.mockitokotlin2.* import dev.fyloz.colorrecipesexplorer.exception.AlreadyExistsException import dev.fyloz.colorrecipesexplorer.model.* import dev.fyloz.colorrecipesexplorer.repository.MaterialRepository -import dev.fyloz.colorrecipesexplorer.service.FileService import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MixServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MixServiceTest.kt index a9debc1..707da9f 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MixServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/MixServiceTest.kt @@ -87,9 +87,9 @@ class MixServiceTest : AbstractExternalModelServiceTest Unit + scope: MixUpdateDtoTestScope = MixUpdateDtoTestScope(), + sharedMixType: Boolean = false, + op: MixUpdateDtoTestScope.() -> Unit ) { with(scope) { doReturn(true).whenever(service).existsById(mix.id!!) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeStepServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeStepServiceTest.kt index b0f9c73..31933b0 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeStepServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/RecipeStepServiceTest.kt @@ -1,8 +1,11 @@ package dev.fyloz.colorrecipesexplorer.service import com.nhaarman.mockitokotlin2.* -import dev.fyloz.colorrecipesexplorer.model.* +import dev.fyloz.colorrecipesexplorer.model.RecipeGroupInformation +import dev.fyloz.colorrecipesexplorer.model.RecipeStep import dev.fyloz.colorrecipesexplorer.model.account.group +import dev.fyloz.colorrecipesexplorer.model.recipeGroupInformation +import dev.fyloz.colorrecipesexplorer.model.recipeStep import dev.fyloz.colorrecipesexplorer.repository.RecipeStepRepository import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt index f6b5ba2..96132b3 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/TouchUpKitServiceTest.kt @@ -4,7 +4,6 @@ import dev.fyloz.colorrecipesexplorer.config.properties.CreProperties import dev.fyloz.colorrecipesexplorer.model.ConfigurationType import dev.fyloz.colorrecipesexplorer.model.configuration import dev.fyloz.colorrecipesexplorer.repository.TouchUpKitRepository -import dev.fyloz.colorrecipesexplorer.service.* import dev.fyloz.colorrecipesexplorer.service.config.ConfigurationService import dev.fyloz.colorrecipesexplorer.utils.PdfDocument import dev.fyloz.colorrecipesexplorer.utils.toByteArrayResource From c54fcc7aef6267344d7e7c4f1375d987fd54412b Mon Sep 17 00:00:00 2001 From: FyloZ Date: Thu, 2 Dec 2021 21:30:07 -0500 Subject: [PATCH 33/37] Update JWT service test --- .../fyloz/colorrecipesexplorer/service/JwtServiceTest.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt index e957fad..8a0a241 100644 --- a/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt +++ b/src/test/kotlin/dev/fyloz/colorrecipesexplorer/service/JwtServiceTest.kt @@ -14,6 +14,7 @@ import dev.fyloz.colorrecipesexplorer.utils.isAround import io.jsonwebtoken.Jwts import io.jsonwebtoken.jackson.io.JacksonDeserializer import io.mockk.spyk +import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.time.Instant import kotlin.test.assertEquals @@ -36,8 +37,6 @@ class JwtServiceTest { private val user = user() private val userOutputDto = user.toOutputDto() - private val jwt = - "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwIiwiZXhwIjoxNjM3NTA0NDYyLCJ1c2VyIjoie1wiaWRcIjowLFwiZmlyc3ROYW1lXCI6XCJmaXJzdE5hbWVcIixcImxhc3ROYW1lXCI6XCJsYXN0TmFtZVwiLFwiZ3JvdXBcIjpudWxsLFwicGVybWlzc2lvbnNcIjpbXSxcImV4cGxpY2l0UGVybWlzc2lvbnNcIjpbXSxcImxhc3RMb2dpblRpbWVcIjpudWxsfSJ9.tSU4gzkPIHldfGKwBuMg1qdQTWIA5kOzMDOBwQuj0S4" // buildJwt() @@ -91,7 +90,8 @@ class JwtServiceTest { // parseJwt() @Test - fun `parseJwt() does things`() { + fun `parseJwt() returns expected user`() { + val jwt = jwtService.buildJwt(user) val parsedUser = jwtService.parseJwt(jwt) assertEquals(userOutputDto, parsedUser) From 3220dc39cee241ca8be41c3ab59af10d1f0bb7eb Mon Sep 17 00:00:00 2001 From: william Date: Tue, 7 Dec 2021 21:48:28 -0500 Subject: [PATCH 34/37] Fix bad security configuration --- .../fyloz/colorrecipesexplorer/config/security/JwtFilters.kt | 1 + .../colorrecipesexplorer/config/security/SecurityConfig.kt | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt index 16523e8..d5b5023 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/JwtFilters.kt @@ -53,6 +53,7 @@ class JwtAuthenticationFilter( val userDetails = auth.principal as UserDetails val token = jwtService.buildJwt(userDetails) + response.addHeader("Access-Control-Expose-Headers", authorizationCookieName) response.addHeader(authorizationCookieName, "Bearer $token") response.addCookie(authorizationCookieName, "Bearer$token") { httpOnly = true diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt index 7272775..ec68d49 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/config/security/SecurityConfig.kt @@ -89,8 +89,9 @@ abstract class BaseSecurityConfig( .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() + .antMatchers("/api/config/**").permitAll() // Allow access to logo and icon + .antMatchers("/api/login").permitAll() // Allow access to login .antMatchers("**").fullyAuthenticated() - .antMatchers("/api/login").permitAll() if (debugMode) { http From d0d35fa832135ce3dcb0272a8553cfc71d3deaed Mon Sep 17 00:00:00 2001 From: FyloZ Date: Fri, 10 Dec 2021 09:27:33 -0500 Subject: [PATCH 35/37] Update Log4j version to fix severe RCE exploit. --- build.gradle.kts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build.gradle.kts b/build.gradle.kts index d0df0f4..6fe585e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -37,6 +37,8 @@ dependencies { implementation("io.jsonwebtoken:jjwt-jackson:0.11.2") implementation("org.apache.poi:poi-ooxml:4.1.0") implementation("org.apache.pdfbox:pdfbox:2.0.4") + implementation("org.apache.logging.log4j:log4j-api:2.15.0") + implementation("org.apache.logging.log4j:log4j-to-slf4j:2.15.0") implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2.1") implementation("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}") From 8e50d520bfee71fc5e41af3b3d5cc983741bd41b Mon Sep 17 00:00:00 2001 From: FyloZ Date: Tue, 14 Dec 2021 23:40:56 -0500 Subject: [PATCH 36/37] Add current group user endpoint to allow to frontend to acknowledge the default user. --- build.gradle.kts | 4 ++-- .../rest/AccountControllers.kt | 23 +++++-------------- 2 files changed, 8 insertions(+), 19 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 6fe585e..91aa6dd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -37,8 +37,8 @@ dependencies { implementation("io.jsonwebtoken:jjwt-jackson:0.11.2") implementation("org.apache.poi:poi-ooxml:4.1.0") implementation("org.apache.pdfbox:pdfbox:2.0.4") - implementation("org.apache.logging.log4j:log4j-api:2.15.0") - implementation("org.apache.logging.log4j:log4j-to-slf4j:2.15.0") + implementation("org.apache.logging.log4j:log4j-api:2.16.0") + implementation("org.apache.logging.log4j:log4j-to-slf4j:2.16.0") implementation("dev.fyloz.colorrecipesexplorer:database-manager:5.2.1") implementation("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}") diff --git a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt index 42ab55e..6864c91 100644 --- a/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt +++ b/src/main/kotlin/dev/fyloz/colorrecipesexplorer/rest/AccountControllers.kt @@ -9,7 +9,6 @@ import org.springframework.context.annotation.Profile import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.* -import java.security.Principal import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.validation.Valid @@ -31,22 +30,6 @@ class UserController(private val userService: UserService) { fun getById(@PathVariable id: Long) = ok(userService.getByIdForOutput(id)) - @GetMapping("current") - @PreAuthorize("isFullyAuthenticated()") - fun getCurrent(loggedInUser: Principal?) = - if (loggedInUser != null) - ok( - with(userService) { - getById( - loggedInUser.name.toLong(), - ignoreDefaultGroupUsers = false, - ignoreSystemUsers = false - ).toOutput() - } - ) - else - forbidden() - @PostMapping @PreAuthorizeEditUsers fun save(@Valid @RequestBody user: UserSaveDto) = @@ -133,6 +116,12 @@ class GroupsController( getRequestDefaultGroup(request).toOutput() }) + @GetMapping("currentuser") + fun getCurrentGroupUser(request: HttpServletRequest) = + ok(with(groupService.getRequestDefaultGroup(request)) { + userService.getDefaultGroupUser(this).toOutputDto() + }) + @PostMapping @PreAuthorizeEditUsers fun save(@Valid @RequestBody group: GroupSaveDto) = From d2781b933595da07f70ef940945a9def23e353e5 Mon Sep 17 00:00:00 2001 From: FyloZ Date: Tue, 14 Dec 2021 23:44:08 -0500 Subject: [PATCH 37/37] CI/CD --- .drone.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.drone.yml b/.drone.yml index df600a7..131882b 100644 --- a/.drone.yml +++ b/.drone.yml @@ -33,6 +33,9 @@ steps: - echo -n "latest" > .tags when: branch: develop + event: + exclude: + - pull_request - name: set-docker-tags-release image: *alpine-image @@ -55,6 +58,9 @@ steps: repo: *docker-registry-repo when: branch: develop + event: + exclude: + - pull_request - name: containerize-release image: plugins/docker