|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | +package org.apache.beam.sdk.util; |
| 19 | + |
| 20 | +import com.google.api.gax.rpc.AlreadyExistsException; |
| 21 | +import com.google.api.gax.rpc.NotFoundException; |
| 22 | +import com.google.cloud.kms.v1.CryptoKeyName; |
| 23 | +import com.google.cloud.kms.v1.EncryptResponse; |
| 24 | +import com.google.cloud.kms.v1.KeyManagementServiceClient; |
| 25 | +import com.google.cloud.secretmanager.v1.AccessSecretVersionResponse; |
| 26 | +import com.google.cloud.secretmanager.v1.ProjectName; |
| 27 | +import com.google.cloud.secretmanager.v1.Replication; |
| 28 | +import com.google.cloud.secretmanager.v1.SecretPayload; |
| 29 | +import com.google.cloud.secretmanager.v1.SecretManagerServiceClient; |
| 30 | +import com.google.cloud.secretmanager.v1.SecretName; |
| 31 | +import com.google.cloud.secretmanager.v1.SecretVersionName; |
| 32 | +import com.google.crypto.tink.subtle.Hkdf; |
| 33 | +import com.google.protobuf.ByteString; |
| 34 | +import java.io.IOException; |
| 35 | +import java.security.GeneralSecurityException; |
| 36 | +import java.security.SecureRandom; |
| 37 | +import java.util.Base64; |
| 38 | +import org.slf4j.Logger; |
| 39 | +import org.slf4j.LoggerFactory; |
| 40 | + |
| 41 | +/** |
| 42 | + * A {@link Secret} manager implementation that retrieves secrets from Google Cloud Secret Manager. |
| 43 | + */ |
| 44 | +public class GcpHsmGeneratedSecret implements Secret { |
| 45 | + private static final Logger LOG = LoggerFactory.getLogger(GcpHsmGeneratedSecret.class); |
| 46 | + private final String projectId; |
| 47 | + private final String locationId; |
| 48 | + private final String keyRingId; |
| 49 | + private final String keyId; |
| 50 | + private final String secretId; |
| 51 | + |
| 52 | + public GcpHsmGeneratedSecret( |
| 53 | + String projectId, String locationId, String keyRingId, String keyId, String jobName) { |
| 54 | + this.projectId = projectId; |
| 55 | + this.locationId = locationId; |
| 56 | + this.keyRingId = keyRingId; |
| 57 | + this.keyId = keyId; |
| 58 | + this.secretId = "HsmGeneratedSecret_" + jobName; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Returns the secret as a byte array. Assumes that the current active service account has |
| 63 | + * permissions to read the secret. |
| 64 | + * |
| 65 | + * @return The secret as a byte array. |
| 66 | + */ |
| 67 | + @Override |
| 68 | + public byte[] getSecretBytes() { |
| 69 | + try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { |
| 70 | + SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretId, "1"); |
| 71 | + |
| 72 | + try { |
| 73 | + AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName); |
| 74 | + return response.getPayload().getData().toByteArray(); |
| 75 | + } catch (NotFoundException e) { |
| 76 | + LOG.info( |
| 77 | + "Secret version {} not found. Creating new secret and version.", |
| 78 | + secretVersionName.toString()); |
| 79 | + } |
| 80 | + |
| 81 | + ProjectName projectName = ProjectName.of(projectId); |
| 82 | + SecretName secretName = SecretName.of(projectId, secretId); |
| 83 | + try { |
| 84 | + com.google.cloud.secretmanager.v1.Secret secret = |
| 85 | + com.google.cloud.secretmanager.v1.Secret.newBuilder() |
| 86 | + .setReplication( |
| 87 | + Replication.newBuilder() |
| 88 | + .setAutomatic(Replication.Automatic.newBuilder().build())) |
| 89 | + .build(); |
| 90 | + client.createSecret(projectName, secretId, secret); |
| 91 | + } catch (AlreadyExistsException e) { |
| 92 | + LOG.info("Secret {} already exists. Adding new version.", secretName.toString()); |
| 93 | + } |
| 94 | + |
| 95 | + byte[] newKey = generateDek(); |
| 96 | + |
| 97 | + try { |
| 98 | + // Try to access again in case another thread created it. |
| 99 | + AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName); |
| 100 | + return response.getPayload().getData().toByteArray(); |
| 101 | + } catch (NotFoundException e) { |
| 102 | + LOG.info( |
| 103 | + "Secret version {} not found after re-check. Creating new secret and version.", |
| 104 | + secretVersionName.toString()); |
| 105 | + } |
| 106 | + |
| 107 | + SecretPayload payload = SecretPayload.newBuilder().setData(ByteString.copyFrom(newKey)).build(); |
| 108 | + client.addSecretVersion(secretName, payload); |
| 109 | + AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName); |
| 110 | + return response.getPayload().getData().toByteArray(); |
| 111 | + |
| 112 | + } catch (IOException | GeneralSecurityException e) { |
| 113 | + throw new RuntimeException("Failed to retrieve or create secret bytes", e); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + private byte[] generateDek() throws IOException, GeneralSecurityException { |
| 118 | + int dekSize = 32; |
| 119 | + try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { |
| 120 | + // 1. Generate nonce_one |
| 121 | + SecureRandom random = new SecureRandom(); |
| 122 | + byte[] nonceOne = new byte[dekSize]; |
| 123 | + random.nextBytes(nonceOne); |
| 124 | + |
| 125 | + // 2. Encrypt to get nonce_two |
| 126 | + CryptoKeyName keyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId); |
| 127 | + EncryptResponse response = client.encrypt(keyName, ByteString.copyFrom(nonceOne)); |
| 128 | + byte[] nonceTwo = response.getCiphertext().toByteArray(); |
| 129 | + |
| 130 | + // 3. Generate DK |
| 131 | + byte[] dk = new byte[dekSize]; |
| 132 | + random.nextBytes(dk); |
| 133 | + |
| 134 | + // 4. Derive DEK using HKDF |
| 135 | + byte[] dek = Hkdf.computeHkdf("HmacSha256", dk, nonceTwo, new byte[0], dekSize); |
| 136 | + |
| 137 | + // 5. Base64 encode |
| 138 | + return Base64.getUrlEncoder().encode(dek); |
| 139 | + } |
| 140 | + } |
| 141 | +} |
0 commit comments