googleauth 1.13.1 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +29 -0
- data/Credentials.md +106 -0
- data/Errors.md +152 -0
- data/README.md +1 -1
- data/lib/googleauth/api_key.rb +164 -0
- data/lib/googleauth/application_default.rb +3 -1
- data/lib/googleauth/base_client.rb +5 -0
- data/lib/googleauth/bearer_token.rb +162 -0
- data/lib/googleauth/client_id.rb +9 -5
- data/lib/googleauth/compute_engine.rb +65 -19
- data/lib/googleauth/credentials.rb +23 -6
- data/lib/googleauth/credentials_loader.rb +11 -6
- data/lib/googleauth/default_credentials.rb +18 -6
- data/lib/googleauth/errors.rb +117 -0
- data/lib/googleauth/external_account/aws_credentials.rb +85 -18
- data/lib/googleauth/external_account/base_credentials.rb +31 -2
- data/lib/googleauth/external_account/external_account_utils.rb +15 -4
- data/lib/googleauth/external_account/identity_pool_credentials.rb +40 -15
- data/lib/googleauth/external_account/pluggable_credentials.rb +34 -19
- data/lib/googleauth/external_account.rb +30 -6
- data/lib/googleauth/helpers/connection.rb +7 -1
- data/lib/googleauth/iam.rb +19 -3
- data/lib/googleauth/id_tokens/errors.rb +13 -7
- data/lib/googleauth/id_tokens/key_sources.rb +13 -7
- data/lib/googleauth/id_tokens/verifier.rb +2 -3
- data/lib/googleauth/id_tokens.rb +4 -4
- data/lib/googleauth/impersonated_service_account.rb +64 -17
- data/lib/googleauth/json_key_reader.rb +11 -2
- data/lib/googleauth/oauth2/sts_client.rb +9 -4
- data/lib/googleauth/scope_util.rb +1 -1
- data/lib/googleauth/service_account.rb +17 -160
- data/lib/googleauth/service_account_jwt_header.rb +187 -0
- data/lib/googleauth/signet.rb +24 -6
- data/lib/googleauth/user_authorizer.rb +35 -7
- data/lib/googleauth/user_refresh.rb +25 -7
- data/lib/googleauth/version.rb +1 -1
- data/lib/googleauth/web_user_authorizer.rb +46 -9
- data/lib/googleauth.rb +8 -0
- metadata +14 -8
data/lib/googleauth/iam.rb
CHANGED
@@ -27,8 +27,9 @@ module Google
|
|
27
27
|
|
28
28
|
# Initializes an IAMCredentials.
|
29
29
|
#
|
30
|
-
# @param selector
|
31
|
-
# @param token
|
30
|
+
# @param selector [String] The IAM selector.
|
31
|
+
# @param token [String] The IAM token.
|
32
|
+
# @raise [TypeError] If selector or token is not a String
|
32
33
|
def initialize selector, token
|
33
34
|
raise TypeError unless selector.is_a? String
|
34
35
|
raise TypeError unless token.is_a? String
|
@@ -37,13 +38,19 @@ module Google
|
|
37
38
|
end
|
38
39
|
|
39
40
|
# Adds the credential fields to the hash.
|
41
|
+
#
|
42
|
+
# @param a_hash [Hash] The hash to update with credentials
|
43
|
+
# @return [Hash] The updated hash with credentials
|
40
44
|
def apply! a_hash
|
41
45
|
a_hash[SELECTOR_KEY] = @selector
|
42
46
|
a_hash[TOKEN_KEY] = @token
|
43
47
|
a_hash
|
44
48
|
end
|
45
49
|
|
46
|
-
# Returns a clone of a_hash updated with the
|
50
|
+
# Returns a clone of a_hash updated with the authorization header
|
51
|
+
#
|
52
|
+
# @param a_hash [Hash] The hash to clone and update with credentials
|
53
|
+
# @return [Hash] A new hash with credentials
|
47
54
|
def apply a_hash
|
48
55
|
a_copy = a_hash.clone
|
49
56
|
apply! a_copy
|
@@ -52,9 +59,18 @@ module Google
|
|
52
59
|
|
53
60
|
# Returns a reference to the #apply method, suitable for passing as
|
54
61
|
# a closure
|
62
|
+
#
|
63
|
+
# @return [Proc] A procedure that updates a hash with credentials
|
55
64
|
def updater_proc
|
56
65
|
proc { |a_hash, _opts = {}| apply a_hash }
|
57
66
|
end
|
67
|
+
|
68
|
+
# Returns the IAM authority selector as the principal
|
69
|
+
# @private
|
70
|
+
# @return [String] the IAM authoirty selector
|
71
|
+
def principal
|
72
|
+
@selector
|
73
|
+
end
|
58
74
|
end
|
59
75
|
end
|
60
76
|
end
|
@@ -14,6 +14,8 @@
|
|
14
14
|
# See the License for the specific language governing permissions and
|
15
15
|
# limitations under the License.
|
16
16
|
|
17
|
+
require "googleauth/errors"
|
18
|
+
|
17
19
|
|
18
20
|
module Google
|
19
21
|
module Auth
|
@@ -21,35 +23,39 @@ module Google
|
|
21
23
|
##
|
22
24
|
# Failed to obtain keys from the key source.
|
23
25
|
#
|
24
|
-
class KeySourceError < StandardError
|
26
|
+
class KeySourceError < StandardError
|
27
|
+
include Google::Auth::Error
|
28
|
+
end
|
25
29
|
|
26
30
|
##
|
27
31
|
# Failed to verify a token.
|
28
32
|
#
|
29
|
-
class VerificationError < StandardError
|
33
|
+
class VerificationError < StandardError
|
34
|
+
include Google::Auth::Error
|
35
|
+
end
|
30
36
|
|
31
37
|
##
|
32
|
-
# Failed to verify
|
38
|
+
# Failed to verify token because it is expired.
|
33
39
|
#
|
34
40
|
class ExpiredTokenError < VerificationError; end
|
35
41
|
|
36
42
|
##
|
37
|
-
# Failed to verify
|
43
|
+
# Failed to verify token because its signature did not match.
|
38
44
|
#
|
39
45
|
class SignatureError < VerificationError; end
|
40
46
|
|
41
47
|
##
|
42
|
-
# Failed to verify
|
48
|
+
# Failed to verify token because its issuer did not match.
|
43
49
|
#
|
44
50
|
class IssuerMismatchError < VerificationError; end
|
45
51
|
|
46
52
|
##
|
47
|
-
# Failed to verify
|
53
|
+
# Failed to verify token because its audience did not match.
|
48
54
|
#
|
49
55
|
class AudienceMismatchError < VerificationError; end
|
50
56
|
|
51
57
|
##
|
52
|
-
# Failed to verify
|
58
|
+
# Failed to verify token because its authorized party did not match.
|
53
59
|
#
|
54
60
|
class AuthorizedPartyMismatchError < VerificationError; end
|
55
61
|
end
|
@@ -72,8 +72,8 @@ module Google
|
|
72
72
|
#
|
73
73
|
# @param jwk [Hash,String] The JWK specification.
|
74
74
|
# @return [KeyInfo]
|
75
|
-
# @raise [KeySourceError] If the key could not be extracted from the
|
76
|
-
# JWK.
|
75
|
+
# @raise [Google::Auth::IDTokens::KeySourceError] If the key could not be extracted from the
|
76
|
+
# JWK due to invalid type, malformed JSON, or invalid key data.
|
77
77
|
#
|
78
78
|
def from_jwk jwk
|
79
79
|
jwk = symbolize_keys ensure_json_parsed jwk
|
@@ -94,10 +94,10 @@ module Google
|
|
94
94
|
# Create an array of KeyInfo from a JWK Set, which may be given as
|
95
95
|
# either a hash or an unparsed JSON string.
|
96
96
|
#
|
97
|
-
# @param
|
97
|
+
# @param jwk_set [Hash,String] The JWK Set specification.
|
98
98
|
# @return [Array<KeyInfo>]
|
99
|
-
# @raise [KeySourceError] If a key could not be extracted from the
|
100
|
-
# JWK Set.
|
99
|
+
# @raise [Google::Auth::IDTokens::KeySourceError] If a key could not be extracted from the
|
100
|
+
# JWK Set, or if the set contains no keys.
|
101
101
|
#
|
102
102
|
def from_jwk_set jwk_set
|
103
103
|
jwk_set = symbolize_keys ensure_json_parsed jwk_set
|
@@ -261,7 +261,8 @@ module Google
|
|
261
261
|
# return the new keys.
|
262
262
|
#
|
263
263
|
# @return [Array<KeyInfo>]
|
264
|
-
# @raise [KeySourceError]
|
264
|
+
# @raise [Google::Auth::IDTokens::KeySourceError] If key retrieval fails, JSON parsing
|
265
|
+
# fails, or the data cannot be interpreted as keys
|
265
266
|
#
|
266
267
|
def refresh_keys
|
267
268
|
@monitor.synchronize do
|
@@ -310,6 +311,11 @@ module Google
|
|
310
311
|
|
311
312
|
protected
|
312
313
|
|
314
|
+
# Interpret JSON data as X509 certificates
|
315
|
+
#
|
316
|
+
# @param data [Hash] The JSON data containing certificate strings
|
317
|
+
# @return [Array<KeyInfo>] Array of key info objects
|
318
|
+
# @raise [Google::Auth::IDTokens::KeySourceError] If X509 certificates cannot be parsed
|
313
319
|
def interpret_json data
|
314
320
|
data.map do |id, cert_str|
|
315
321
|
key = OpenSSL::X509::Certificate.new(cert_str).public_key
|
@@ -371,7 +377,7 @@ module Google
|
|
371
377
|
# Attempt to refresh keys and return the new keys.
|
372
378
|
#
|
373
379
|
# @return [Array<KeyInfo>]
|
374
|
-
# @raise [KeySourceError]
|
380
|
+
# @raise [Google::Auth::IDTokens::KeySourceError] If key retrieval failed for any source.
|
375
381
|
#
|
376
382
|
def refresh_keys
|
377
383
|
@sources.flat_map(&:refresh_keys)
|
@@ -61,10 +61,9 @@ module Google
|
|
61
61
|
# @param iss [String,nil] If given, override the `iss` check.
|
62
62
|
#
|
63
63
|
# @return [Hash] the decoded payload, if verification succeeded.
|
64
|
-
# @raise [KeySourceError] if the key source failed to obtain public keys
|
65
|
-
# @raise [VerificationError] if the token verification failed.
|
64
|
+
# @raise [Google::Auth::IDTokens::KeySourceError] if the key source failed to obtain public keys
|
65
|
+
# @raise [Google::Auth::IDTokens::VerificationError] if the token verification failed.
|
66
66
|
# Additional data may be available in the error subclass and message.
|
67
|
-
#
|
68
67
|
def verify token,
|
69
68
|
key_source: :default,
|
70
69
|
aud: :default,
|
data/lib/googleauth/id_tokens.rb
CHANGED
@@ -160,8 +160,8 @@ module Google
|
|
160
160
|
# checking is performed. Default is to check against {OIDC_ISSUERS}.
|
161
161
|
#
|
162
162
|
# @return [Hash] The decoded token payload.
|
163
|
-
# @raise [KeySourceError] if the key source failed to obtain public keys
|
164
|
-
# @raise [VerificationError] if the token verification failed.
|
163
|
+
# @raise [Google::Auth::IDTokens::KeySourceError] if the key source failed to obtain public keys
|
164
|
+
# @raise [Google::Auth::IDTokens::VerificationError] if the token verification failed.
|
165
165
|
# Additional data may be available in the error subclass and message.
|
166
166
|
#
|
167
167
|
def verify_oidc token,
|
@@ -197,8 +197,8 @@ module Google
|
|
197
197
|
# checking is performed. Default is to check against {IAP_ISSUERS}.
|
198
198
|
#
|
199
199
|
# @return [Hash] The decoded token payload.
|
200
|
-
# @raise [KeySourceError] if the key source failed to obtain public keys
|
201
|
-
# @raise [VerificationError] if the token verification failed.
|
200
|
+
# @raise [Google::Auth::IDTokens::KeySourceError] if the key source failed to obtain public keys
|
201
|
+
# @raise [Google::Auth::IDTokens::VerificationError] if the token verification failed.
|
202
202
|
# Additional data may be available in the error subclass and message.
|
203
203
|
#
|
204
204
|
def verify_iap token,
|
@@ -12,8 +12,8 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
|
15
|
-
require "googleauth/signet"
|
16
15
|
require "googleauth/base_client"
|
16
|
+
require "googleauth/errors"
|
17
17
|
require "googleauth/helpers/connection"
|
18
18
|
|
19
19
|
module Google
|
@@ -191,6 +191,20 @@ module Google
|
|
191
191
|
self.class.new options
|
192
192
|
end
|
193
193
|
|
194
|
+
# The principal behind the credentials. This class allows custom source credentials type
|
195
|
+
# that might not implement `principal`, in which case `:unknown` is returned.
|
196
|
+
#
|
197
|
+
# @private
|
198
|
+
# @return [String, Symbol] The string representation of the principal,
|
199
|
+
# the token type in lieu of the principal, or :unknown if source principal is unknown.
|
200
|
+
def principal
|
201
|
+
if @source_credentials.respond_to? :principal
|
202
|
+
@source_credentials.principal
|
203
|
+
else
|
204
|
+
:unknown
|
205
|
+
end
|
206
|
+
end
|
207
|
+
|
194
208
|
private
|
195
209
|
|
196
210
|
# Generates a new impersonation access token by exchanging the source credentials' token
|
@@ -200,21 +214,16 @@ module Google
|
|
200
214
|
# for an impersonation token using the specified impersonation URL. The generated token and
|
201
215
|
# its expiration time are cached for subsequent use.
|
202
216
|
#
|
217
|
+
# @private
|
203
218
|
# @param _options [Hash] (optional) Additional options for token retrieval (currently unused).
|
204
219
|
#
|
205
|
-
# @raise [
|
206
|
-
# @raise [
|
220
|
+
# @raise [Google::Auth::UnexpectedStatusError] If the response status is 403 or 500.
|
221
|
+
# @raise [Google::Auth::AuthorizationError] For other unexpected response statuses.
|
207
222
|
#
|
208
223
|
# @return [String] The newly generated impersonation access token.
|
209
224
|
def fetch_access_token! _options = {}
|
210
|
-
auth_header =
|
211
|
-
|
212
|
-
|
213
|
-
resp = connection.post @impersonation_url do |req|
|
214
|
-
req.headers.merge! auth_header
|
215
|
-
req.headers["Content-Type"] = "application/json"
|
216
|
-
req.body = MultiJson.dump({ scope: @scope })
|
217
|
-
end
|
225
|
+
auth_header = prepare_auth_header
|
226
|
+
resp = make_impersonation_request auth_header
|
218
227
|
|
219
228
|
case resp.status
|
220
229
|
when 200
|
@@ -223,14 +232,51 @@ module Google
|
|
223
232
|
@access_token = response["accessToken"]
|
224
233
|
access_token
|
225
234
|
when 403, 500
|
226
|
-
|
227
|
-
raise Signet::UnexpectedStatusError, msg
|
235
|
+
handle_error_response resp, UnexpectedStatusError
|
228
236
|
else
|
229
|
-
|
230
|
-
|
237
|
+
handle_error_response resp, AuthorizationError
|
238
|
+
end
|
239
|
+
end
|
240
|
+
|
241
|
+
# Prepares the authorization header for the impersonation request
|
242
|
+
# by fetching a token from source credentials.
|
243
|
+
#
|
244
|
+
# @private
|
245
|
+
# @return [Hash] The authorization header with the source credentials' token
|
246
|
+
def prepare_auth_header
|
247
|
+
auth_header = {}
|
248
|
+
@source_credentials.updater_proc.call auth_header
|
249
|
+
auth_header
|
250
|
+
end
|
251
|
+
|
252
|
+
# Makes the HTTP request to the impersonation endpoint.
|
253
|
+
#
|
254
|
+
# @private
|
255
|
+
# @param [Hash] auth_header The authorization header containing the source token
|
256
|
+
# @return [Faraday::Response] The HTTP response from the impersonation endpoint
|
257
|
+
def make_impersonation_request auth_header
|
258
|
+
connection.post @impersonation_url do |req|
|
259
|
+
req.headers.merge! auth_header
|
260
|
+
req.headers["Content-Type"] = "application/json"
|
261
|
+
req.body = MultiJson.dump({ scope: @scope })
|
231
262
|
end
|
232
263
|
end
|
233
264
|
|
265
|
+
# Creates and raises an appropriate error based on the response.
|
266
|
+
#
|
267
|
+
# @private
|
268
|
+
# @param [Faraday::Response] resp The HTTP response
|
269
|
+
# @param [Class] error_class The error class to instantiate
|
270
|
+
# @raise [StandardError] The appropriate error with details
|
271
|
+
def handle_error_response resp, error_class
|
272
|
+
msg = "Unexpected error code #{resp.status}.\n #{resp.env.response_body} #{ERROR_SUFFIX}"
|
273
|
+
raise error_class.with_details(
|
274
|
+
msg,
|
275
|
+
credential_type_name: self.class.name,
|
276
|
+
principal: principal
|
277
|
+
)
|
278
|
+
end
|
279
|
+
|
234
280
|
# Setter for the expires_at value that makes sure it is converted
|
235
281
|
# to Time object.
|
236
282
|
def expires_at= new_expires_at
|
@@ -249,7 +295,7 @@ module Google
|
|
249
295
|
#
|
250
296
|
# @return [Time, nil] The normalized Time object, or nil if the input is nil.
|
251
297
|
#
|
252
|
-
# @raise [
|
298
|
+
# @raise [Google::Auth::CredentialsError] If the input is not a Time, String, or nil.
|
253
299
|
def normalize_timestamp time
|
254
300
|
case time
|
255
301
|
when NilClass
|
@@ -259,7 +305,8 @@ module Google
|
|
259
305
|
when String
|
260
306
|
Time.parse time
|
261
307
|
else
|
262
|
-
|
308
|
+
message = "Invalid time value #{time}"
|
309
|
+
raise CredentialsError.with_details(message, credential_type_name: self.class.name, principal: principal)
|
263
310
|
end
|
264
311
|
end
|
265
312
|
|
@@ -12,6 +12,8 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
|
15
|
+
require "googleauth/errors"
|
16
|
+
|
15
17
|
module Google
|
16
18
|
# Module Auth provides classes that provide Google-specific authorization
|
17
19
|
# used to access Google APIs.
|
@@ -19,10 +21,17 @@ module Google
|
|
19
21
|
# JsonKeyReader contains the behaviour used to read private key and
|
20
22
|
# client email fields from the service account
|
21
23
|
module JsonKeyReader
|
24
|
+
# Reads a JSON key from an IO object and extracts common fields.
|
25
|
+
#
|
26
|
+
# @param json_key_io [IO] An IO object containing the JSON key
|
27
|
+
# @return [Array(String, String, String, String, String)] An array containing:
|
28
|
+
# private_key, client_email, project_id, quota_project_id, and universe_domain
|
29
|
+
# @raise [Google::Auth::InitializationError] If client_email or private_key
|
30
|
+
# fields are missing from the JSON
|
22
31
|
def read_json_key json_key_io
|
23
32
|
json_key = MultiJson.load json_key_io.read
|
24
|
-
raise "missing client_email" unless json_key.key? "client_email"
|
25
|
-
raise "missing private_key" unless json_key.key? "private_key"
|
33
|
+
raise InitializationError, "missing client_email" unless json_key.key? "client_email"
|
34
|
+
raise InitializationError, "missing private_key" unless json_key.key? "private_key"
|
26
35
|
[
|
27
36
|
json_key["private_key"],
|
28
37
|
json_key["client_email"],
|
@@ -12,6 +12,7 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
|
15
|
+
require "googleauth/errors"
|
15
16
|
require "googleauth/helpers/connection"
|
16
17
|
|
17
18
|
module Google
|
@@ -36,10 +37,12 @@ module Google
|
|
36
37
|
|
37
38
|
# Create a new instance of the STSClient.
|
38
39
|
#
|
39
|
-
# @param [
|
40
|
-
#
|
40
|
+
# @param [Hash] options Configuration options
|
41
|
+
# @option options [String] :token_exchange_endpoint The token exchange endpoint
|
42
|
+
# @option options [Faraday::Connection] :connection The Faraday connection to use
|
43
|
+
# @raise [Google::Auth::InitializationError] If token_exchange_endpoint is nil
|
41
44
|
def initialize options = {}
|
42
|
-
raise "Token exchange endpoint can not be nil" if options[:token_exchange_endpoint].nil?
|
45
|
+
raise InitializationError, "Token exchange endpoint can not be nil" if options[:token_exchange_endpoint].nil?
|
43
46
|
self.default_connection = options[:connection]
|
44
47
|
@token_exchange_endpoint = options[:token_exchange_endpoint]
|
45
48
|
end
|
@@ -67,6 +70,8 @@ module Google
|
|
67
70
|
# The optional additional headers to pass to the token exchange endpoint.
|
68
71
|
#
|
69
72
|
# @return [Hash] A hash containing the token exchange response.
|
73
|
+
# @raise [ArgumentError] If required options are missing
|
74
|
+
# @raise [Google::Auth::AuthorizationError] If the token exchange request fails
|
70
75
|
def exchange_token options = {}
|
71
76
|
missing_required_opts = [:grant_type, :subject_token, :subject_token_type] - options.keys
|
72
77
|
unless missing_required_opts.empty?
|
@@ -81,7 +86,7 @@ module Google
|
|
81
86
|
response = connection.post @token_exchange_endpoint, URI.encode_www_form(request_body), headers
|
82
87
|
|
83
88
|
if response.status != 200
|
84
|
-
raise "Token exchange failed with status #{response.status}"
|
89
|
+
raise AuthorizationError, "Token exchange failed with status #{response.status}"
|
85
90
|
end
|
86
91
|
|
87
92
|
MultiJson.load response.body
|
@@ -57,7 +57,7 @@ module Google
|
|
57
57
|
#
|
58
58
|
# @param scope [String,Array<String>] Input scope(s)
|
59
59
|
# @return [Array<String>] Always an array of strings
|
60
|
-
# @raise ArgumentError If the input is not a string or array of strings
|
60
|
+
# @raise [ArgumentError] If the input is not a string or array of strings
|
61
61
|
#
|
62
62
|
def self.as_array scope
|
63
63
|
case scope
|
@@ -12,13 +12,15 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
|
15
|
+
require "jwt"
|
16
|
+
require "multi_json"
|
17
|
+
require "stringio"
|
18
|
+
|
15
19
|
require "google/logging/message"
|
16
20
|
require "googleauth/signet"
|
17
21
|
require "googleauth/credentials_loader"
|
18
22
|
require "googleauth/json_key_reader"
|
19
|
-
require "
|
20
|
-
require "multi_json"
|
21
|
-
require "stringio"
|
23
|
+
require "googleauth/service_account_jwt_header"
|
22
24
|
|
23
25
|
module Google
|
24
26
|
# Module Auth provides classes that provide Google-specific authorization
|
@@ -49,8 +51,9 @@ module Google
|
|
49
51
|
|
50
52
|
# Creates a ServiceAccountCredentials.
|
51
53
|
#
|
52
|
-
# @param json_key_io [IO]
|
54
|
+
# @param json_key_io [IO] An IO object containing the JSON key
|
53
55
|
# @param scope [string|array|nil] the scope(s) to access
|
56
|
+
# @raise [ArgumentError] If both scope and target_audience are specified
|
54
57
|
def self.make_creds options = {}
|
55
58
|
json_key_io, scope, enable_self_signed_jwt, target_audience, audience, token_credential_uri =
|
56
59
|
options.values_at :json_key_io, :scope, :enable_self_signed_jwt, :target_audience,
|
@@ -108,6 +111,9 @@ module Google
|
|
108
111
|
# Handles certain escape sequences that sometimes appear in input.
|
109
112
|
# Specifically, interprets the "\n" sequence for newline, and removes
|
110
113
|
# enclosing quotes.
|
114
|
+
#
|
115
|
+
# @param str [String] The string to unescape
|
116
|
+
# @return [String] The unescaped string
|
111
117
|
def self.unescape str
|
112
118
|
str = str.gsub '\n', "\n"
|
113
119
|
str = str[1..-2] if str.start_with?('"') && str.end_with?('"')
|
@@ -162,6 +168,13 @@ module Google
|
|
162
168
|
self
|
163
169
|
end
|
164
170
|
|
171
|
+
# Returns the client email as the principal for service account credentials
|
172
|
+
# @private
|
173
|
+
# @return [String] the email address of the service account
|
174
|
+
def principal
|
175
|
+
@issuer
|
176
|
+
end
|
177
|
+
|
165
178
|
private
|
166
179
|
|
167
180
|
def apply_self_signed_jwt! a_hash
|
@@ -178,161 +191,5 @@ module Google
|
|
178
191
|
alt.apply! a_hash
|
179
192
|
end
|
180
193
|
end
|
181
|
-
|
182
|
-
# Authenticates requests using Google's Service Account credentials via
|
183
|
-
# JWT Header.
|
184
|
-
#
|
185
|
-
# This class allows authorizing requests for service accounts directly
|
186
|
-
# from credentials from a json key file downloaded from the developer
|
187
|
-
# console (via 'Generate new Json Key'). It is not part of any OAuth2
|
188
|
-
# flow, rather it creates a JWT and sends that as a credential.
|
189
|
-
#
|
190
|
-
# cf [Application Default Credentials](https://cloud.google.com/docs/authentication/production)
|
191
|
-
class ServiceAccountJwtHeaderCredentials
|
192
|
-
JWT_AUD_URI_KEY = :jwt_aud_uri
|
193
|
-
AUTH_METADATA_KEY = Google::Auth::BaseClient::AUTH_METADATA_KEY
|
194
|
-
TOKEN_CRED_URI = "https://www.googleapis.com/oauth2/v4/token".freeze
|
195
|
-
SIGNING_ALGORITHM = "RS256".freeze
|
196
|
-
EXPIRY = 60
|
197
|
-
|
198
|
-
extend CredentialsLoader
|
199
|
-
extend JsonKeyReader
|
200
|
-
|
201
|
-
attr_reader :project_id
|
202
|
-
attr_reader :quota_project_id
|
203
|
-
attr_accessor :universe_domain
|
204
|
-
attr_accessor :logger
|
205
|
-
|
206
|
-
# Create a ServiceAccountJwtHeaderCredentials.
|
207
|
-
#
|
208
|
-
# @param json_key_io [IO] an IO from which the JSON key can be read
|
209
|
-
# @param scope [string|array|nil] the scope(s) to access
|
210
|
-
def self.make_creds options = {}
|
211
|
-
json_key_io, scope = options.values_at :json_key_io, :scope
|
212
|
-
new json_key_io: json_key_io, scope: scope
|
213
|
-
end
|
214
|
-
|
215
|
-
# Initializes a ServiceAccountJwtHeaderCredentials.
|
216
|
-
#
|
217
|
-
# @param json_key_io [IO] an IO from which the JSON key can be read
|
218
|
-
def initialize options = {}
|
219
|
-
json_key_io = options[:json_key_io]
|
220
|
-
if json_key_io
|
221
|
-
@private_key, @issuer, @project_id, @quota_project_id, @universe_domain =
|
222
|
-
self.class.read_json_key json_key_io
|
223
|
-
else
|
224
|
-
@private_key = options.key?(:private_key) ? options[:private_key] : ENV[CredentialsLoader::PRIVATE_KEY_VAR]
|
225
|
-
@issuer = options.key?(:issuer) ? options[:issuer] : ENV[CredentialsLoader::CLIENT_EMAIL_VAR]
|
226
|
-
@project_id = options.key?(:project_id) ? options[:project_id] : ENV[CredentialsLoader::PROJECT_ID_VAR]
|
227
|
-
@quota_project_id = options[:quota_project_id] if options.key? :quota_project_id
|
228
|
-
@universe_domain = options[:universe_domain] if options.key? :universe_domain
|
229
|
-
end
|
230
|
-
@universe_domain ||= "googleapis.com"
|
231
|
-
@project_id ||= CredentialsLoader.load_gcloud_project_id
|
232
|
-
@signing_key = OpenSSL::PKey::RSA.new @private_key
|
233
|
-
@scope = options[:scope] if options.key? :scope
|
234
|
-
@logger = options[:logger] if options.key? :scope
|
235
|
-
end
|
236
|
-
|
237
|
-
# Creates a duplicate of these credentials
|
238
|
-
#
|
239
|
-
# @param options [Hash] Overrides for the credentials parameters.
|
240
|
-
# The following keys are recognized
|
241
|
-
# * `private key` the private key in string form
|
242
|
-
# * `issuer` the SA issuer
|
243
|
-
# * `scope` the scope(s) to access
|
244
|
-
# * `project_id` the project id to use during the authentication
|
245
|
-
# * `quota_project_id` the quota project id to use
|
246
|
-
# * `universe_domain` the universe domain of the credentials
|
247
|
-
def duplicate options = {}
|
248
|
-
options = deep_hash_normalize options
|
249
|
-
|
250
|
-
options = {
|
251
|
-
private_key: @private_key,
|
252
|
-
issuer: @issuer,
|
253
|
-
scope: @scope,
|
254
|
-
project_id: project_id,
|
255
|
-
quota_project_id: quota_project_id,
|
256
|
-
universe_domain: universe_domain,
|
257
|
-
logger: logger
|
258
|
-
}.merge(options)
|
259
|
-
|
260
|
-
self.class.new options
|
261
|
-
end
|
262
|
-
|
263
|
-
# Construct a jwt token if the JWT_AUD_URI key is present in the input
|
264
|
-
# hash.
|
265
|
-
#
|
266
|
-
# The jwt token is used as the value of a 'Bearer '.
|
267
|
-
def apply! a_hash, opts = {}
|
268
|
-
jwt_aud_uri = a_hash.delete JWT_AUD_URI_KEY
|
269
|
-
return a_hash if jwt_aud_uri.nil? && @scope.nil?
|
270
|
-
jwt_token = new_jwt_token jwt_aud_uri, opts
|
271
|
-
a_hash[AUTH_METADATA_KEY] = "Bearer #{jwt_token}"
|
272
|
-
logger&.debug do
|
273
|
-
hash = Digest::SHA256.hexdigest jwt_token
|
274
|
-
Google::Logging::Message.from message: "Sending JWT auth token. (sha256:#{hash})"
|
275
|
-
end
|
276
|
-
a_hash
|
277
|
-
end
|
278
|
-
|
279
|
-
# Returns a clone of a_hash updated with the authorization header
|
280
|
-
def apply a_hash, opts = {}
|
281
|
-
a_copy = a_hash.clone
|
282
|
-
apply! a_copy, opts
|
283
|
-
a_copy
|
284
|
-
end
|
285
|
-
|
286
|
-
# Returns a reference to the #apply method, suitable for passing as
|
287
|
-
# a closure
|
288
|
-
def updater_proc
|
289
|
-
proc { |a_hash, opts = {}| apply a_hash, opts }
|
290
|
-
end
|
291
|
-
|
292
|
-
# Creates a jwt uri token.
|
293
|
-
def new_jwt_token jwt_aud_uri = nil, options = {}
|
294
|
-
now = Time.new
|
295
|
-
skew = options[:skew] || 60
|
296
|
-
assertion = {
|
297
|
-
"iss" => @issuer,
|
298
|
-
"sub" => @issuer,
|
299
|
-
"exp" => (now + EXPIRY).to_i,
|
300
|
-
"iat" => (now - skew).to_i
|
301
|
-
}
|
302
|
-
|
303
|
-
jwt_aud_uri = nil if @scope
|
304
|
-
|
305
|
-
assertion["scope"] = Array(@scope).join " " if @scope
|
306
|
-
assertion["aud"] = jwt_aud_uri if jwt_aud_uri
|
307
|
-
|
308
|
-
logger&.debug do
|
309
|
-
Google::Logging::Message.from message: "JWT assertion: #{assertion}"
|
310
|
-
end
|
311
|
-
|
312
|
-
JWT.encode assertion, @signing_key, SIGNING_ALGORITHM
|
313
|
-
end
|
314
|
-
|
315
|
-
# Duck-types the corresponding method from BaseClient
|
316
|
-
def needs_access_token?
|
317
|
-
false
|
318
|
-
end
|
319
|
-
|
320
|
-
private
|
321
|
-
|
322
|
-
def deep_hash_normalize old_hash
|
323
|
-
sym_hash = {}
|
324
|
-
old_hash&.each { |k, v| sym_hash[k.to_sym] = recursive_hash_normalize_keys v }
|
325
|
-
sym_hash
|
326
|
-
end
|
327
|
-
|
328
|
-
# Convert all keys in this hash (nested) to symbols for uniform retrieval
|
329
|
-
def recursive_hash_normalize_keys val
|
330
|
-
if val.is_a? Hash
|
331
|
-
deep_hash_normalize val
|
332
|
-
else
|
333
|
-
val
|
334
|
-
end
|
335
|
-
end
|
336
|
-
end
|
337
194
|
end
|
338
195
|
end
|