FileUploadToGitService.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:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026

  Contributors:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2026
      Марат Ниязматов <mrusniyazmatov@sberbank.ru>, Sber - 2026
*/

package org.archtool.service

import kotlinx.coroutines.reactor.awaitSingle
import org.archtool.data.dto.ArchitectureSendResponse
import org.archtool.helper.BranchUpdateResult
import org.archtool.helper.ChecksumHelper
import org.archtool.helper.SeafGitClient
import org.archtool.provider.VcsProvider
import org.archtool.service.dto.UploadRequest
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.core.io.buffer.DataBufferUtils
import org.springframework.stereotype.Service
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

/**
 * Общая логика приёма ZIP-архива с архитектурой и загрузки его содержимого в ветку репозитория
 */
@Service
class FileUploadToGitService(
    private val seafGitClient: SeafGitClient,
    private val checksumHelper: ChecksumHelper,
    private val vcsProvider: VcsProvider,
) {

    suspend fun uploadArchive(request: UploadRequest): ArchitectureSendResponse {
        val repoRef = vcsProvider.parse(request.repoUrl)

        val branchName = request.branchName ?: generateBranchName(vcsProvider.tempBranchSuffix(request.repoUrl))

        log.debug(
            "Параметры загрузки архива: processId={}, repoUrl={}, sub={}, name={}, surname={}, email={}, branchName={}",
            request.processId,
            request.repoUrl,
            request.userData.sub,
            request.userData.name,
            request.userData.surname,
            request.userData.email,
            branchName
        )

        val dataBuffer = DataBufferUtils.join(request.filePart.content()).awaitSingle()
        val result = try {
            dataBuffer.asInputStream(false).use { inputStream ->
                checksumHelper.validateChecksum(
                    inputStream = inputStream,
                    expectedChecksum = request.checksum
                )
            }
            dataBuffer.readPosition(0)
            seafGitClient.createOrUpdateBranchWithChanges(
                repoRef = repoRef,
                credentials = vcsProvider.credentials(),
                defaultBranch = vcsProvider.defaultBranch(),
                branchName = branchName,
                commitMessage = request.commitMessage,
                author = request.userData.sub,
                email = request.userData.email
            ) { targetDir ->
                dataBuffer.asInputStream(false).use { inputStream ->
                    unzip(
                        inputStream = inputStream,
                        targetDir = targetDir
                    )
                }
            }
        } finally {
            DataBufferUtils.release(dataBuffer)
        }

        if (result == BranchUpdateResult.LOCK_NOT_ACQUIRED) {
            error("Не получилось взять блокировку при создании новой ветки")
        }

        // status остаётся "success" в обоих случаях: seaf-arch-loader (GasSenderScheduler)
        // сравнивает response.status с жёстко заданной константой GAS_SUCCESS_STATUS = "success" —
        // "нет изменений" для вызывающей стороны не ошибка, различие видно только в message
        return ArchitectureSendResponse(
            status = "success",
            message = if (result == BranchUpdateResult.NO_CHANGES) {
                "Архив принят, но изменений относительно текущего состояния ветки $branchName нет — коммит не создавался"
            } else {
                "Архив успешно принят, разархивирован и загружен в репозиторий ${request.repoUrl} в ветку $branchName"
            },
        )
    }

    private fun generateBranchName(repoSlug: String): String {
        val timestamp = Instant.now()
            .atZone(ZoneId.of("UTC"))
            .format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"))
        return "temp_${repoSlug}_$timestamp"
    }

    private fun unzip(inputStream: InputStream, targetDir: Path) {
        var entryCount = 0
        ZipInputStream(inputStream).use { zis ->
            var entry: ZipEntry? = zis.nextEntry
            while (entry != null) {
                log.trace(
                    "Распаковка entry #{}: '{}' (размер: {}, сжатый: {}, директория: {})",
                    ++entryCount, entry.name, entry.size, entry.compressedSize, entry.isDirectory
                )
                val entryPath = targetDir.resolve(entry.name)
                if (!entryPath.normalize().startsWith(targetDir.normalize())) {
                    log.warn("Попытка zip-slip атаки: entry '{}' выходит за пределы целевой директории", entry.name)
                    throw SecurityException("Zip entry '${entry.name}' выходит за пределы целевой директории")
                }
                if (entry.isDirectory) {
                    Files.createDirectories(entryPath)
                    log.trace("Создана директория: {}", entryPath)
                } else {
                    Files.createDirectories(entryPath.parent)
                    // REPLACE_EXISTING: файл может уже присутствовать в ветке (актуально для
                    // send-files, где повторная передача того же файла должна его обновлять, а
                    // не приводить к FileAlreadyExistsException)
                    Files.copy(zis, entryPath, StandardCopyOption.REPLACE_EXISTING)
                    log.trace("Распакован файл: {} -> {}", entry.name, entryPath)
                }
                zis.closeEntry()
                entry = zis.nextEntry
            }
        }
        log.debug("Распаковка завершена: {} entries, в директорию {}", entryCount, targetDir)
    }

    companion object {
        private val log: Logger = LoggerFactory.getLogger(FileUploadToGitService::class.java)
    }
}