From 66b0479fbd150201574e7d6fd103ffc973c9a7a2 Mon Sep 17 00:00:00 2001 From: jsonwan Date: Fri, 28 Jul 2023 15:26:49 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=95=8F=E6=84=9F=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E5=AD=98=E5=82=A8=E6=94=AF=E6=8C=81=E5=9B=BD=E5=AF=86=20#2055?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 优化代码结构 --- .../commons/common-crypto/build.gradle | 3 + .../crypto/RSAEncryptor.java | 60 ----- .../bk/job/common}/crypto/AESCryptor.java | 8 +- .../common}/crypto/CryptoConfigService.java | 0 .../common}/crypto/CryptoScenarioEnum.java | 0 .../bk/job/common}/crypto/CryptoTypeEnum.java | 0 .../bk/job/common}/crypto/EncryptConfig.java | 0 .../bk/job/common}/crypto/Encryptor.java | 0 .../job/common}/crypto/JobCryptorNames.java | 0 .../bk/job/common/crypto/RSAEncryptor.java} | 34 ++- .../crypto/SymmetricCryptoService.java | 0 .../scenario/CipherVariableCryptoService.java | 0 .../scenario/DbPasswordCryptoService.java | 0 .../scenario/SensitiveParamCryptoService.java | 0 .../bk/job/common/crypto/util}/AESUtils.java | 212 ++++++++---------- .../bk/job/common/crypto/util/RSAUtils.java | 134 +++++++++++ .../job/common/crypto/util}/AESUtilsTest.java | 13 +- .../build.gradle} | 19 +- .../bk/job/common}/jwt/BasicJwtManager.java | 15 +- .../bk/job/common}/jwt/JwtManager.java | 2 +- .../commons/common-security/build.gradle | 1 + .../ServiceSecurityAutoConfiguration.java | 2 +- .../FeignBasicAuthRequestInterceptor.java | 2 +- .../feign/FeignSecurityConfiguration.java | 3 +- .../security/jwt/AutoUpdateJwtManager.java | 8 +- src/backend/commons/common-utils/build.gradle | 1 - .../bk/job/common/util/crypto/RSAUtils.java | 191 ---------------- .../ServiceSecurityInterceptor.java | 2 +- .../crypto/BackupFileCryptoService.java | 2 +- .../SQLScriptGseTaskStartCommand.java | 14 +- .../global/AddJwtHeaderGlobalFilter.java | 2 +- ...EncryptDbAccountPasswordMigrationTask.java | 4 +- .../service/impl/AccountServiceImpl.java | 19 +- src/backend/settings.gradle | 1 + src/backend/upgrader/build.gradle | 1 + .../UseAccountPermissionMigrationTask.java | 34 ++- 36 files changed, 303 insertions(+), 484 deletions(-) delete mode 100644 src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/RSAEncryptor.java rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/AESCryptor.java (93%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/CryptoConfigService.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/CryptoScenarioEnum.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/CryptoTypeEnum.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/EncryptConfig.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/Encryptor.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/JobCryptorNames.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common/crypto/AsymmetricEncryptor.java => com/tencent/bk/job/common/crypto/RSAEncryptor.java} (70%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/SymmetricCryptoService.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/scenario/CipherVariableCryptoService.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/scenario/DbPasswordCryptoService.java (100%) rename src/backend/commons/common-crypto/src/main/java/{com.tencent.bk.job.common => com/tencent/bk/job/common}/crypto/scenario/SensitiveParamCryptoService.java (100%) rename src/backend/commons/{common-utils/src/main/java/com/tencent/bk/job/common/util/crypto => common-crypto/src/main/java/com/tencent/bk/job/common/crypto/util}/AESUtils.java (58%) create mode 100644 src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/util/RSAUtils.java rename src/backend/commons/{common-utils/src/test/java/com/tencent/bk/job/common/util/crypto => common-crypto/src/test/java/com/tencent/bk/job/common/crypto/util}/AESUtilsTest.java (84%) rename src/backend/commons/{common/src/main/java/com/tencent/bk/job/common/exception/CryptoException.java => common-jwt/build.gradle} (83%) rename src/backend/commons/{common-utils/src/main/java/com/tencent/bk/job/common/util => common-jwt/src/main/java/com/tencent/bk/job/common}/jwt/BasicJwtManager.java (91%) rename src/backend/commons/{common-utils/src/main/java/com/tencent/bk/job/common/util => common-jwt/src/main/java/com/tencent/bk/job/common}/jwt/JwtManager.java (75%) delete mode 100644 src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/crypto/RSAUtils.java diff --git a/src/backend/commons/common-crypto/build.gradle b/src/backend/commons/common-crypto/build.gradle index 3c77209593..95a9177c70 100644 --- a/src/backend/commons/common-crypto/build.gradle +++ b/src/backend/commons/common-crypto/build.gradle @@ -24,5 +24,8 @@ dependencies { api project(':commons:common') + api project(':commons:common-utils') api 'com.tencent.bk.sdk:crypto-java-sdk' + testImplementation 'org.junit.jupiter:junit-jupiter' + testImplementation 'org.springframework.boot:spring-boot-starter-test' } diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/RSAEncryptor.java b/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/RSAEncryptor.java deleted file mode 100644 index 3ca5eb22fc..0000000000 --- a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/RSAEncryptor.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available. - * - * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. - * - * BK-JOB蓝鲸智云作业平台 is licensed under the MIT License. - * - * License for BK-JOB蓝鲸智云作业平台: - * -------------------------------------------------------------------- - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and - * to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial portions of - * the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO - * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - */ - -package com.tencent.bk.job.common.crypto; - -import com.tencent.bk.job.common.util.crypto.RSAUtils; - -import java.io.File; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.PublicKey; - -public class RSAEncryptor implements AsymmetricEncryptor { - private PublicKey publicKey; - - public RSAEncryptor(File rsaPubPermFile) throws IOException, GeneralSecurityException { - publicKey = RSAUtils.getPublicKey(rsaPubPermFile); - } - - public RSAEncryptor(String rsaPublicKeyBase64) throws IOException, GeneralSecurityException { - publicKey = RSAUtils.getPublicKey(rsaPublicKeyBase64); - } - - public String encrypt(String rawText) { - try { - return RSAUtils.encrypt(rawText, publicKey); - } catch (IOException | GeneralSecurityException e) { - return null; - } - } - - public boolean verify(String message, String signature) { - try { - return RSAUtils.verify(publicKey, message, signature); - } catch (Exception e) { - return false; - } - } -} diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/AESCryptor.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/AESCryptor.java similarity index 93% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/AESCryptor.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/AESCryptor.java index daa7436b5e..c97e0ef481 100644 --- a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/AESCryptor.java +++ b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/AESCryptor.java @@ -24,11 +24,11 @@ package com.tencent.bk.job.common.crypto; -import com.tencent.bk.job.common.exception.CryptoException; -import com.tencent.bk.job.common.util.crypto.AESUtils; +import com.tencent.bk.job.common.crypto.util.AESUtils; import com.tencent.bk.sdk.crypto.annotation.Cryptor; import com.tencent.bk.sdk.crypto.annotation.CryptorTypeEnum; import com.tencent.bk.sdk.crypto.cryptor.AbstractSymmetricCryptor; +import com.tencent.bk.sdk.crypto.exception.CryptoException; import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.MessageFormatter; @@ -92,7 +92,7 @@ public void encryptIndeed(String key, InputStream in, OutputStream out) { key.length() } ); - throw new com.tencent.bk.sdk.crypto.exception.CryptoException(msg.getMessage(), e); + throw new CryptoException(msg.getMessage(), e); } } @@ -108,7 +108,7 @@ public void decryptIndeed(String key, InputStream in, OutputStream out) { key.length() } ); - throw new com.tencent.bk.sdk.crypto.exception.CryptoException(msg.getMessage(), e); + throw new CryptoException(msg.getMessage(), e); } } } diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/CryptoConfigService.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/CryptoConfigService.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/CryptoConfigService.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/CryptoConfigService.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/CryptoScenarioEnum.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/CryptoScenarioEnum.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/CryptoScenarioEnum.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/CryptoScenarioEnum.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/CryptoTypeEnum.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/CryptoTypeEnum.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/CryptoTypeEnum.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/CryptoTypeEnum.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/EncryptConfig.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/EncryptConfig.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/EncryptConfig.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/EncryptConfig.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/Encryptor.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/Encryptor.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/Encryptor.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/Encryptor.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/JobCryptorNames.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/JobCryptorNames.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/JobCryptorNames.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/JobCryptorNames.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/AsymmetricEncryptor.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/RSAEncryptor.java similarity index 70% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/AsymmetricEncryptor.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/RSAEncryptor.java index 79b80ff1f6..a795487046 100644 --- a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/AsymmetricEncryptor.java +++ b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/RSAEncryptor.java @@ -24,17 +24,27 @@ package com.tencent.bk.job.common.crypto; -/** - * 非对称加密器 - */ -public interface AsymmetricEncryptor extends Encryptor { +import com.tencent.bk.job.common.crypto.util.RSAUtils; +import com.tencent.bk.sdk.crypto.exception.CryptoException; +import lombok.extern.slf4j.Slf4j; + +import java.security.PublicKey; + +@Slf4j +public class RSAEncryptor implements Encryptor { + + private final PublicKey publicKey; + + public RSAEncryptor(String rsaPublicKeyBase64) { + publicKey = RSAUtils.getPublicKey(rsaPublicKeyBase64); + } - /** - * 校验消息的签名是否一致 通过公钥对消息内容进行校验signature内容(由私钥加签名) - * - * @param message 原消息内容 - * @param signature 消息的签名 - * @return 是否签名一致 - */ - boolean verify(String message, String signature); + public String encrypt(String rawText) { + try { + return RSAUtils.encrypt(rawText, publicKey); + } catch (CryptoException e) { + log.error("Fail to encrypt", e); + return null; + } + } } diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/SymmetricCryptoService.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/SymmetricCryptoService.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/SymmetricCryptoService.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/SymmetricCryptoService.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/scenario/CipherVariableCryptoService.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/scenario/CipherVariableCryptoService.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/scenario/CipherVariableCryptoService.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/scenario/CipherVariableCryptoService.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/scenario/DbPasswordCryptoService.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/scenario/DbPasswordCryptoService.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/scenario/DbPasswordCryptoService.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/scenario/DbPasswordCryptoService.java diff --git a/src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/scenario/SensitiveParamCryptoService.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/scenario/SensitiveParamCryptoService.java similarity index 100% rename from src/backend/commons/common-crypto/src/main/java/com.tencent.bk.job.common/crypto/scenario/SensitiveParamCryptoService.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/scenario/SensitiveParamCryptoService.java diff --git a/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/crypto/AESUtils.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/util/AESUtils.java similarity index 58% rename from src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/crypto/AESUtils.java rename to src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/util/AESUtils.java index f9f6e13b9d..a6b98a87ef 100644 --- a/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/crypto/AESUtils.java +++ b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/util/AESUtils.java @@ -22,18 +22,17 @@ * IN THE SOFTWARE. */ -package com.tencent.bk.job.common.util.crypto; +package com.tencent.bk.job.common.crypto.util; import com.tencent.bk.job.common.util.Base64Util; +import com.tencent.bk.sdk.crypto.exception.CryptoException; import lombok.extern.slf4j.Slf4j; +import org.slf4j.helpers.MessageFormatter; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; @@ -50,36 +49,14 @@ public class AESUtils { private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; /** - * 加密数据 - * - * @param data 待加密数据 - * @param password 密钥 - * @return byte[] 加密后的数据 - */ - public static byte[] encrypt(byte[] data, String password) throws Exception { - return encrypt(data, password.getBytes(StandardCharsets.UTF_8)); - } - - /** - * 加密数据 + * 加密数据,并是使用base64编码 * * @param data 待加密数据 * @param password 密钥 * @return byte[] 加密后的数据 */ - public static byte[] encrypt(String data, String password) throws Exception { - return encrypt(data.getBytes(StandardCharsets.UTF_8), password.getBytes(StandardCharsets.UTF_8)); - } - - /** - * 加密数据 - * - * @param data 待加密数据 - * @param password 密钥 - * @return String 加密后的数据 - */ - public static String encryptToBase64EncodedCipherText(byte[] data, String password) throws Exception { - return Base64Util.encodeContentToStr(encrypt(data, password.getBytes(StandardCharsets.UTF_8))); + public static String encryptToBase64EncodedCipherText(String data, String password) throws CryptoException { + return Base64Util.encodeContentToStr(encrypt(data, password)); } /** @@ -89,41 +66,103 @@ public static String encryptToBase64EncodedCipherText(byte[] data, String passwo * @param password 密钥 * @return String 解密后的数据 */ - public static String decryptBase64EncodedDataToPlainText(String data, String password) throws Exception { + public static String decryptBase64EncodedDataToPlainText(String data, String password) throws CryptoException { return decryptToPlainText(Base64Util.decodeContentToByte(data), password); } /** - * 加密数据,并是使用base64编码 + * 加密数据 * - * @param data 待加密数据 - * @param password 密钥 + * @param data 待加密数据 + * @param key 密钥 * @return byte[] 加密后的数据 */ - public static String encryptToBase64EncodedCipherText(String data, String password) throws Exception { - return Base64Util.encodeContentToStr(encrypt(data, password)); + public static byte[] encrypt(byte[] data, byte[] key) throws CryptoException { + byte[] iv; + byte[] finalData; + try { + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(cipher, key)); + + iv = cipher.getIV(); + finalData = cipher.doFinal(data); + } catch (Exception e) { + String msg = MessageFormatter.arrayFormat( + "Fail to encrypt using {}, data.len={}, key.len={}", + new Object[]{CIPHER_ALGORITHM, data.length, key.length} + ).getMessage(); + throw new CryptoException(msg, e); + } + if (iv == null) { + throw new RuntimeException(String.format("CIPHER_ALGORITHM %s is invalid", CIPHER_ALGORITHM)); + } + byte[] finalDataWithIv = new byte[finalData.length + iv.length]; + System.arraycopy(iv, 0, finalDataWithIv, 0, iv.length); + System.arraycopy(finalData, 0, finalDataWithIv, iv.length, finalData.length); + return finalDataWithIv; } /** * 解密数据 * - * @param data 待解密数据 - * @param password 密钥 + * @param data 待解密数据 + * @param key 密钥 * @return byte[] 解密后的数据 */ - public static byte[] decrypt(byte[] data, String password) throws Exception { - return decrypt(data, password.getBytes(StandardCharsets.UTF_8)); + public static byte[] decrypt(byte[] data, byte[] key) throws CryptoException { + try { + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); + cipher.init(Cipher.DECRYPT_MODE, getKeySpec(cipher, key), getIvSpec(cipher, data)); + byte[] dataWithoutIv = new byte[data.length - cipher.getBlockSize()]; + System.arraycopy(data, cipher.getBlockSize(), dataWithoutIv, + 0, data.length - cipher.getBlockSize()); + return cipher.doFinal(dataWithoutIv); + } catch (Exception e) { + String msg = MessageFormatter.arrayFormat( + "Fail to decrypt using {}, data.len={}, key.len={}", + new Object[]{CIPHER_ALGORITHM, data.length, key.length} + ).getMessage(); + throw new CryptoException(msg, e); + } } - /** - * 解密数据 - * - * @param data 待解密数据 - * @param password 密钥 - * @return byte[] 解密后的数据 - */ - public static String decryptToPlainText(byte[] data, String password) throws Exception { - return new String(decrypt(data, password.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); + public static void encrypt(InputStream in, OutputStream out, String password) throws CryptoException { + byte[] key = password.getBytes(StandardCharsets.UTF_8); + try { + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(cipher, key)); + byte[] arr = cipher.getIV(); + if (arr == null) { + throw new RuntimeException(String.format("CIPHER_ALGORITHM %s is invalid", CIPHER_ALGORITHM)); + } + out.write(arr); + write(in, out, cipher); + } catch (Exception e) { + String msg = MessageFormatter.format( + "Fail to encrypt using {}, password.len={}", CIPHER_ALGORITHM, password.length() + ).getMessage(); + throw new CryptoException(msg, e); + } + } + + public static void decrypt(InputStream in, OutputStream out, String password) throws CryptoException { + try { + log.debug("decrypt: in.available={}", in.available()); + byte[] key = password.getBytes(StandardCharsets.UTF_8); + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); + byte[] iv = new byte[cipher.getBlockSize()]; + if (in.read(iv) < iv.length) { + throw new RuntimeException(); + } + log.debug("decrypt: iv={}", Arrays.toString(iv)); + cipher.init(Cipher.DECRYPT_MODE, getKeySpec(cipher, key), new IvParameterSpec(iv)); + write(in, out, cipher); + } catch (Exception e) { + String msg = MessageFormatter.format( + "Fail to decrypt using {}, password.len={}", CIPHER_ALGORITHM, password.length() + ).getMessage(); + throw new CryptoException(msg, e); + } } /** @@ -133,47 +172,19 @@ public static String decryptToPlainText(byte[] data, String password) throws Exc * @param password 密钥 * @return byte[] 解密后的数据 */ - public static String decryptToPlainText(String data, String password) throws Exception { - return new String(decrypt(data.getBytes(StandardCharsets.UTF_8), - password.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); + private static String decryptToPlainText(byte[] data, String password) throws CryptoException { + return new String(decrypt(data, password.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); } /** * 加密数据 * - * @param data 待加密数据 - * @param key 密钥 + * @param data 待加密数据 + * @param password 密钥 * @return byte[] 加密后的数据 */ - public static byte[] encrypt(byte[] data, byte[] key) throws Exception { - Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); - cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(cipher, key)); - - byte[] iv = cipher.getIV(); - byte[] finalData = cipher.doFinal(data); - if (iv == null) { - throw new RuntimeException(String.format("CIPHER_ALGORITHM %s is invalid", CIPHER_ALGORITHM)); - } - byte[] finalDataWithIv = new byte[finalData.length + iv.length]; - System.arraycopy(iv, 0, finalDataWithIv, 0, iv.length); - System.arraycopy(finalData, 0, finalDataWithIv, iv.length, finalData.length); - return finalDataWithIv; - } - - /** - * 解密数据 - * - * @param data 待解密数据 - * @param key 密钥 - * @return byte[] 解密后的数据 - */ - public static byte[] decrypt(byte[] data, byte[] key) throws Exception { - Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); - cipher.init(Cipher.DECRYPT_MODE, getKeySpec(cipher, key), getIvSpec(cipher, data)); - byte[] dataWithoutIv = new byte[data.length - cipher.getBlockSize()]; - System.arraycopy(data, cipher.getBlockSize(), dataWithoutIv, - 0, data.length - cipher.getBlockSize()); - return cipher.doFinal(dataWithoutIv); + private static byte[] encrypt(String data, String password) throws CryptoException { + return encrypt(data.getBytes(StandardCharsets.UTF_8), password.getBytes(StandardCharsets.UTF_8)); } private static IvParameterSpec getIvSpec(Cipher cipher, byte[] data) { @@ -191,43 +202,6 @@ private static SecretKeySpec getKeySpec(Cipher cipher, byte[] key) return new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"); } - public static void encrypt(File inFile, File outFile, String password) throws Exception { - try (FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile)) { - encrypt(in, out, password); - } - } - - public static void encrypt(InputStream in, OutputStream out, String password) throws Exception { - byte[] key = password.getBytes(StandardCharsets.UTF_8); - Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); - cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(cipher, key)); - byte[] arr = cipher.getIV(); - if (arr == null) { - throw new RuntimeException(String.format("CIPHER_ALGORITHM %s is invalid", CIPHER_ALGORITHM)); - } - out.write(arr); - write(in, out, cipher); - } - - public static void decrypt(File inFile, File outFile, String password) throws Exception { - try (FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile)) { - decrypt(in, out, password); - } - } - - public static void decrypt(InputStream in, OutputStream out, String password) throws Exception { - log.debug("decrypt: in.available={}", in.available()); - byte[] key = password.getBytes(StandardCharsets.UTF_8); - Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); - byte[] iv = new byte[cipher.getBlockSize()]; - if (in.read(iv) < iv.length) { - throw new RuntimeException(); - } - log.debug("decrypt: iv={}", Arrays.toString(iv)); - cipher.init(Cipher.DECRYPT_MODE, getKeySpec(cipher, key), new IvParameterSpec(iv)); - write(in, out, cipher); - } - private static void write(InputStream in, OutputStream out, Cipher cipher) throws Exception { byte[] iBuffer = new byte[1024]; int len; diff --git a/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/util/RSAUtils.java b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/util/RSAUtils.java new file mode 100644 index 0000000000..b89561354b --- /dev/null +++ b/src/backend/commons/common-crypto/src/main/java/com/tencent/bk/job/common/crypto/util/RSAUtils.java @@ -0,0 +1,134 @@ +/* + * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available. + * + * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. + * + * BK-JOB蓝鲸智云作业平台 is licensed under the MIT License. + * + * License for BK-JOB蓝鲸智云作业平台: + * -------------------------------------------------------------------- + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and + * to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of + * the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO + * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +package com.tencent.bk.job.common.crypto.util; + +import com.google.common.collect.Lists; +import com.tencent.bk.job.common.util.Base64Util; +import com.tencent.bk.sdk.crypto.exception.CryptoException; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.helpers.MessageFormatter; + +import javax.crypto.Cipher; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.List; + +/** + * RSAUtils 加解密 + */ +public class RSAUtils { + private static final String KEY_ALGORITHM = "RSA"; + + private static final String BEGIN_ENCRYPTED_PRIVATE_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----"; + private static final String END_ENCRYPTED_PRIVATE_KEY = "-----END ENCRYPTED PRIVATE KEY-----"; + private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----"; + private static final String END_RSA_PRIVATE_KEY = "-----END RSA PRIVATE KEY-----"; + + private static final String BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----"; + private static final String END_PRIVATE_KEY = "-----END PRIVATE KEY-----"; + private static final String BEGIN_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----"; + private static final String END_PUBLIC_KEY = "-----END PUBLIC KEY-----"; + + private static final String CHARSET_NAME = "UTF-8"; + private static final String LINE_SPLIT = "\n"; + + private static final List SKIP_STR = Lists.newArrayList( + BEGIN_PRIVATE_KEY, END_PRIVATE_KEY, BEGIN_PUBLIC_KEY, END_PUBLIC_KEY, + BEGIN_ENCRYPTED_PRIVATE_KEY, END_ENCRYPTED_PRIVATE_KEY, BEGIN_RSA_PRIVATE_KEY, END_RSA_PRIVATE_KEY + ); + + public static RSAPrivateKey getPrivateKey(String rsaPrivateKeyBase64) throws CryptoException { + try { + String privateKeyPEM = getPermKey(rsaPrivateKeyBase64); + byte[] encoded = Base64.decodeBase64(privateKeyPEM); + return (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(encoded)); + } catch (Exception e) { + String msg = MessageFormatter.arrayFormat( + "Fail to getPrivateKey using {}, rsaPrivateKeyBase64.len={}", + new Object[]{KEY_ALGORITHM, rsaPrivateKeyBase64.length()} + ).getMessage(); + throw new CryptoException(msg, e); + } + } + + public static RSAPublicKey getPublicKey(String rsaPublicKeyBase64) throws CryptoException { + try { + byte[] encoded = Base64.decodeBase64(getPermKey(rsaPublicKeyBase64)); + return (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(encoded)); + } catch (Exception e) { + String msg = MessageFormatter.arrayFormat( + "Fail to getPublicKey using {}, rsaPublicKeyBase64={}", + new Object[]{KEY_ALGORITHM, rsaPublicKeyBase64} + ).getMessage(); + throw new CryptoException(msg, e); + } + } + + public static String encrypt(String rawText, PublicKey publicKey) throws CryptoException { + try { + return encrypt(rawText.getBytes(CHARSET_NAME), publicKey); + } catch (Exception e) { + String msg = MessageFormatter.arrayFormat( + "Fail to getPublicKey using {}, rawText.len={}, publicKey={}", + new Object[]{KEY_ALGORITHM, rawText.length(), publicKey} + ).getMessage(); + throw new CryptoException(msg, e); + } + } + + private static String getPermKey(String permBase64) throws IOException { + String perm = Base64Util.decodeContentToStr(permBase64); + if (StringUtils.isEmpty(perm)) { + throw new IOException("Perm content is empty"); + } + StringBuilder strKeyPEM = new StringBuilder(2048); + try (BufferedReader br = new BufferedReader(new StringReader(perm))) { + String line; + while ((line = br.readLine()) != null) { + if (SKIP_STR.contains(line)) { + continue; + } + strKeyPEM.append(line).append(LINE_SPLIT); + } + } + return strKeyPEM.toString(); + } + + private static String encrypt(byte[] messageBytes, + PublicKey publicKey) throws GeneralSecurityException { + Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + return Base64.encodeBase64String(cipher.doFinal(messageBytes)); + } +} diff --git a/src/backend/commons/common-utils/src/test/java/com/tencent/bk/job/common/util/crypto/AESUtilsTest.java b/src/backend/commons/common-crypto/src/test/java/com/tencent/bk/job/common/crypto/util/AESUtilsTest.java similarity index 84% rename from src/backend/commons/common-utils/src/test/java/com/tencent/bk/job/common/util/crypto/AESUtilsTest.java rename to src/backend/commons/common-crypto/src/test/java/com/tencent/bk/job/common/crypto/util/AESUtilsTest.java index bcc191d214..2ae8fcb5ea 100644 --- a/src/backend/commons/common-utils/src/test/java/com/tencent/bk/job/common/util/crypto/AESUtilsTest.java +++ b/src/backend/commons/common-crypto/src/test/java/com/tencent/bk/job/common/crypto/util/AESUtilsTest.java @@ -22,27 +22,26 @@ * IN THE SOFTWARE. */ -package com.tencent.bk.job.common.util.crypto; +package com.tencent.bk.job.common.crypto.util; +import org.assertj.core.api.AssertionsForClassTypes; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; - public class AESUtilsTest { @Test - void testEncryptToBase64EncodedCipherText() throws Exception { + void testEncryptToBase64EncodedCipherText() { String text = "job"; String encryptPassword = "job#123"; String encryptedData = AESUtils.encryptToBase64EncodedCipherText(text, encryptPassword); - assertThat(encryptedData).isNotEmpty(); + AssertionsForClassTypes.assertThat(encryptedData).isNotEmpty(); } @Test - void testDecryptBase64EncodedCipherText() throws Exception { + void testDecryptBase64EncodedCipherText() { String encryptedBase64EncodedData = "GQ6kLqtMevL8z/kXGVANQ+VP5o2Bt30yzXALfZbeOoY="; String encryptPassword = "job#123"; String decodeData = AESUtils.decryptBase64EncodedDataToPlainText(encryptedBase64EncodedData, encryptPassword); - assertThat(decodeData).isEqualTo("job"); + AssertionsForClassTypes.assertThat(decodeData).isEqualTo("job"); } } diff --git a/src/backend/commons/common/src/main/java/com/tencent/bk/job/common/exception/CryptoException.java b/src/backend/commons/common-jwt/build.gradle similarity index 83% rename from src/backend/commons/common/src/main/java/com/tencent/bk/job/common/exception/CryptoException.java rename to src/backend/commons/common-jwt/build.gradle index 92e86c7811..1f45f95659 100644 --- a/src/backend/commons/common/src/main/java/com/tencent/bk/job/common/exception/CryptoException.java +++ b/src/backend/commons/common-jwt/build.gradle @@ -22,19 +22,8 @@ * IN THE SOFTWARE. */ -package com.tencent.bk.job.common.exception; - -import lombok.Getter; -import lombok.ToString; - -/** - * 加解密异常 - */ -@Getter -@ToString -public class CryptoException extends RuntimeException { - - public CryptoException(String message, Throwable cause) { - super(message, cause); - } +dependencies { + api project(':commons:common-crypto') + api 'com.google.guava:guava' + api 'io.jsonwebtoken:jjwt' } diff --git a/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/jwt/BasicJwtManager.java b/src/backend/commons/common-jwt/src/main/java/com/tencent/bk/job/common/jwt/BasicJwtManager.java similarity index 91% rename from src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/jwt/BasicJwtManager.java rename to src/backend/commons/common-jwt/src/main/java/com/tencent/bk/job/common/jwt/BasicJwtManager.java index 10ebb6b3ca..d691ec92fc 100644 --- a/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/jwt/BasicJwtManager.java +++ b/src/backend/commons/common-jwt/src/main/java/com/tencent/bk/job/common/jwt/BasicJwtManager.java @@ -22,19 +22,17 @@ * IN THE SOFTWARE. */ -package com.tencent.bk.job.common.util.jwt; +package com.tencent.bk.job.common.jwt; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; -import com.tencent.bk.job.common.util.crypto.RSAUtils; +import com.tencent.bk.job.common.crypto.util.RSAUtils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.extern.slf4j.Slf4j; -import java.io.IOException; -import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import java.time.Instant; @@ -51,17 +49,16 @@ public class BasicJwtManager implements JwtManager { private final Cache tokenCache = CacheBuilder.newBuilder() .maximumSize(9999).expireAfterWrite(5, TimeUnit.MINUTES).build(); - public BasicJwtManager(String privateKeyBase64, - String publicKeyBase64) throws IOException, GeneralSecurityException { + public BasicJwtManager(String privateKeyBase64, String publicKeyBase64) { this.privateKey = RSAUtils.getPrivateKey(privateKeyBase64); this.publicKey = RSAUtils.getPublicKey(publicKeyBase64); log.info("Init JwtManager successfully!"); } /** - * 获取JWT jwt token + * 获取 jwt token * - * @return + * @return jwt token */ @Override public String getToken() { @@ -89,7 +86,7 @@ public String generateToken() { * 验证JWT * * @param token jwt token - * @return + * @return 是否通过 */ @Override public boolean verifyJwt(String token) { diff --git a/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/jwt/JwtManager.java b/src/backend/commons/common-jwt/src/main/java/com/tencent/bk/job/common/jwt/JwtManager.java similarity index 75% rename from src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/jwt/JwtManager.java rename to src/backend/commons/common-jwt/src/main/java/com/tencent/bk/job/common/jwt/JwtManager.java index edfbf16267..3af1eacfb1 100644 --- a/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/jwt/JwtManager.java +++ b/src/backend/commons/common-jwt/src/main/java/com/tencent/bk/job/common/jwt/JwtManager.java @@ -1,4 +1,4 @@ -package com.tencent.bk.job.common.util.jwt; +package com.tencent.bk.job.common.jwt; public interface JwtManager { String getToken(); diff --git a/src/backend/commons/common-security/build.gradle b/src/backend/commons/common-security/build.gradle index e540f42654..9dd2dfe762 100644 --- a/src/backend/commons/common-security/build.gradle +++ b/src/backend/commons/common-security/build.gradle @@ -24,6 +24,7 @@ dependencies { api project(':commons:common-utils') + api project(':commons:common-jwt') implementation 'io.jsonwebtoken:jjwt' implementation 'com.google.guava:guava' implementation 'org.springframework.cloud:spring-cloud-starter-openfeign' diff --git a/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/autoconfigure/ServiceSecurityAutoConfiguration.java b/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/autoconfigure/ServiceSecurityAutoConfiguration.java index 929c828213..5792b83cfb 100644 --- a/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/autoconfigure/ServiceSecurityAutoConfiguration.java +++ b/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/autoconfigure/ServiceSecurityAutoConfiguration.java @@ -25,7 +25,7 @@ package com.tencent.bk.job.common.security.autoconfigure; import com.tencent.bk.job.common.security.jwt.AutoUpdateJwtManager; -import com.tencent.bk.job.common.util.jwt.JwtManager; +import com.tencent.bk.job.common.jwt.JwtManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; diff --git a/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/feign/FeignBasicAuthRequestInterceptor.java b/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/feign/FeignBasicAuthRequestInterceptor.java index cca93f1d90..20ce1124aa 100644 --- a/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/feign/FeignBasicAuthRequestInterceptor.java +++ b/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/feign/FeignBasicAuthRequestInterceptor.java @@ -24,7 +24,7 @@ package com.tencent.bk.job.common.security.feign; -import com.tencent.bk.job.common.util.jwt.JwtManager; +import com.tencent.bk.job.common.jwt.JwtManager; import feign.RequestInterceptor; import feign.RequestTemplate; import lombok.extern.slf4j.Slf4j; diff --git a/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/feign/FeignSecurityConfiguration.java b/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/feign/FeignSecurityConfiguration.java index d9ca0cb5df..3bcb543977 100644 --- a/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/feign/FeignSecurityConfiguration.java +++ b/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/feign/FeignSecurityConfiguration.java @@ -24,7 +24,7 @@ package com.tencent.bk.job.common.security.feign; -import com.tencent.bk.job.common.util.jwt.JwtManager; +import com.tencent.bk.job.common.jwt.JwtManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -36,7 +36,6 @@ public class FeignSecurityConfiguration { * Feign 服务认证拦截 * * @param jwtManager jwt管理 - * @return */ @Bean public FeignBasicAuthRequestInterceptor basicAuthRequestInterceptor(@Autowired JwtManager jwtManager) { diff --git a/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/jwt/AutoUpdateJwtManager.java b/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/jwt/AutoUpdateJwtManager.java index 76dc95b062..81d05b7e8d 100644 --- a/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/jwt/AutoUpdateJwtManager.java +++ b/src/backend/commons/common-security/src/main/java/com/tencent/bk/job/common/security/jwt/AutoUpdateJwtManager.java @@ -1,16 +1,12 @@ package com.tencent.bk.job.common.security.jwt; -import com.tencent.bk.job.common.util.jwt.BasicJwtManager; +import com.tencent.bk.job.common.jwt.BasicJwtManager; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; -import java.io.IOException; -import java.security.GeneralSecurityException; - @Slf4j public class AutoUpdateJwtManager extends BasicJwtManager { - public AutoUpdateJwtManager(String privateKeyBase64, String publicKeyBase64) - throws IOException, GeneralSecurityException { + public AutoUpdateJwtManager(String privateKeyBase64, String publicKeyBase64) { super(privateKeyBase64, publicKeyBase64); } diff --git a/src/backend/commons/common-utils/build.gradle b/src/backend/commons/common-utils/build.gradle index e4f8643cb9..9e99e455ec 100644 --- a/src/backend/commons/common-utils/build.gradle +++ b/src/backend/commons/common-utils/build.gradle @@ -32,7 +32,6 @@ dependencies { api 'org.apache.commons:commons-collections4' api 'commons-codec:commons-codec' api 'com.google.guava:guava' - api 'io.jsonwebtoken:jjwt' api 'org.apache.commons:commons-lang3' api 'joda-time:joda-time' compileOnly 'org.projectlombok:lombok' diff --git a/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/crypto/RSAUtils.java b/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/crypto/RSAUtils.java deleted file mode 100644 index b5944a997d..0000000000 --- a/src/backend/commons/common-utils/src/main/java/com/tencent/bk/job/common/util/crypto/RSAUtils.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available. - * - * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. - * - * BK-JOB蓝鲸智云作业平台 is licensed under the MIT License. - * - * License for BK-JOB蓝鲸智云作业平台: - * -------------------------------------------------------------------- - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and - * to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial portions of - * the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO - * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - */ - -package com.tencent.bk.job.common.util.crypto; - -import com.google.common.collect.Lists; -import com.tencent.bk.job.common.util.Base64Util; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.lang3.StringUtils; - -import javax.crypto.Cipher; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.List; - -/** - * RSAUtils 加解密 - */ -public class RSAUtils { - private static final String KEY_ALGORITHM = "RSA"; - private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; - - private static final String BEGIN_ENCRYPTED_PRIVATE_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----"; - private static final String END_ENCRYPTED_PRIVATE_KEY = "-----END ENCRYPTED PRIVATE KEY-----"; - private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----"; - private static final String END_RSA_PRIVATE_KEY = "-----END RSA PRIVATE KEY-----"; - - private static final String BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----"; - private static final String END_PRIVATE_KEY = "-----END PRIVATE KEY-----"; - private static final String BEGIN_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----"; - private static final String END_PUBLIC_KEY = "-----END PUBLIC KEY-----"; - - private static final String CHARSET_NAME = "UTF-8"; - private static final String LINE_SPLIT = "\n"; - - private static List SKIP_STR = Lists.newArrayList( - BEGIN_PRIVATE_KEY, END_PRIVATE_KEY, BEGIN_PUBLIC_KEY, END_PUBLIC_KEY, - BEGIN_ENCRYPTED_PRIVATE_KEY, END_ENCRYPTED_PRIVATE_KEY, BEGIN_RSA_PRIVATE_KEY, END_RSA_PRIVATE_KEY - ); - - private static String getPermKey(File permFile) throws IOException { - StringBuilder strKeyPEM = new StringBuilder(2048); - try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(permFile), - StandardCharsets.UTF_8))) { - String line; - while ((line = br.readLine()) != null) { - if (SKIP_STR.contains(line)) { - continue; - } - strKeyPEM.append(line).append(LINE_SPLIT); - } - } - return strKeyPEM.toString(); - } - - private static String getPermKey(String permBase64) throws IOException { - String perm = Base64Util.decodeContentToStr(permBase64); - if (StringUtils.isEmpty(perm)) { - throw new IOException("Perm content is empty"); - } - StringBuilder strKeyPEM = new StringBuilder(2048); - try (BufferedReader br = new BufferedReader(new StringReader(perm))) { - String line; - while ((line = br.readLine()) != null) { - if (SKIP_STR.contains(line)) { - continue; - } - strKeyPEM.append(line).append(LINE_SPLIT); - } - } - return strKeyPEM.toString(); - } - - - public static RSAPrivateKey getPrivateKey(File rsaPrivatePermFile) throws IOException, GeneralSecurityException { - String privateKeyPEM = getPermKey(rsaPrivatePermFile); - byte[] encoded = Base64.decodeBase64(privateKeyPEM); - return (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(encoded)); - } - - public static RSAPrivateKey getPrivateKey(String rsaPrivateKeyBase64) throws IOException, GeneralSecurityException { - String privateKeyPEM = getPermKey(rsaPrivateKeyBase64); - byte[] encoded = Base64.decodeBase64(privateKeyPEM); - return (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(encoded)); - } - - public static RSAPublicKey getPublicKey(File rsaPublicPermFile) throws IOException, GeneralSecurityException { - String publicKeyPEM = getPermKey(rsaPublicPermFile); - byte[] encoded = Base64.decodeBase64(publicKeyPEM); - return (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(encoded)); - } - - public static RSAPublicKey getPublicKey(String rsaPublicKeyBase64) throws IOException, GeneralSecurityException { - byte[] encoded = Base64.decodeBase64(getPermKey(rsaPublicKeyBase64)); - return (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(new X509EncodedKeySpec(encoded)); - } - - public static String sign(PrivateKey privateKey, - String message) throws NoSuchAlgorithmException, InvalidKeyException, - SignatureException, UnsupportedEncodingException { - Signature sign = Signature.getInstance(SIGNATURE_ALGORITHM); - sign.initSign(privateKey); - sign.update(message.getBytes(CHARSET_NAME)); - return new String(Base64.encodeBase64(sign.sign()), CHARSET_NAME); - } - - public static boolean verify(PublicKey publicKey, String message, - String signature) throws SignatureException, NoSuchAlgorithmException, - UnsupportedEncodingException, InvalidKeyException { - Signature sign = Signature.getInstance(SIGNATURE_ALGORITHM); - sign.initVerify(publicKey); - sign.update(message.getBytes(CHARSET_NAME)); - return sign.verify(Base64.decodeBase64(signature.getBytes(CHARSET_NAME))); - } - - public static String encrypt(String rawText, PublicKey publicKey) throws IOException, GeneralSecurityException { - return encrypt(rawText.getBytes(CHARSET_NAME), publicKey); - } - - public static String encrypt(byte[] messageBytes, - PublicKey publicKey) throws GeneralSecurityException { - Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); - cipher.init(Cipher.ENCRYPT_MODE, publicKey); - return Base64.encodeBase64String(cipher.doFinal(messageBytes)); - } - - public static byte[] encryptToBytes(byte[] messageBytes, - PublicKey publicKey) throws GeneralSecurityException { - Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); - cipher.init(Cipher.ENCRYPT_MODE, publicKey); - return cipher.doFinal(messageBytes); - } - - public static String decrypt(String cipherBase64Text, - PrivateKey privateKey) throws IOException, GeneralSecurityException { - return decrypt(Base64.decodeBase64(cipherBase64Text), privateKey); - } - - public static String decrypt(byte[] cipherBytes, - PrivateKey privateKey) throws IOException, GeneralSecurityException { - Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); - cipher.init(Cipher.DECRYPT_MODE, privateKey); - return new String(cipher.doFinal(cipherBytes), CHARSET_NAME); - } - - public static byte[] decryptToBytes(byte[] cipherBytes, - PrivateKey privateKey) throws IOException, GeneralSecurityException { - Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); - cipher.init(Cipher.DECRYPT_MODE, privateKey); - return cipher.doFinal(cipherBytes); - } -} diff --git a/src/backend/commons/common-web/src/main/java/com/tencent/bk/job/common/web/interceptor/ServiceSecurityInterceptor.java b/src/backend/commons/common-web/src/main/java/com/tencent/bk/job/common/web/interceptor/ServiceSecurityInterceptor.java index 9162095b2d..0d1da2ab1b 100644 --- a/src/backend/commons/common-web/src/main/java/com/tencent/bk/job/common/web/interceptor/ServiceSecurityInterceptor.java +++ b/src/backend/commons/common-web/src/main/java/com/tencent/bk/job/common/web/interceptor/ServiceSecurityInterceptor.java @@ -24,7 +24,7 @@ package com.tencent.bk.job.common.web.interceptor; -import com.tencent.bk.job.common.util.jwt.JwtManager; +import com.tencent.bk.job.common.jwt.JwtManager; import com.tencent.bk.job.common.web.exception.ServiceNoAuthException; import com.tencent.bk.job.common.web.util.ProfileUtil; import lombok.extern.slf4j.Slf4j; diff --git a/src/backend/job-backup/service-job-backup/src/main/java/com/tencent/bk/job/backup/crypto/BackupFileCryptoService.java b/src/backend/job-backup/service-job-backup/src/main/java/com/tencent/bk/job/backup/crypto/BackupFileCryptoService.java index 17088f1c6a..8d26ba699c 100644 --- a/src/backend/job-backup/service-job-backup/src/main/java/com/tencent/bk/job/backup/crypto/BackupFileCryptoService.java +++ b/src/backend/job-backup/service-job-backup/src/main/java/com/tencent/bk/job/backup/crypto/BackupFileCryptoService.java @@ -27,7 +27,7 @@ import com.tencent.bk.job.common.crypto.CryptoScenarioEnum; import com.tencent.bk.job.common.crypto.JobCryptorNames; import com.tencent.bk.job.common.crypto.SymmetricCryptoService; -import com.tencent.bk.job.common.exception.CryptoException; +import com.tencent.bk.sdk.crypto.exception.CryptoException; import com.tencent.bk.sdk.crypto.util.CryptorMetaUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; diff --git a/src/backend/job-execute/service-job-execute/src/main/java/com/tencent/bk/job/execute/engine/executor/SQLScriptGseTaskStartCommand.java b/src/backend/job-execute/service-job-execute/src/main/java/com/tencent/bk/job/execute/engine/executor/SQLScriptGseTaskStartCommand.java index 41992b79f4..38436dd568 100644 --- a/src/backend/job-execute/service-job-execute/src/main/java/com/tencent/bk/job/execute/engine/executor/SQLScriptGseTaskStartCommand.java +++ b/src/backend/job-execute/service-job-execute/src/main/java/com/tencent/bk/job/execute/engine/executor/SQLScriptGseTaskStartCommand.java @@ -25,14 +25,10 @@ package com.tencent.bk.job.execute.engine.executor; import com.google.common.collect.Maps; -import com.tencent.bk.job.common.constant.ErrorCode; -import com.tencent.bk.job.common.exception.InternalException; import com.tencent.bk.job.common.gse.GseClient; import com.tencent.bk.job.common.gse.util.ScriptRequestBuilder; import com.tencent.bk.job.common.gse.v2.model.Agent; import com.tencent.bk.job.common.gse.v2.model.ExecuteScriptRequest; -import com.tencent.bk.job.common.util.Base64Util; -import com.tencent.bk.job.common.util.crypto.AESUtils; import com.tencent.bk.job.execute.config.JobExecuteConfig; import com.tencent.bk.job.execute.engine.evict.TaskEvictPolicyExecutor; import com.tencent.bk.job.execute.engine.listener.event.TaskExecuteMQEventDispatcher; @@ -203,15 +199,7 @@ private String buildRunSqlShellParams(String sqlScriptFileName) { sb.append(" EMPTY"); } if (StringUtils.isNotBlank(stepInstance.getDbPass()) && !StringUtils.equals("null", stepInstance.getDbPass())) { - String dbPassword; - try { - dbPassword = AESUtils.decryptToPlainText(Base64Util.decodeContentToByte(stepInstance.getDbPass()), - jobExecuteConfig.getEncryptPassword()); - } catch (Exception e) { - log.error("Decrypt db password failed!", e); - throw new InternalException(ErrorCode.INTERNAL_ERROR); - } - sb.append(" ").append(dbPassword); + sb.append(" ").append(stepInstance.getDbPass()); } else { sb.append(" EMPTY"); } diff --git a/src/backend/job-gateway/src/main/java/com/tencent/bk/job/gateway/filter/global/AddJwtHeaderGlobalFilter.java b/src/backend/job-gateway/src/main/java/com/tencent/bk/job/gateway/filter/global/AddJwtHeaderGlobalFilter.java index cb7e6e0a3f..af371a33d0 100644 --- a/src/backend/job-gateway/src/main/java/com/tencent/bk/job/gateway/filter/global/AddJwtHeaderGlobalFilter.java +++ b/src/backend/job-gateway/src/main/java/com/tencent/bk/job/gateway/filter/global/AddJwtHeaderGlobalFilter.java @@ -24,7 +24,7 @@ package com.tencent.bk.job.gateway.filter.global; -import com.tencent.bk.job.common.util.jwt.JwtManager; +import com.tencent.bk.job.common.jwt.JwtManager; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.gateway.filter.GatewayFilterChain; diff --git a/src/backend/job-manage/service-job-manage/src/main/java/com/tencent/bk/job/manage/migration/EncryptDbAccountPasswordMigrationTask.java b/src/backend/job-manage/service-job-manage/src/main/java/com/tencent/bk/job/manage/migration/EncryptDbAccountPasswordMigrationTask.java index fe38a40404..dba07f1006 100644 --- a/src/backend/job-manage/service-job-manage/src/main/java/com/tencent/bk/job/manage/migration/EncryptDbAccountPasswordMigrationTask.java +++ b/src/backend/job-manage/service-job-manage/src/main/java/com/tencent/bk/job/manage/migration/EncryptDbAccountPasswordMigrationTask.java @@ -24,12 +24,12 @@ package com.tencent.bk.job.manage.migration; +import com.tencent.bk.job.common.constant.AccountCategoryEnum; import com.tencent.bk.job.common.constant.ErrorCode; +import com.tencent.bk.job.common.crypto.util.AESUtils; import com.tencent.bk.job.common.exception.InternalException; import com.tencent.bk.job.common.exception.InvalidParamException; import com.tencent.bk.job.common.model.Response; -import com.tencent.bk.job.common.util.crypto.AESUtils; -import com.tencent.bk.job.common.constant.AccountCategoryEnum; import com.tencent.bk.job.manage.config.JobManageConfig; import com.tencent.bk.job.manage.dao.AccountDAO; import com.tencent.bk.job.manage.model.dto.AccountDTO; diff --git a/src/backend/job-manage/service-job-manage/src/main/java/com/tencent/bk/job/manage/service/impl/AccountServiceImpl.java b/src/backend/job-manage/service-job-manage/src/main/java/com/tencent/bk/job/manage/service/impl/AccountServiceImpl.java index aaeecb4a5d..ab508c74a0 100644 --- a/src/backend/job-manage/service-job-manage/src/main/java/com/tencent/bk/job/manage/service/impl/AccountServiceImpl.java +++ b/src/backend/job-manage/service-job-manage/src/main/java/com/tencent/bk/job/manage/service/impl/AccountServiceImpl.java @@ -24,10 +24,10 @@ package com.tencent.bk.job.manage.service.impl; +import com.tencent.bk.job.common.constant.AccountCategoryEnum; import com.tencent.bk.job.common.constant.ErrorCode; import com.tencent.bk.job.common.crypto.Encryptor; import com.tencent.bk.job.common.exception.AlreadyExistsException; -import com.tencent.bk.job.common.exception.InternalException; import com.tencent.bk.job.common.exception.InvalidParamException; import com.tencent.bk.job.common.exception.NotFoundException; import com.tencent.bk.job.common.exception.ServiceException; @@ -40,9 +40,7 @@ import com.tencent.bk.job.common.util.check.StringCheckHelper; import com.tencent.bk.job.common.util.check.TrimChecker; import com.tencent.bk.job.common.util.check.exception.StringCheckException; -import com.tencent.bk.job.common.util.crypto.AESUtils; import com.tencent.bk.job.common.util.date.DateUtils; -import com.tencent.bk.job.common.constant.AccountCategoryEnum; import com.tencent.bk.job.manage.common.consts.account.AccountTypeEnum; import com.tencent.bk.job.manage.common.consts.globalsetting.OSTypeEnum; import com.tencent.bk.job.manage.config.JobManageConfig; @@ -109,9 +107,6 @@ public long saveAccount(AccountDTO account) throws ServiceException { , account.getDbSystemAccountId(), dbSystemAccount.getAppId()); throw new NotFoundException(ErrorCode.DB_SYSTEM_ACCOUNT_IS_INVALID); } - if (StringUtils.isNotEmpty(account.getDbPassword())) { - account.setDbPassword(encryptPassword(account.getDbPassword())); - } } if (account.getId() == null) { return accountDAO.saveAccount(account); @@ -160,22 +155,10 @@ public void updateAccount(AccountDTO account) throws ServiceException { if (StringUtils.isNotEmpty(account.getPassword())) { account.setPassword(encryptor.encrypt(account.getPassword())); } - if (account.getCategory() == AccountCategoryEnum.DB && StringUtils.isNotEmpty(account.getDbPassword())) { - account.setDbPassword(encryptPassword(account.getDbPassword())); - } log.info("Update account, account={}", account); accountDAO.updateAccount(account); } - private String encryptPassword(String text) throws ServiceException { - try { - return AESUtils.encryptToBase64EncodedCipherText(text, jobManageConfig.getEncryptPassword()); - } catch (Exception e) { - log.error("Encrypt password error", e); - throw new InternalException(ErrorCode.INTERNAL_ERROR); - } - } - @Override public void deleteAccount(Long accountId) throws ServiceException { log.info("Delete account, accountId={}", accountId); diff --git a/src/backend/settings.gradle b/src/backend/settings.gradle index ef0373e854..524842ba04 100644 --- a/src/backend/settings.gradle +++ b/src/backend/settings.gradle @@ -33,6 +33,7 @@ include 'commons:cmdb-sdk-ext' include 'commons:paas-sdk' include 'commons:gse-sdk' include 'commons:common-iam' +include 'commons:common-jwt' include 'commons:common-utils' include 'commons:common-otel' include 'commons:common-redis' diff --git a/src/backend/upgrader/build.gradle b/src/backend/upgrader/build.gradle index 99086efd57..0e9525d5ab 100644 --- a/src/backend/upgrader/build.gradle +++ b/src/backend/upgrader/build.gradle @@ -39,6 +39,7 @@ dependencies { api project(":commons:common-api") api project(":commons:common-iam") api project(":commons:common-utils") + api project(":commons:common-jwt") api project(":commons:esb-sdk") api project(":commons:cmdb-sdk-model") api project(":commons:artifactory-sdk") diff --git a/src/backend/upgrader/src/main/java/com/tencent/bk/job/upgrader/task/UseAccountPermissionMigrationTask.java b/src/backend/upgrader/src/main/java/com/tencent/bk/job/upgrader/task/UseAccountPermissionMigrationTask.java index 049f905a9b..d432e3c8c4 100644 --- a/src/backend/upgrader/src/main/java/com/tencent/bk/job/upgrader/task/UseAccountPermissionMigrationTask.java +++ b/src/backend/upgrader/src/main/java/com/tencent/bk/job/upgrader/task/UseAccountPermissionMigrationTask.java @@ -35,10 +35,10 @@ import com.tencent.bk.job.common.iam.dto.EsbIamPathItem; import com.tencent.bk.job.common.iam.dto.EsbIamSubject; import com.tencent.bk.job.common.iam.util.BusinessAuthHelper; +import com.tencent.bk.job.common.jwt.BasicJwtManager; +import com.tencent.bk.job.common.jwt.JwtManager; import com.tencent.bk.job.common.model.dto.AppResourceScope; import com.tencent.bk.job.common.util.json.JsonUtils; -import com.tencent.bk.job.common.util.jwt.BasicJwtManager; -import com.tencent.bk.job.common.util.jwt.JwtManager; import com.tencent.bk.job.upgrader.anotation.ExecuteTimeEnum; import com.tencent.bk.job.upgrader.anotation.RequireTaskParam; import com.tencent.bk.job.upgrader.anotation.UpgradeTask; @@ -55,8 +55,6 @@ import lombok.extern.slf4j.Slf4j; import org.slf4j.helpers.MessageFormatter; -import java.io.IOException; -import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -108,10 +106,10 @@ public void init() { (String) getProperties().get(ParamNameConsts.CONFIG_PROPERTY_JOB_SECURITY_PUBLIC_KEY_BASE64); String securityPrivateKeyBase64 = (String) getProperties().get(ParamNameConsts.CONFIG_PROPERTY_JOB_SECURITY_PRIVATE_KEY_BASE64); - JwtManager jwtManager = null; + JwtManager jwtManager; try { jwtManager = new BasicJwtManager(securityPrivateKeyBase64, securityPublicKeyBase64); - } catch (IOException | GeneralSecurityException e) { + } catch (Exception e) { String msg = "Fail to generate jwt auth token"; log.error(msg, e); throw new InternalException(msg, e, ErrorCode.INTERNAL_ERROR); @@ -123,9 +121,7 @@ public void init() { ); this.basicAppInfoList = getAllNormalAppInfoFromManage(); appInfoMap = new HashMap<>(); - basicAppInfoList.forEach(basicAppInfo -> { - appInfoMap.put(basicAppInfo.getAppId(), basicAppInfo.getName()); - }); + basicAppInfoList.forEach(basicAppInfo -> appInfoMap.put(basicAppInfo.getAppId(), basicAppInfo.getName())); } private IamClient getIamClient() { @@ -170,8 +166,8 @@ private List getAllNormalAppInfoFromManage() { /** * 根据策略计算出有权限的业务Id列表 * - * @param policy - * @return + * @param policy 策略 + * @return 有权限的业务ID列表 */ private List getAuthorizedAppIdList(Policy policy) { BusinessAuthHelper businessAuthHelper = jobIamHelper.businessAuthHelper(); @@ -186,8 +182,8 @@ private List getAuthorizedAppIdList(Policy policy) { /** * 根据业务ID获取业务名称 * - * @param appId - * @return + * @param appId 业务ID + * @return 业务名称 */ private String getAppNameById(Long appId) { if (appInfoMap.containsKey(appId)) return appInfoMap.get(appId); @@ -300,11 +296,10 @@ public void printSeparateLine() { } public void showPolicies(List policies) { - policies.forEach(policy -> { + policies.forEach(policy -> log.info("{}: {} expiredAt {}, expression:{}", policy.getId(), policy.getSubject().getType() + ":" + policy.getSubject().getName(), - policy.getExpiredAt(), JsonUtils.toJson(policy.getExpression())); - }); + policy.getExpiredAt(), JsonUtils.toJson(policy.getExpression()))); } @Override @@ -319,14 +314,15 @@ public boolean execute(String[] args) { printSeparateLine(); log.info("Begin to auth according to oldPolicies:"); // 2.新权限数据授权 - oldAuthorizedPolicies.forEach(policy -> { + oldAuthorizedPolicies.forEach(policy -> log.info( "auth {}:{}:{}:{}", policy.getSubject().getType(), policy.getSubject().getName(), policy.getExpiredAt(), - authByPolicy(policy)); - }); + authByPolicy(policy) + ) + ); // 3.新权限策略查询 String newActionId = ActionId.USE_ACCOUNT; List newAuthorizedPolicies = queryAuthorizedPolicies(newActionId);