SecurityConfig.kt

/*
  Copyright (C) 2026 Sber

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project

  https://dochub.info

  The use of this product or its derivatives for any purpose cannot be a secret.


  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  Maintainers:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2026

  Contributors:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2026
*/

package org.archtool.fileloader2.configuration

import com.nimbusds.jose.jwk.RSAKey
import java.nio.file.Files
import java.nio.file.Paths
import org.archtool.fileloader2.configuration.properties.SecurityProperties
import org.archtool.fileloader2.controller.filter.JwtDevFilter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.invoke
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.oauth2.jwt.JwtDecoder
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder
import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter
import org.springframework.security.web.SecurityFilterChain

/**
 * Перенесено из seaf-arch-loader, единственное изменение - сессия STATELESS.
 * Признак сервиса (X-seaf-system) ставит [org.archtool.fileloader2.controller.filter.CustomHeaderFilter] до этой цепочки,
 * поэтому он есть и в ответах 401.
 */
@Configuration
class SecurityConfig(
    private val securityProperties: SecurityProperties,
) {

    /**
     * Цепочка безопасности: каждый запрос, кроме мониторинга и документации API, должен нести действительный JWT.
     * Http-сессия не создаётся. В режиме разработки перед проверкой токена подставляется токен из настроек.
     *
     * @param http построитель цепочки Spring Security
     * @return настроенная цепочка фильтров
     */
    @Bean
    fun securityWebFilterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            csrf { disable() }
            // отличие от seaf-arch-loader: сервис аутентифицирует каждый запрос по JWT, http-сессия не нужна
            sessionManagement { sessionCreationPolicy = SessionCreationPolicy.STATELESS }
            if (securityProperties.devMode?.enabled == true) { // если devMode включен, добавляем фильтр, который подставляет заголовок с авторизацией
                val jwtDevFilter = JwtDevFilter(securityProperties = securityProperties)
                addFilterBefore<BearerTokenAuthenticationFilter>(jwtDevFilter)
            }
            authorizeHttpRequests {
                authorize("/actuator/**", permitAll)
                authorize("/v3/api-docs*/**", permitAll)
                authorize("/swagger-ui/**", permitAll)
                authorize("/swagger-ui.html", permitAll)
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                jwt {}
            }
        }
        return http.build()
    }


    /**
     * Проверка JWT: подпись проверяется публичным RSA-ключом, прочитанным из файла при старте, и срок действия токена.
     * Другие системы для проверки токена не вызываются.
     *
     * @param securityProperties настройки с путём к файлу публичного ключа в формате PEM
     * @return декодер JWT
     * @throws java.io.IOException файл ключа не найден или не читается, сервис не стартует
     */
    @Bean
    fun jwtDecoder(securityProperties: SecurityProperties): JwtDecoder {
        val publicKeyPEM = Files.readString(Paths.get(securityProperties.publicKeyLocation))
        val publicKey = RSAKey.parseFromPEMEncodedObjects(publicKeyPEM).toRSAKey().toRSAPublicKey()
        return NimbusJwtDecoder
            .withPublicKey(publicKey)
            .build()
    }
}