-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathVaultClient.java
More file actions
428 lines (362 loc) · 17.7 KB
/
VaultClient.java
File metadata and controls
428 lines (362 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package com.skyflow;
import com.skyflow.config.Credentials;
import com.skyflow.config.VaultConfig;
import com.skyflow.enums.DetectEntities;
import com.skyflow.errors.ErrorCode;
import com.skyflow.errors.ErrorMessage;
import com.skyflow.errors.SkyflowException;
import com.skyflow.generated.rest.ApiClient;
import com.skyflow.generated.rest.ApiClientBuilder;
import com.skyflow.generated.rest.resources.query.QueryClient;
import com.skyflow.generated.rest.resources.records.RecordsClient;
import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody;
import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody;
import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody;
import com.skyflow.generated.rest.resources.strings.StringsClient;
import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest;
import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest;
import com.skyflow.generated.rest.resources.strings.types.ReidentifyStringRequestFormat;
import com.skyflow.generated.rest.resources.tokens.TokensClient;
import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload;
import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload;
import com.skyflow.generated.rest.types.*;
import com.skyflow.generated.rest.types.Transformations;
import com.skyflow.logs.InfoLogs;
import com.skyflow.serviceaccount.util.Token;
import com.skyflow.utils.Constants;
import com.skyflow.utils.Utils;
import com.skyflow.utils.logger.LogUtil;
import com.skyflow.utils.validations.Validations;
import com.skyflow.vault.data.InsertRequest;
import com.skyflow.vault.data.UpdateRequest;
import com.skyflow.vault.detect.*;
import com.skyflow.vault.tokens.ColumnValue;
import com.skyflow.vault.tokens.DetokenizeData;
import com.skyflow.vault.tokens.DetokenizeRequest;
import com.skyflow.vault.tokens.TokenizeRequest;
import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvException;
import java.util.*;
import java.util.stream.Collectors;
public class VaultClient {
private final VaultConfig vaultConfig;
private final ApiClientBuilder apiClientBuilder;
private ApiClient apiClient;
private Credentials commonCredentials;
private Credentials finalCredentials;
private String token;
private String apiKey;
protected VaultClient(VaultConfig vaultConfig, Credentials credentials) {
super();
this.vaultConfig = vaultConfig;
this.commonCredentials = credentials;
this.apiClientBuilder = new ApiClientBuilder();
this.apiClient = null;
updateVaultURL();
}
protected RecordsClient getRecordsApi() {
return this.apiClient.records();
}
protected TokensClient getTokensApi() {
return this.apiClient.tokens();
}
protected StringsClient getDetectTextApi() {
return this.apiClient.strings();
}
protected QueryClient getQueryApi() {
return this.apiClient.query();
}
protected VaultConfig getVaultConfig() {
return vaultConfig;
}
protected void setCommonCredentials(Credentials commonCredentials) throws SkyflowException {
this.commonCredentials = commonCredentials;
prioritiseCredentials();
}
protected void updateVaultConfig() throws SkyflowException {
updateVaultURL();
prioritiseCredentials();
}
protected V1DetokenizePayload getDetokenizePayload(DetokenizeRequest request) {
List<V1DetokenizeRecordRequest> recordRequests = new ArrayList<>();
for (DetokenizeData detokenizeDataRecord : request.getDetokenizeData()) {
V1DetokenizeRecordRequest recordRequest = V1DetokenizeRecordRequest.builder()
.token(detokenizeDataRecord.getToken())
.redaction(detokenizeDataRecord.getRedactionType().getRedaction())
.build();
recordRequests.add(recordRequest);
}
return V1DetokenizePayload.builder()
.continueOnError(request.getContinueOnError())
.downloadUrl(request.getDownloadURL())
.detokenizationParameters(recordRequests)
.build();
}
protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest request) {
List<HashMap<String, Object>> values = request.getValues();
List<HashMap<String, Object>> tokens = request.getTokens();
List<V1FieldRecords> records = new ArrayList<>();
for (int index = 0; index < values.size(); index++) {
V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder().fields(values.get(index));
if (tokens != null && index < tokens.size()) {
recordBuilder.tokens(tokens.get(index));
}
records.add(recordBuilder.build());
}
return RecordServiceInsertRecordBody.builder()
.tokenization(request.getReturnTokens())
.homogeneous(request.getHomogeneous())
.upsert(request.getUpsert())
.byot(request.getTokenMode().getBYOT())
.records(records)
.build();
}
protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertRequest request) {
ArrayList<HashMap<String, Object>> values = request.getValues();
ArrayList<HashMap<String, Object>> tokens = request.getTokens();
List<V1BatchRecord> records = new ArrayList<>();
for (int index = 0; index < values.size(); index++) {
V1BatchRecord.Builder recordBuilder = V1BatchRecord.builder()
.method(BatchRecordMethod.POST)
.tableName(request.getTable())
.upsert(request.getUpsert())
.tokenization(request.getReturnTokens())
.fields(values.get(index));
if (tokens != null && index < tokens.size()) {
recordBuilder.tokens(tokens.get(index));
}
records.add(recordBuilder.build());
}
return RecordServiceBatchOperationBody.builder()
.continueOnError(true)
.byot(request.getTokenMode().getBYOT())
.records(records)
.build();
}
protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest request) {
RecordServiceUpdateRecordBody.Builder updateRequestBodyBuilder = RecordServiceUpdateRecordBody.builder();
updateRequestBodyBuilder.byot(request.getTokenMode().getBYOT());
updateRequestBodyBuilder.tokenization(request.getReturnTokens());
V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder();
HashMap<String, Object> values = request.getData();
if (values != null) {
recordBuilder.fields(values);
}
HashMap<String, Object> tokens = request.getTokens();
if (tokens != null) {
recordBuilder.tokens(tokens);
}
updateRequestBodyBuilder.record(recordBuilder.build());
return updateRequestBodyBuilder.build();
}
protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) {
List<V1TokenizeRecordRequest> tokenizationParameters = new ArrayList<>();
for (ColumnValue columnValue : request.getColumnValues()) {
V1TokenizeRecordRequest.Builder recordBuilder = V1TokenizeRecordRequest.builder();
String value = columnValue.getValue();
if (value != null) {
recordBuilder.value(value);
}
String columnGroup = columnValue.getColumnGroup();
if (columnGroup != null) {
recordBuilder.columnGroup(columnGroup);
}
tokenizationParameters.add(recordBuilder.build());
}
V1TokenizePayload.Builder payloadBuilder = V1TokenizePayload.builder();
if (!tokenizationParameters.isEmpty()) {
payloadBuilder.tokenizationParameters(tokenizationParameters);
}
return payloadBuilder.build();
}
protected void setBearerToken() throws SkyflowException {
prioritiseCredentials();
Validations.validateCredentials(this.finalCredentials);
if (this.finalCredentials.getApiKey() != null) {
setApiKey();
return;
} else if (Token.isExpired(token)) {
LogUtil.printInfoLog(InfoLogs.BEARER_TOKEN_EXPIRED.getLog());
token = Utils.generateBearerToken(this.finalCredentials);
} else {
LogUtil.printInfoLog(InfoLogs.REUSE_BEARER_TOKEN.getLog());
}
this.apiClientBuilder.token(token);
this.apiClient = this.apiClientBuilder.build();
}
protected DeidentifyTextResponse getDeIdentifyTextResponse(DeidentifyStringResponse deidentifyStringResponse) {
List<EntityInfo> entities = deidentifyStringResponse.getEntities() != null
? deidentifyStringResponse.getEntities().stream()
.map(this::convertDetectedEntityToEntityInfo)
.collect(Collectors.toList())
: null;
return new DeidentifyTextResponse(
deidentifyStringResponse.getProcessedText(),
entities,
deidentifyStringResponse.getWordCount(),
deidentifyStringResponse.getCharacterCount()
);
}
protected DeidentifyStringRequest getDeidentifyStringRequest(DeidentifyTextRequest deIdentifyTextRequest, String vaultId) throws SkyflowException {
List<DetectEntities> entities = deIdentifyTextRequest.getEntities();
List<EntityType> mappedEntityTypes = null;
if (entities != null) {
mappedEntityTypes = deIdentifyTextRequest.getEntities().stream()
.map(detectEntity -> EntityType.valueOf(detectEntity.name()))
.collect(Collectors.toList());
}
TokenFormat tokenFormat = deIdentifyTextRequest.getTokenFormat();
Optional<List<EntityType>> vaultToken = Optional.empty();
Optional<List<EntityType>> entityTypes = Optional.empty();
Optional<List<EntityType>> entityUniqueCounter = Optional.empty();
Optional<List<String>> allowRegex = Optional.ofNullable(deIdentifyTextRequest.getAllowRegexList());
Optional<List<String>> restrictRegex = Optional.ofNullable(deIdentifyTextRequest.getRestrictRegexList());
Optional<Transformations> transformations = Optional.ofNullable(getTransformations(deIdentifyTextRequest.getTransformations()));
if (tokenFormat != null) {
if (tokenFormat.getVaultToken() != null && !tokenFormat.getVaultToken().isEmpty()) {
vaultToken = Optional.of(tokenFormat.getVaultToken().stream()
.map(detectEntity -> EntityType.valueOf(detectEntity.name()))
.collect(Collectors.toList()));
}
if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) {
entityTypes = Optional.of(tokenFormat.getEntityOnly().stream()
.map(detectEntity -> EntityType.valueOf(detectEntity.name()))
.collect(Collectors.toList()));
}
if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) {
entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream()
.map(detectEntity -> EntityType.valueOf(detectEntity.name()))
.collect(Collectors.toList()));
}
}
TokenType tokenType = TokenType.builder()
.vaultToken(vaultToken)
.entityOnly(entityTypes)
.entityUnqCounter(entityUniqueCounter)
.build();
return DeidentifyStringRequest.builder()
.vaultId(vaultId)
.text(deIdentifyTextRequest.getText())
.entityTypes(mappedEntityTypes)
.tokenType(tokenType)
.allowRegex(allowRegex)
.restrictRegex(restrictRegex)
.transformations(transformations)
.build();
}
protected ReidentifyStringRequest getReidentifyStringRequest(ReidentifyTextRequest reidentifyTextRequest, String vaultId) throws SkyflowException {
List<EntityType> maskEntities = null;
List<EntityType> redactedEntities = null;
List<EntityType> plaintextEntities = null;
if (reidentifyTextRequest.getMaskedEntities() != null) {
maskEntities = reidentifyTextRequest.getMaskedEntities().stream()
.map(detectEntity -> EntityType.valueOf(detectEntity.name()))
.collect(Collectors.toList());
}
if (reidentifyTextRequest.getPlainTextEntities() != null) {
plaintextEntities = reidentifyTextRequest.getPlainTextEntities().stream()
.map(detectEntity -> EntityType.valueOf(detectEntity.name()))
.collect(Collectors.toList());
}
if (reidentifyTextRequest.getRedactedEntities() != null) {
redactedEntities = reidentifyTextRequest.getRedactedEntities().stream()
.map(detectEntity -> EntityType.valueOf(detectEntity.name()))
.collect(Collectors.toList());
}
ReidentifyStringRequestFormat reidentifyStringRequestFormat = ReidentifyStringRequestFormat.builder()
.masked(maskEntities)
.plaintext(plaintextEntities)
.redacted(redactedEntities)
.build();
return ReidentifyStringRequest.builder()
.text(reidentifyTextRequest.getText())
.vaultId(vaultId)
.format(reidentifyStringRequestFormat)
.build();
}
private EntityInfo convertDetectedEntityToEntityInfo(DetectedEntity detectedEntity) {
TextIndex textIndex = new TextIndex(
detectedEntity.getLocation().get().getStartIndex().orElse(0),
detectedEntity.getLocation().get().getEndIndex().orElse(0)
);
TextIndex processedIndex = new TextIndex(
detectedEntity.getLocation().get().getStartIndexProcessed().orElse(0),
detectedEntity.getLocation().get().getEndIndexProcessed().orElse(0)
);
Map<String, Float> entityScores = detectedEntity.getEntityScores()
.map(doubleMap -> doubleMap.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> entry.getValue().floatValue()
)))
.orElse(Collections.emptyMap());
return new EntityInfo(
detectedEntity.getToken().orElse(""),
detectedEntity.getValue().orElse(""),
textIndex,
processedIndex,
detectedEntity.getEntityType().orElse(""),
entityScores);
}
private Transformations getTransformations(com.skyflow.vault.detect.Transformations transformations) {
if (transformations == null || transformations.getShiftDates() == null) {
return null;
}
List<TransformationsShiftDatesEntityTypesItem> entityTypes = null;
if (!transformations.getShiftDates().getEntities().isEmpty()) {
entityTypes = transformations.getShiftDates().getEntities().stream()
.map(entity -> TransformationsShiftDatesEntityTypesItem.valueOf(entity.name()))
.collect(Collectors.toList());
} else {
entityTypes = Collections.emptyList();
}
return Transformations.builder()
.shiftDates(TransformationsShiftDates.builder()
.maxDays(transformations.getShiftDates().getMax())
.minDays(transformations.getShiftDates().getMin())
.entityTypes(entityTypes)
.build())
.build();
}
private void setApiKey() {
if (apiKey == null) {
apiKey = this.finalCredentials.getApiKey();
} else {
LogUtil.printInfoLog(InfoLogs.REUSE_API_KEY.getLog());
}
this.apiClientBuilder.token(token);
}
private void updateVaultURL() {
String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv());
this.apiClientBuilder.url(vaultURL);
}
private void prioritiseCredentials() throws SkyflowException {
try {
Credentials original = this.finalCredentials;
if (this.vaultConfig.getCredentials() != null) {
this.finalCredentials = this.vaultConfig.getCredentials();
} else if (this.commonCredentials != null) {
this.finalCredentials = this.commonCredentials;
} else {
Dotenv dotenv = Dotenv.load();
String sysCredentials = dotenv.get(Constants.ENV_CREDENTIALS_KEY_NAME);
if (sysCredentials == null) {
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(),
ErrorMessage.EmptyCredentials.getMessage());
} else {
this.finalCredentials = new Credentials();
this.finalCredentials.setCredentialsString(sysCredentials);
}
}
if (original != null && !original.equals(this.finalCredentials)) {
token = null;
apiKey = null;
}
} catch (DotenvException e) {
throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(),
ErrorMessage.EmptyCredentials.getMessage());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}