This repository was archived by the owner on Mar 23, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathBigQueryJdbcOAuthUtility.java
More file actions
733 lines (671 loc) · 29.6 KB
/
BigQueryJdbcOAuthUtility.java
File metadata and controls
733 lines (671 loc) · 29.6 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigquery.jdbc;
import static com.google.api.client.util.PemReader.readFirstSectionAndClose;
import static com.google.cloud.bigquery.jdbc.BigQueryErrorMessage.OAUTH_TYPE_ERROR_MESSAGE;
import com.google.api.client.util.PemReader;
import com.google.api.client.util.SecurityUtils;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.ClientId;
import com.google.auth.oauth2.ExternalAccountCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ImpersonatedCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.auth.oauth2.UserAuthorizer;
import com.google.auth.oauth2.UserCredentials;
import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.Strictness;
import com.google.gson.stream.JsonReader;
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final class BigQueryJdbcOAuthUtility {
private static final String USER_AUTH_SUCCESS_HTTP_RESPONSE =
"HTTP/1.1 200 OK\n"
+ "Content-Length: 300\n"
+ "Connection: close\n"
+ "Content-Type: text/html; charset=utf-8\n"
+ "\n"
+ "<!DOCTYPE html><html><body>\n"
+ "Thank you for using JDBC Driver for Google BigQuery!\n"
+ "You may now close the window.</body></html>";
private static final int USER_AUTH_TIMEOUT_MS = 120000;
private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(BigQueryJdbcOAuthUtility.class.getName());
private static final Map<String, String> BYOID_NAME_MAP =
new HashMap<String, String>() {
{
put(BigQueryJdbcUrlUtility.BYOID_AUDIENCE_URI_PROPERTY_NAME, "audience");
put(BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME, "credential_source");
put(BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME, "subject_token_type");
put(BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME, "token_url");
put(
BigQueryJdbcUrlUtility.BYOID_POOL_USER_PROJECT_PROPERTY_NAME,
"workforce_pool_user_project");
put(
BigQueryJdbcUrlUtility.BYOID_SA_IMPERSONATION_URI_PROPERTY_NAME,
"service_account_impersonation_url");
}
};
/**
* Parses the OAuth properties from the given URL.
*
* @param url The URL to parse.
* @return A map of OAuth properties.
*/
static Map<String, String> parseOAuthProperties(DataSource ds, String callerClassName) {
LOG.finest("++enter++\t" + callerClassName);
Map<String, String> oauthProperties = new HashMap<>();
AuthType authType;
try {
authType = AuthType.fromValue(ds.getOAuthType());
} catch (NumberFormatException exception) {
throw new IllegalArgumentException(OAUTH_TYPE_ERROR_MESSAGE);
}
oauthProperties.put(BigQueryJdbcUrlUtility.OAUTH_TYPE_PROPERTY_NAME, String.valueOf(authType));
switch (authType) {
case GOOGLE_SERVICE_ACCOUNT:
// For using a Google Service Account (OAuth Type 0)
// need: project id, OAuthServiceAcctEmail and OAuthPvtKey or OAuthPvtKeyPath that can be
// .p12 or json.
// TODO: validation if .p12 or json file can be in getPropertyInfo can be handy for user
String serviceAccountEmail = ds.getOAuthServiceAcctEmail();
String serviceAccountPK = ds.getOAuthPvtKey();
String serviceAccountPrivateKeyPath = ds.getOAuthPvtKeyPath();
String p12Password = ds.getOAuthP12Password();
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_SA_EMAIL_PROPERTY_NAME, serviceAccountEmail);
oauthProperties.put(BigQueryJdbcUrlUtility.OAUTH_P12_PASSWORD_PROPERTY_NAME, p12Password);
if (serviceAccountEmail != null && serviceAccountPK != null) {
oauthProperties.put(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME, serviceAccountPK);
} else {
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME,
serviceAccountPrivateKeyPath);
}
break;
case GOOGLE_USER_ACCOUNT:
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, ds.getOAuthClientId());
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, ds.getOAuthClientSecret());
int reqGoogleDriveScope = ds.getRequestGoogleDriveScope();
oauthProperties.put(
BigQueryJdbcUrlUtility.REQUEST_GOOGLE_DRIVE_SCOPE_PROPERTY_NAME,
String.valueOf(reqGoogleDriveScope));
LOG.fine("RequestGoogleDriveScope parsed.");
break;
case PRE_GENERATED_TOKEN:
String refreshToken = ds.getOAuthRefreshToken();
if (refreshToken != null) {
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_REFRESH_TOKEN_PROPERTY_NAME, refreshToken);
LOG.fine("OAuthRefreshToken provided.");
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, ds.getOAuthClientId());
LOG.fine("OAuthClientId provided.");
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, ds.getOAuthClientSecret());
LOG.fine("OAuthClientSecret provided.");
break;
}
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_PROPERTY_NAME, ds.getOAuthAccessToken());
LOG.fine("OAuthAccessToken provided.");
break;
case APPLICATION_DEFAULT_CREDENTIALS:
// For Application Default Credentials (OAuth Type 3)
// need: project id
break;
case EXTERNAL_ACCOUNT_AUTH:
// For External account authentication (OAuth Type 4)
// need: project id, OAuthPvtKey or OAuthPvtKeyPath or BYOID_PROPERTIES
String pvtKey = ds.getOAuthPvtKey();
String pvtKeyPath = ds.getOAuthPvtKeyPath();
if (pvtKey != null) {
oauthProperties.put(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME, pvtKey);
LOG.fine("OAuthPvtKey provided.");
} else if (pvtKeyPath != null) {
oauthProperties.put(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME, pvtKeyPath);
LOG.fine("OAuthPvtKeyPath provided.");
} else {
if (ds.getByoidAudienceUri() != null) {
oauthProperties.put(
BigQueryJdbcUrlUtility.BYOID_AUDIENCE_URI_PROPERTY_NAME, ds.getByoidAudienceUri());
}
if (ds.getByoidCredentialSource() != null) {
oauthProperties.put(
BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME,
ds.getByoidCredentialSource());
}
if (ds.getByoidPoolUserProject() != null) {
oauthProperties.put(
BigQueryJdbcUrlUtility.BYOID_POOL_USER_PROJECT_PROPERTY_NAME,
ds.getByoidPoolUserProject());
}
if (ds.getByoidSAImpersonationUri() != null) {
oauthProperties.put(
BigQueryJdbcUrlUtility.BYOID_SA_IMPERSONATION_URI_PROPERTY_NAME,
ds.getByoidSAImpersonationUri());
}
if (ds.getByoidSubjectTokenType() != null) {
oauthProperties.put(
BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME,
ds.getByoidSubjectTokenType());
}
if (ds.getByoidTokenUri() != null) {
oauthProperties.put(
BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME, ds.getByoidTokenUri());
}
String universeDomain = ds.getUniverseDomain();
if (universeDomain != null) {
oauthProperties.put(
BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, universeDomain);
LOG.fine(
BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME
+ " provided. Caller : "
+ callerClassName);
}
}
break;
}
if (authType == AuthType.GOOGLE_SERVICE_ACCOUNT
|| authType == AuthType.GOOGLE_USER_ACCOUNT
|| authType == AuthType.PRE_GENERATED_TOKEN) {
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_EMAIL_PROPERTY_NAME,
ds.getOAuthSAImpersonationEmail());
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_CHAIN_PROPERTY_NAME,
ds.getOAuthSAImpersonationChain());
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_SCOPES_PROPERTY_NAME,
ds.getOAuthSAImpersonationScopes() != null
? ds.getOAuthSAImpersonationScopes()
: BigQueryJdbcUrlUtility.DEFAULT_OAUTH_SA_IMPERSONATION_SCOPES_VALUE);
oauthProperties.put(
BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_TOKEN_LIFETIME_PROPERTY_NAME,
ds.getOAuthSAImpersonationTokenLifetime() != null
? ds.getOAuthSAImpersonationTokenLifetime()
: BigQueryJdbcUrlUtility.DEFAULT_OAUTH_SA_IMPERSONATION_TOKEN_LIFETIME_VALUE);
}
return oauthProperties;
}
/**
* Gets the credentials for the given Auth properties.
*
* @param authProperties A map of Auth properties.
* @return A GoogleCredentials object.
*/
static GoogleCredentials getCredentials(
Map<String, String> authProperties,
Map<String, String> overrideProperties,
String callerClassName) {
LOG.finest("++enter++\t" + callerClassName);
AuthType authType =
AuthType.valueOf(authProperties.get(BigQueryJdbcUrlUtility.OAUTH_TYPE_PROPERTY_NAME));
GoogleCredentials credentials;
switch (authType) {
case GOOGLE_SERVICE_ACCOUNT:
credentials =
getGoogleServiceAccountCredentials(authProperties, overrideProperties, callerClassName);
break;
case GOOGLE_USER_ACCOUNT:
credentials =
getGoogleUserAccountCredentials(authProperties, overrideProperties, callerClassName);
break;
case PRE_GENERATED_TOKEN:
credentials =
getPreGeneratedTokensCredentials(authProperties, overrideProperties, callerClassName);
break;
case APPLICATION_DEFAULT_CREDENTIALS:
// This auth method doesn't support service account impersonation
return getApplicationDefaultCredentials(callerClassName);
case EXTERNAL_ACCOUNT_AUTH:
// This auth method doesn't support service account impersonation
return getExternalAccountAuthCredentials(authProperties, callerClassName);
default:
throw new IllegalStateException(OAUTH_TYPE_ERROR_MESSAGE);
}
return getServiceAccountImpersonatedCredentials(credentials, authProperties);
}
private static boolean isFileExists(String filename) {
try {
return filename != null && !filename.isEmpty() && Files.exists(Paths.get(filename));
} catch (Exception e) {
// Filename is invalid
return false;
}
}
private static boolean isJson(byte[] value) {
try {
// This is done this way to ensure strict Json parsing
// https://github.com/google/gson/issues/1208#issuecomment-2120764686
InputStream stream = new ByteArrayInputStream(value);
InputStreamReader reader = new InputStreamReader(stream);
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setStrictness(Strictness.STRICT);
JsonElement json = JsonParser.parseReader(jsonReader);
return json != null;
} catch (Exception e) {
// Unable to parse json string
return false;
}
}
private static GoogleCredentials getGoogleServiceAccountCredentials(
Map<String, String> authProperties,
Map<String, String> overrideProperties,
String callerClassName) {
LOG.finest("++enter++\t" + callerClassName);
ServiceAccountCredentials.Builder builder;
try {
final String pvtKeyPath =
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME);
final String pvtKey = authProperties.get(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME);
final String pvtEmail =
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_SA_EMAIL_PROPERTY_NAME);
final String p12Password =
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_P12_PASSWORD_PROPERTY_NAME);
final String keyPath = pvtKeyPath != null ? pvtKeyPath : pvtKey;
PrivateKey key = null;
byte[] keyBytes = pvtKey != null ? pvtKey.getBytes() : null;
if (isFileExists(keyPath)) {
try (InputStream stream = new FileInputStream(keyPath)) {
int bufferSize = 1024 * 1024;
byte[] buffer = new byte[bufferSize];
stream.read(buffer, 0, bufferSize);
keyBytes = buffer;
}
}
InputStream stream = null;
if (isJson(keyBytes)) {
stream = new ByteArrayInputStream(keyBytes);
} else if (pvtKey != null) {
key = privateKeyFromPkcs8(pvtKey);
} else if (keyBytes != null) {
key = privateKeyFromP12Bytes(keyBytes, p12Password);
}
if (stream != null) {
builder = ServiceAccountCredentials.fromStream(stream).toBuilder();
} else if (pvtEmail != null && key != null) {
builder =
ServiceAccountCredentials.newBuilder().setClientEmail(pvtEmail).setPrivateKey(key);
} else {
LOG.severe("No valid Service Account credentials provided.");
throw new BigQueryJdbcRuntimeException("No valid credentials provided.");
}
if (overrideProperties.containsKey(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME)) {
builder.setTokenServerUri(
new URI(overrideProperties.get(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME)));
}
if (overrideProperties.containsKey(
BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) {
builder.setUniverseDomain(
overrideProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
}
} catch (URISyntaxException | IOException e) {
LOG.severe("Validation failure for Service Account credentials.");
throw new BigQueryJdbcRuntimeException(e);
}
LOG.info("GoogleCredentials instantiated. Auth Method: Service Account.");
return builder.build();
}
static UserAuthorizer getUserAuthorizer(
Map<String, String> authProperties,
Map<String, String> overrideProperties,
int port,
String callerClassName)
throws URISyntaxException {
LOG.finest("++enter++\t" + callerClassName);
List<String> scopes = new ArrayList<>();
scopes.add("https://www.googleapis.com/auth/bigquery");
// Add Google Drive scope conditionally
if (authProperties.containsKey(
BigQueryJdbcUrlUtility.REQUEST_GOOGLE_DRIVE_SCOPE_PROPERTY_NAME)) {
try {
int driveScopeValue =
Integer.parseInt(
authProperties.get(
BigQueryJdbcUrlUtility.REQUEST_GOOGLE_DRIVE_SCOPE_PROPERTY_NAME));
if (driveScopeValue == 1) {
scopes.add("https://www.googleapis.com/auth/drive.readonly");
LOG.fine("Added Google Drive read-only scope. Caller: " + callerClassName);
}
} catch (NumberFormatException e) {
LOG.severe(
"Invalid value for RequestGoogleDriveScope, defaulting to not request Drive scope."
+ " Caller: "
+ callerClassName);
}
}
List<String> responseTypes = new ArrayList<>();
responseTypes.add("code");
ClientId clientId =
ClientId.of(
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME),
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME));
UserAuthorizer.Builder userAuthorizerBuilder =
UserAuthorizer.newBuilder()
.setClientId(clientId)
.setScopes(scopes)
.setCallbackUri(URI.create("http://localhost:" + port));
if (overrideProperties.containsKey(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME)) {
userAuthorizerBuilder.setTokenServerUri(
new URI(overrideProperties.get(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME)));
}
return userAuthorizerBuilder.build();
}
static UserCredentials getCredentialsFromCode(
UserAuthorizer userAuthorizer, String code, String callerClassName) throws IOException {
LOG.finest("++enter++\t" + callerClassName);
return userAuthorizer.getCredentialsFromCode(code, URI.create(""));
}
private static GoogleCredentials getGoogleUserAccountCredentials(
Map<String, String> authProperties,
Map<String, String> overrideProperties,
String callerClassName) {
LOG.finest("++enter++\t" + callerClassName);
try {
ServerSocket serverSocket = new ServerSocket(0);
serverSocket.setSoTimeout(USER_AUTH_TIMEOUT_MS);
int port = serverSocket.getLocalPort();
UserAuthorizer userAuthorizer =
getUserAuthorizer(authProperties, overrideProperties, port, callerClassName);
URL authURL = userAuthorizer.getAuthorizationUrl("user", "", URI.create(""));
String code;
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(authURL.toURI());
Socket socket = serverSocket.accept();
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = bufferedReader.readLine();
Pattern p = Pattern.compile("(?<=code=).*?(?=&|$)");
Matcher m = p.matcher(response);
if (!m.find()) {
throw new BigQueryJdbcRuntimeException("Could not retrieve the code for user auth");
}
code = m.group();
printWriter.println(USER_AUTH_SUCCESS_HTTP_RESPONSE);
printWriter.flush();
socket.close();
serverSocket.close();
} else {
throw new BigQueryJdbcRuntimeException("User auth only supported in desktop environments");
}
return getCredentialsFromCode(userAuthorizer, code, callerClassName);
} catch (IOException | URISyntaxException ex) {
LOG.severe(
"Failed to establish connection using User Account authentication: %s", ex.getMessage());
throw new BigQueryJdbcRuntimeException(ex);
}
}
private static GoogleCredentials getPreGeneratedAccessTokenCredentials(
Map<String, String> authProperties,
Map<String, String> overrideProperties,
String callerClassName) {
LOG.finest("++enter++\t" + callerClassName);
GoogleCredentials.Builder builder = GoogleCredentials.newBuilder();
if (overrideProperties.containsKey(
BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) {
builder.setUniverseDomain(
overrideProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
}
LOG.info("Connection established. Auth Method: Pre-generated Access Token.");
return builder
.setAccessToken(
AccessToken.newBuilder()
.setTokenValue(
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_PROPERTY_NAME))
.build())
.build();
}
static GoogleCredentials getPreGeneratedTokensCredentials(
Map<String, String> authProperties,
Map<String, String> overrideProperties,
String callerClassName) {
LOG.finest("++enter++\t" + callerClassName);
if (authProperties.containsKey(BigQueryJdbcUrlUtility.OAUTH_REFRESH_TOKEN_PROPERTY_NAME)) {
try {
return getPreGeneratedRefreshTokenCredentials(
authProperties, overrideProperties, callerClassName);
} catch (URISyntaxException ex) {
throw new BigQueryJdbcRuntimeException(ex);
}
} else {
return getPreGeneratedAccessTokenCredentials(
authProperties, overrideProperties, callerClassName);
}
}
static UserCredentials getPreGeneratedRefreshTokenCredentials(
Map<String, String> authProperties,
Map<String, String> overrideProperties,
String callerClassName)
throws URISyntaxException {
LOG.finest("++enter++\t" + callerClassName);
UserCredentials.Builder userCredentialsBuilder =
UserCredentials.newBuilder()
.setRefreshToken(
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_REFRESH_TOKEN_PROPERTY_NAME))
.setClientId(authProperties.get(BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME))
.setClientSecret(
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME));
if (overrideProperties.containsKey(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME)) {
userCredentialsBuilder.setTokenServerUri(
new URI(overrideProperties.get(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME)));
}
if (overrideProperties.containsKey(
BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) {
userCredentialsBuilder.setUniverseDomain(
overrideProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
}
LOG.info("Connection established. Auth Method: Pre-generated Refresh Token.");
return userCredentialsBuilder.build();
}
private static GoogleCredentials getApplicationDefaultCredentials(String callerClassName) {
LOG.finest("++enter++\t" + callerClassName);
try {
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
String principal = "unknown";
if (credentials instanceof ServiceAccountCredentials) {
principal = ((ServiceAccountCredentials) credentials).getClientEmail();
} else if (credentials instanceof UserCredentials) {
principal = "user credentials";
} else if (credentials instanceof ExternalAccountCredentials) {
principal = "external account";
}
LOG.info(
"Connection established. Auth Method: Application Default Credentials, Principal: %s.",
principal);
return credentials;
} catch (IOException exception) {
// TODO throw exception
throw new BigQueryJdbcRuntimeException("Application default credentials not found.");
}
}
private static GoogleCredentials getExternalAccountAuthCredentials(
Map<String, String> authProperties, String callerClassName) {
LOG.finest("++enter++\t" + callerClassName);
try {
JsonObject jsonObject = null;
String credentialsPath = null;
if (authProperties.containsKey(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME)) {
String pvtKeyPath =
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME).trim();
if (pvtKeyPath.startsWith("{")) {
jsonObject = JsonParser.parseString(pvtKeyPath).getAsJsonObject();
} else {
credentialsPath = pvtKeyPath;
}
} else if (authProperties.containsKey(
BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME)) {
credentialsPath =
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME);
} else {
jsonObject = new JsonObject();
for (String property : BigQueryJdbcUrlUtility.BYOID_PROPERTIES) {
if (Objects.equals(
property, BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME)) {
jsonObject.add(
BYOID_NAME_MAP.get(property),
JsonParser.parseString(authProperties.get(property)).getAsJsonObject());
} else if (authProperties.containsKey(property)) {
jsonObject.addProperty(BYOID_NAME_MAP.get(property), authProperties.get(property));
}
}
if (authProperties.containsKey(
BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) {
jsonObject.addProperty(
"universe_domain",
authProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
}
}
if (credentialsPath != null) {
return ExternalAccountCredentials.fromStream(
Files.newInputStream(Paths.get(credentialsPath)));
} else if (jsonObject != null) {
return ExternalAccountCredentials.fromStream(
new ByteArrayInputStream(jsonObject.toString().getBytes()));
} else {
throw new IllegalArgumentException(
"Insufficient info provided for external authentication");
}
} catch (IOException e) {
throw new BigQueryJdbcRuntimeException(e);
}
}
// This function checks if connection string contains configuration for
// credentials impersonation. If not, it returns regular credentials object.
// If impersonated service account is provided, returns Credentials object
// accomodating this information.
private static GoogleCredentials getServiceAccountImpersonatedCredentials(
GoogleCredentials credentials, Map<String, String> authProperties) {
String impersonationEmail =
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_EMAIL_PROPERTY_NAME);
if (impersonationEmail == null || impersonationEmail.isEmpty()) {
return credentials;
}
String impersonationChainString =
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_CHAIN_PROPERTY_NAME);
List<String> impersonationChain = null;
if (impersonationChainString != null && !impersonationChainString.isEmpty()) {
impersonationChain = Arrays.asList(impersonationChainString.split(","));
}
// Scopes has a default value, so it should never be null
List<String> impersonationScopes =
Arrays.asList(
authProperties
.get(BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_SCOPES_PROPERTY_NAME)
.split(","));
// Token lifetime has a default value, so it should never be null
String impersonationLifetime =
authProperties.get(
BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_TOKEN_LIFETIME_PROPERTY_NAME);
int impersonationLifetimeInt = 0;
try {
impersonationLifetimeInt = Integer.parseInt(impersonationLifetime);
} catch (NumberFormatException e) {
LOG.severe("Invalid value for ServiceAccountImpersonationTokenLifetime.");
throw new IllegalArgumentException(
"Invalid value for ServiceAccountImpersonationTokenLifetime: must be a positive integer.",
e);
}
return ImpersonatedCredentials.create(
credentials,
impersonationEmail,
impersonationChain,
impersonationScopes,
impersonationLifetimeInt);
}
static PrivateKey privateKeyFromP12Bytes(byte[] privateKey, String password) {
try {
InputStream stream = new ByteArrayInputStream(privateKey);
return SecurityUtils.loadPrivateKeyFromKeyStore(
SecurityUtils.getPkcs12KeyStore(), stream, "notasecret", "privatekey", password);
} catch (IOException | GeneralSecurityException e) {
LOG.warning("Unable to parse p12 file: " + e.getMessage());
return null;
}
}
static PrivateKey privateKeyFromPkcs8(String privateKeyPkcs8) {
try {
Reader reader = new StringReader(privateKeyPkcs8);
PemReader.Section section = readFirstSectionAndClose(reader, "PRIVATE KEY");
if (section == null) {
throw new IOException("Invalid PKCS#8 data.");
}
byte[] bytes = section.getBase64DecodedBytes();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory();
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException e) {
LOG.warning("Unable to parse pkcs8 secret: " + e.getMessage());
return null;
}
}
enum AuthType {
GOOGLE_SERVICE_ACCOUNT(0),
GOOGLE_USER_ACCOUNT(1),
PRE_GENERATED_TOKEN(2),
APPLICATION_DEFAULT_CREDENTIALS(3),
EXTERNAL_ACCOUNT_AUTH(4);
private final int value;
AuthType(int value) {
this.value = value;
}
static AuthType fromValue(int value) {
for (AuthType authType : values()) {
if (authType.value == value) {
return authType;
}
}
throw new IllegalStateException(OAUTH_TYPE_ERROR_MESSAGE + ": " + value);
}
}
}