|
| 1 | +package com.databricks.jdbc.auth; |
| 2 | + |
| 3 | +import com.databricks.jdbc.log.JdbcLogger; |
| 4 | +import com.databricks.jdbc.log.JdbcLoggerFactory; |
| 5 | +import com.databricks.sdk.core.DatabricksException; |
| 6 | +import com.databricks.sdk.core.oauth.Token; |
| 7 | +import com.databricks.sdk.core.oauth.TokenCache; |
| 8 | +import com.databricks.sdk.core.utils.SerDeUtils; |
| 9 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 10 | +import java.io.File; |
| 11 | +import java.nio.charset.StandardCharsets; |
| 12 | +import java.nio.file.Files; |
| 13 | +import java.nio.file.Path; |
| 14 | +import java.security.SecureRandom; |
| 15 | +import java.security.spec.KeySpec; |
| 16 | +import java.util.Base64; |
| 17 | +import java.util.Objects; |
| 18 | +import javax.crypto.Cipher; |
| 19 | +import javax.crypto.SecretKey; |
| 20 | +import javax.crypto.SecretKeyFactory; |
| 21 | +import javax.crypto.spec.IvParameterSpec; |
| 22 | +import javax.crypto.spec.PBEKeySpec; |
| 23 | +import javax.crypto.spec.SecretKeySpec; |
| 24 | + |
| 25 | +/** A TokenCache implementation that stores tokens in encrypted files. */ |
| 26 | +public class EncryptedFileTokenCache implements TokenCache { |
| 27 | + private static final JdbcLogger LOGGER = |
| 28 | + JdbcLoggerFactory.getLogger(EncryptedFileTokenCache.class); |
| 29 | + |
| 30 | + // Encryption constants |
| 31 | + private static final String ALGORITHM = "AES"; |
| 32 | + private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; |
| 33 | + private static final String SECRET_KEY_ALGORITHM = "PBKDF2WithHmacSHA256"; |
| 34 | + private static final byte[] SALT = "DatabricksJdbcTokenCache".getBytes(); |
| 35 | + private static final int ITERATION_COUNT = 65536; |
| 36 | + private static final int KEY_LENGTH = 256; |
| 37 | + private static final int IV_SIZE = 16; // 128 bits |
| 38 | + |
| 39 | + private final Path cacheFile; |
| 40 | + private final ObjectMapper mapper; |
| 41 | + private final String passphrase; |
| 42 | + |
| 43 | + /** |
| 44 | + * Constructs a new EncryptingFileTokenCache instance. |
| 45 | + * |
| 46 | + * @param cacheFilePath The path where the token cache will be stored |
| 47 | + * @param passphrase The passphrase used for encryption |
| 48 | + */ |
| 49 | + public EncryptedFileTokenCache(Path cacheFilePath, String passphrase) { |
| 50 | + Objects.requireNonNull(cacheFilePath, "cacheFilePath must be defined"); |
| 51 | + Objects.requireNonNull(passphrase, "passphrase must be defined for encrypted token cache"); |
| 52 | + |
| 53 | + this.cacheFile = cacheFilePath; |
| 54 | + this.mapper = SerDeUtils.createMapper(); |
| 55 | + this.passphrase = passphrase; |
| 56 | + } |
| 57 | + |
| 58 | + @Override |
| 59 | + public void save(Token token) throws DatabricksException { |
| 60 | + try { |
| 61 | + Files.createDirectories(cacheFile.getParent()); |
| 62 | + |
| 63 | + // Serialize token to JSON |
| 64 | + String json = mapper.writeValueAsString(token); |
| 65 | + byte[] dataToWrite = json.getBytes(StandardCharsets.UTF_8); |
| 66 | + |
| 67 | + // Encrypt data |
| 68 | + dataToWrite = encrypt(dataToWrite); |
| 69 | + |
| 70 | + Files.write(cacheFile, dataToWrite); |
| 71 | + // Set file permissions to be readable only by the owner (equivalent to 0600) |
| 72 | + File file = cacheFile.toFile(); |
| 73 | + file.setReadable(false, false); |
| 74 | + file.setReadable(true, true); |
| 75 | + file.setWritable(false, false); |
| 76 | + file.setWritable(true, true); |
| 77 | + |
| 78 | + LOGGER.debug("Successfully saved encrypted token to cache: %s", cacheFile); |
| 79 | + } catch (Exception e) { |
| 80 | + throw new DatabricksException("Failed to save token cache: " + e.getMessage(), e); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + @Override |
| 85 | + public Token load() { |
| 86 | + try { |
| 87 | + if (!Files.exists(cacheFile)) { |
| 88 | + LOGGER.debug("No token cache file found at: %s", cacheFile); |
| 89 | + return null; |
| 90 | + } |
| 91 | + |
| 92 | + byte[] fileContent = Files.readAllBytes(cacheFile); |
| 93 | + |
| 94 | + // Decrypt data |
| 95 | + byte[] decodedContent; |
| 96 | + try { |
| 97 | + decodedContent = decrypt(fileContent); |
| 98 | + } catch (Exception e) { |
| 99 | + LOGGER.debug("Failed to decrypt token cache: %s", e.getMessage()); |
| 100 | + return null; |
| 101 | + } |
| 102 | + |
| 103 | + // Deserialize token from JSON |
| 104 | + String json = new String(decodedContent, StandardCharsets.UTF_8); |
| 105 | + Token token = mapper.readValue(json, Token.class); |
| 106 | + LOGGER.debug("Successfully loaded encrypted token from cache: %s", cacheFile); |
| 107 | + return token; |
| 108 | + } catch (Exception e) { |
| 109 | + // If there's any issue loading the token, return null |
| 110 | + // to allow a fresh token to be obtained |
| 111 | + LOGGER.debug("Failed to load token from cache: %s", e.getMessage()); |
| 112 | + return null; |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Generates a secret key from the passphrase using PBKDF2 with HMAC-SHA256. |
| 118 | + * |
| 119 | + * @return A SecretKey generated from the passphrase |
| 120 | + * @throws Exception If an error occurs generating the key |
| 121 | + */ |
| 122 | + private SecretKey generateSecretKey() throws Exception { |
| 123 | + SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); |
| 124 | + KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), SALT, ITERATION_COUNT, KEY_LENGTH); |
| 125 | + return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), ALGORITHM); |
| 126 | + } |
| 127 | + |
| 128 | + /** |
| 129 | + * Encrypts the given data using AES/CBC/PKCS5Padding encryption with a key derived from the |
| 130 | + * passphrase. The IV is generated randomly and prepended to the encrypted data. |
| 131 | + * |
| 132 | + * @param data The data to encrypt |
| 133 | + * @return The encrypted data with IV prepended |
| 134 | + * @throws Exception If an error occurs during encryption |
| 135 | + */ |
| 136 | + private byte[] encrypt(byte[] data) throws Exception { |
| 137 | + Cipher cipher = Cipher.getInstance(TRANSFORMATION); |
| 138 | + |
| 139 | + // Generate a random IV |
| 140 | + SecureRandom random = new SecureRandom(); |
| 141 | + byte[] iv = new byte[IV_SIZE]; |
| 142 | + random.nextBytes(iv); |
| 143 | + IvParameterSpec ivSpec = new IvParameterSpec(iv); |
| 144 | + |
| 145 | + cipher.init(Cipher.ENCRYPT_MODE, generateSecretKey(), ivSpec); |
| 146 | + byte[] encryptedData = cipher.doFinal(data); |
| 147 | + |
| 148 | + // Combine IV and encrypted data |
| 149 | + byte[] combined = new byte[iv.length + encryptedData.length]; |
| 150 | + System.arraycopy(iv, 0, combined, 0, iv.length); |
| 151 | + System.arraycopy(encryptedData, 0, combined, iv.length, encryptedData.length); |
| 152 | + |
| 153 | + return Base64.getEncoder().encode(combined); |
| 154 | + } |
| 155 | + |
| 156 | + /** |
| 157 | + * Decrypts the given encrypted data using AES/CBC/PKCS5Padding decryption with a key derived from |
| 158 | + * the passphrase. The IV is extracted from the beginning of the encrypted data. |
| 159 | + * |
| 160 | + * @param encryptedData The encrypted data with IV prepended, Base64 encoded |
| 161 | + * @return The decrypted data |
| 162 | + * @throws Exception If an error occurs during decryption |
| 163 | + */ |
| 164 | + private byte[] decrypt(byte[] encryptedData) throws Exception { |
| 165 | + byte[] decodedData = Base64.getDecoder().decode(encryptedData); |
| 166 | + |
| 167 | + // Extract IV |
| 168 | + byte[] iv = new byte[IV_SIZE]; |
| 169 | + byte[] actualData = new byte[decodedData.length - IV_SIZE]; |
| 170 | + System.arraycopy(decodedData, 0, iv, 0, IV_SIZE); |
| 171 | + System.arraycopy(decodedData, IV_SIZE, actualData, 0, actualData.length); |
| 172 | + |
| 173 | + Cipher cipher = Cipher.getInstance(TRANSFORMATION); |
| 174 | + IvParameterSpec ivSpec = new IvParameterSpec(iv); |
| 175 | + cipher.init(Cipher.DECRYPT_MODE, generateSecretKey(), ivSpec); |
| 176 | + |
| 177 | + return cipher.doFinal(actualData); |
| 178 | + } |
| 179 | +} |
0 commit comments