@@ -855,8 +855,15 @@ default boolean isEnableEndToEndTracing() {
855855 default String getMonitoringHost () {
856856 return null ;
857857 }
858+
859+ default GoogleCredentials getDefaultExternalHostCredentials () {
860+ return null ;
861+ }
858862 }
859863
864+ static final String DEFAULT_SPANNER_EXTERNAL_HOST_CREDENTIALS =
865+ "SPANNER_EXTERNAL_HOST_AUTH_TOKEN" ;
866+
860867 /**
861868 * Default implementation of {@link SpannerEnvironment}. Reads all configuration from environment
862869 * variables.
@@ -912,6 +919,11 @@ public boolean isEnableEndToEndTracing() {
912919 public String getMonitoringHost () {
913920 return System .getenv (SPANNER_MONITORING_HOST );
914921 }
922+
923+ @ Override
924+ public GoogleCredentials getDefaultExternalHostCredentials () {
925+ return getOAuthTokenFromFile (System .getenv (DEFAULT_SPANNER_EXTERNAL_HOST_CREDENTIALS ));
926+ }
915927 }
916928
917929 /** Builder for {@link SpannerOptions} instances. */
@@ -1646,18 +1658,7 @@ public SpannerOptions build() {
16461658 // As we are using plain text, we should never send any credentials.
16471659 this .setCredentials (NoCredentials .getInstance ());
16481660 } else if (isExternalHost && credentials == null ) {
1649- String externalHostTokenPath = System .getenv ("SPANNER_EXTERNAL_HOST_AUTH_TOKEN" );
1650- if (!Strings .isNullOrEmpty (externalHostTokenPath )) {
1651- String token ;
1652- try {
1653- token =
1654- Base64 .getEncoder ()
1655- .encodeToString (Files .readAllBytes (Paths .get (externalHostTokenPath )));
1656- } catch (IOException e ) {
1657- throw SpannerExceptionFactory .newSpannerException (e );
1658- }
1659- credentials = GoogleCredentials .create (new AccessToken (token , null ));
1660- }
1661+ credentials = environment .getDefaultExternalHostCredentials ();
16611662 }
16621663 if (this .numChannels == null ) {
16631664 this .numChannels =
@@ -1698,6 +1699,24 @@ public static void useDefaultEnvironment() {
16981699 SpannerOptions .environment = SpannerEnvironmentImpl .INSTANCE ;
16991700 }
17001701
1702+ @ InternalApi
1703+ public static GoogleCredentials getDefaultExternalHostCredentialsFromSysEnv () {
1704+ return getOAuthTokenFromFile (System .getenv (DEFAULT_SPANNER_EXTERNAL_HOST_CREDENTIALS ));
1705+ }
1706+
1707+ private static @ Nullable GoogleCredentials getOAuthTokenFromFile (@ Nullable String file ) {
1708+ if (!Strings .isNullOrEmpty (file )) {
1709+ String token ;
1710+ try {
1711+ token = Base64 .getEncoder ().encodeToString (Files .readAllBytes (Paths .get (file )));
1712+ } catch (IOException e ) {
1713+ throw SpannerExceptionFactory .newSpannerException (e );
1714+ }
1715+ return GoogleCredentials .create (new AccessToken (token , null ));
1716+ }
1717+ return null ;
1718+ }
1719+
17011720 /**
17021721 * Enables OpenTelemetry traces. Enabling OpenTelemetry traces will disable OpenCensus traces. By
17031722 * default, OpenCensus traces are enabled.
0 commit comments